From ff2be5372c12df90f344740c89fe07b10e21ca2f Mon Sep 17 00:00:00 2001 From: status-im-auto Date: Tue, 6 Sep 2022 18:31:23 +0000 Subject: [PATCH] Updates --- relay-angular-chat/3rdpartylicenses.txt | 2917 +++++++++++++++++ relay-angular-chat/favicon.ico | Bin 0 -> 948 bytes relay-angular-chat/index.html | 12 + relay-angular-chat/main.12089dc23166e9e6.js | 1 + .../runtime.85abfe8aa64fdd33.js | 1 + .../styles.ef46db3751d8e999.css | 0 relay-js | 133 + relay-reactjs-chat/asset-manifest.json | 13 + relay-reactjs-chat/favicon.ico | Bin 0 -> 3870 bytes relay-reactjs-chat/index.html | 1 + relay-reactjs-chat/logo192.png | Bin 0 -> 5347 bytes relay-reactjs-chat/logo512.png | Bin 0 -> 9664 bytes relay-reactjs-chat/manifest.json | 25 + relay-reactjs-chat/robots.txt | 3 + .../static/css/main.e6c13ad2.css | 2 + .../static/css/main.e6c13ad2.css.map | 1 + relay-reactjs-chat/static/js/main.d422f314.js | 3 + .../static/js/main.d422f314.js.LICENSE.txt | 52 + .../static/js/main.d422f314.js.map | 1 + store-js | 83 + store-reactjs-chat/asset-manifest.json | 14 + store-reactjs-chat/favicon.ico | Bin 0 -> 3870 bytes store-reactjs-chat/index.html | 1 + store-reactjs-chat/logo192.png | Bin 0 -> 5347 bytes store-reactjs-chat/logo512.png | Bin 0 -> 9664 bytes store-reactjs-chat/manifest.json | 25 + store-reactjs-chat/robots.txt | 3 + .../static/css/main.e6c13ad2.css | 2 + .../static/css/main.e6c13ad2.css.map | 1 + store-reactjs-chat/static/js/main.dce8435a.js | 3 + .../static/js/main.dce8435a.js.LICENSE.txt | 52 + .../static/js/main.dce8435a.js.map | 1 + .../static/media/rpc.93e8f6196bd2c425bf03.cjs | 1 + web-chat/asset-manifest.json | 14 + web-chat/index.html | 1 + web-chat/manifest.json | 25 + web-chat/robots.txt | 3 + web-chat/static/css/main.b267dcda.css | 2 + web-chat/static/css/main.b267dcda.css.map | 1 + web-chat/static/js/main.1d6d6520.js | 3 + .../static/js/main.1d6d6520.js.LICENSE.txt | 83 + web-chat/static/js/main.1d6d6520.js.map | 1 + .../static/media/rpc.93e8f6196bd2c425bf03.cjs | 1 + 43 files changed, 3485 insertions(+) create mode 100644 relay-angular-chat/3rdpartylicenses.txt create mode 100644 relay-angular-chat/favicon.ico create mode 100644 relay-angular-chat/index.html create mode 100644 relay-angular-chat/main.12089dc23166e9e6.js create mode 100644 relay-angular-chat/runtime.85abfe8aa64fdd33.js create mode 100644 relay-angular-chat/styles.ef46db3751d8e999.css create mode 100644 relay-js create mode 100644 relay-reactjs-chat/asset-manifest.json create mode 100644 relay-reactjs-chat/favicon.ico create mode 100644 relay-reactjs-chat/index.html create mode 100644 relay-reactjs-chat/logo192.png create mode 100644 relay-reactjs-chat/logo512.png create mode 100644 relay-reactjs-chat/manifest.json create mode 100644 relay-reactjs-chat/robots.txt create mode 100644 relay-reactjs-chat/static/css/main.e6c13ad2.css create mode 100644 relay-reactjs-chat/static/css/main.e6c13ad2.css.map create mode 100644 relay-reactjs-chat/static/js/main.d422f314.js create mode 100644 relay-reactjs-chat/static/js/main.d422f314.js.LICENSE.txt create mode 100644 relay-reactjs-chat/static/js/main.d422f314.js.map create mode 100644 store-js create mode 100644 store-reactjs-chat/asset-manifest.json create mode 100644 store-reactjs-chat/favicon.ico create mode 100644 store-reactjs-chat/index.html create mode 100644 store-reactjs-chat/logo192.png create mode 100644 store-reactjs-chat/logo512.png create mode 100644 store-reactjs-chat/manifest.json create mode 100644 store-reactjs-chat/robots.txt create mode 100644 store-reactjs-chat/static/css/main.e6c13ad2.css create mode 100644 store-reactjs-chat/static/css/main.e6c13ad2.css.map create mode 100644 store-reactjs-chat/static/js/main.dce8435a.js create mode 100644 store-reactjs-chat/static/js/main.dce8435a.js.LICENSE.txt create mode 100644 store-reactjs-chat/static/js/main.dce8435a.js.map create mode 100644 store-reactjs-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs create mode 100644 web-chat/asset-manifest.json create mode 100644 web-chat/index.html create mode 100644 web-chat/manifest.json create mode 100644 web-chat/robots.txt create mode 100644 web-chat/static/css/main.b267dcda.css create mode 100644 web-chat/static/css/main.b267dcda.css.map create mode 100644 web-chat/static/js/main.1d6d6520.js create mode 100644 web-chat/static/js/main.1d6d6520.js.LICENSE.txt create mode 100644 web-chat/static/js/main.1d6d6520.js.map create mode 100644 web-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs diff --git a/relay-angular-chat/3rdpartylicenses.txt b/relay-angular-chat/3rdpartylicenses.txt new file mode 100644 index 0000000..cb6c30f --- /dev/null +++ b/relay-angular-chat/3rdpartylicenses.txt @@ -0,0 +1,2917 @@ +@achingbrain/nat-port-mapper +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@angular/common +MIT + +@angular/core +MIT + +@angular/platform-browser +MIT + +@babel/runtime +MIT +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +@chainsafe/libp2p-gossipsub +Apache-2.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +@chainsafe/libp2p-noise +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/components +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/connection +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/crypto +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interface-connection +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interface-connection-encrypter +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interface-peer-discovery +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interface-peer-id +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interface-peer-store +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interface-pubsub +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interface-registrar +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interface-transport +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/interfaces +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/logger +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/mplex +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/multistream-select +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/peer-collections +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/peer-id +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/peer-id-factory +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/peer-record +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/peer-store +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/pubsub +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/topology +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/tracked-map +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/utils +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@libp2p/websockets +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@multiformats/mafmt +Apache-2.0 OR MIT +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + +@multiformats/multiaddr +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +@multiformats/multiaddr-to-uri +Apache-2.0 or MIT +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + +@noble/ed25519 +MIT +The MIT License (MIT) + +Copyright (c) 2019 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +@noble/secp256k1 +MIT +The MIT License (MIT) + +Copyright (c) 2019 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +@protobufjs/aspromise +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/base64 +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/codegen +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/eventemitter +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/fetch +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/float +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/inquire +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/path +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/pool +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@protobufjs/utf8 +BSD-3-Clause +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@stablelib/binary +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/chacha +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/chacha20poly1305 +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/constant-time +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +This software includes code derived from other projects: + +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +@stablelib/hash +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/hkdf +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/hmac +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/int +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/poly1305 +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +This software includes code derived from other projects: + +TweetNaCl.js +https://tweetnacl.js.org + +Public domain code written by Dmitry Chestnykh, Devi Mandiri, AndSDev, +derived from public domain code in TweetNaCl by Bernard van Gastel, +Daniel J. Bernstein, Peter Schwabe, Sjaak Smetsers, Tanja Lange, +Wesley Janssen. + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + + +Poly1305-donna +https://github.com/floodyberry/poly1305-donna + +by Andrew Moon +MIT or PUBLIC DOMAIN + + +@stablelib/random +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/sha256 +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/wipe +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +@stablelib/x25519 +MIT +This software is licensed under the MIT license: + +Copyright (C) 2016 Dmitry Chestnykh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +This software includes code derived from other projects: + + +TweetNaCl.js +https://tweetnacl.js.org + +Public domain code written by Dmitry Chestnykh, Devi Mandiri, AndSDev, +derived from public domain code in TweetNaCl by Bernard van Gastel, +Daniel J. Bernstein, Peter Schwabe, Sjaak Smetsers, Tanja Lange, +Wesley Janssen. + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + + +abortable-iterator +MIT +MIT License + +Copyright (c) 2018 Alan Shaw + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +any-signal +MIT +MIT License + +Copyright (c) 2019 Jacob Heun + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +byte-access +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +clone-regexp +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +datastore-core +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +debug +MIT +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +denque +Apache-2.0 +Copyright (c) 2018 Mike Diarmid (Salakar) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this library except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +dns-over-http-resolver +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +err-code +MIT + +event-iterator +MIT + +eventemitter3 +MIT +The MIT License (MIT) + +Copyright (c) 2014 Arnout Kazemier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +events +MIT +MIT + +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + + +fast-fifo +MIT +The MIT License (MIT) + +Copyright (c) 2019 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +function-timeout +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +get-iterator +MIT +MIT License + +Copyright (c) 2018 Alan Shaw + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +hashlru +MIT +Copyright (c) 2016 'Dominic Tarr' + +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software and +associated documentation files (the "Software"), to +deal in the Software without restriction, including +without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom +the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +interface-datastore +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +ip-regex +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +ipaddr.js +MIT +Copyright (C) 2011-2017 whitequark + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +is-electron +MIT +The MIT License (MIT) + +Copyright (c) 2016-2018 Cheton Wu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +is-ip +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +is-loopback-addr +MIT +MIT License + +Copyright (c) 2020 Vasco Santos + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +is-plain-obj +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +is-regexp +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +iso-url +MIT +MIT License + +Copyright (c) Hugo Dias (hugodias.me) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +it-all +ISC + +it-drain +ISC + +it-filter +ISC + +it-first +ISC + +it-foreach +ISC + +it-handshake +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +it-length-prefixed +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +it-map +ISC + +it-merge +ISC + +it-pair +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +it-pb-stream +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +it-pipe +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +it-pushable +MIT +MIT License + +Copyright (c) 2019 Alan Shaw + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +it-reader +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +it-sort +ISC + +it-take +ISC + +it-ws +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +js-sha3 +MIT +Copyright 2015-2018 Chen, Yi-Cyuan + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +js-waku +MIT OR Apache-2.0 + +libp2p +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +longbits +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +merge-options +MIT +The MIT License (MIT) + +Copyright (c) Michael Mayer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +mortice +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +ms +MIT +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +multiformats +(Apache-2.0 AND MIT) +Copyright 2020 Protocol Labs + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +mutable-proxy +MIT +The MIT License (MIT) +Copyright (c) 2016 John Griffing + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +nanoid +MIT +The MIT License (MIT) + +Copyright 2017 Andrey Sitnik + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +native-fetch +MIT + +netmask +MIT + +node-forge +(BSD-3-Clause OR GPL-2.0) +You may use the Forge project under the terms of either the BSD License or the +GNU General Public License (GPL) Version 2. + +The BSD License is recommended for most projects. It is simple and easy to +understand and it places almost no restrictions on what you can do with the +Forge project. + +If the GPL suits your project better you are also free to use Forge under +that license. + +You don't have to do anything special to choose one license or the other and +you don't have to notify anyone which license you are using. You are free to +use this project in commercial projects as long as the copyright header is +left intact. + +If you are a commercial entity and use this set of libraries in your +commercial software then reasonable payment to Digital Bazaar, if you can +afford it, is not required but is expected and would be appreciated. If this +library saves you time, then it's saving you money. The cost of developing +the Forge software was on the order of several hundred hours and tens of +thousands of dollars. We are attempting to strike a balance between helping +the development community while not being taken advantage of by lucrative +commercial entities for our efforts. + +------------------------------------------------------------------------------- +New BSD License (3-clause) +Copyright (c) 2010, Digital Bazaar, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Digital Bazaar, Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL DIGITAL BAZAAR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------- + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + 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 +this service 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. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + + +observable-webworkers +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +p-defer +MIT +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +p-event +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +p-fifo +MIT +MIT License + +Copyright (c) 2019 Alan Shaw + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +p-limit +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +p-queue +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +p-reflect +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +p-settle +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +p-timeout +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +private-ip +MIT +The MIT License (MIT) + +Copyright (c) 2016 Damir Mustafin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +protobufjs +BSD-3-Clause +This license applies to all parts of protobuf.js except those files +either explicitly including or referencing a different license or +located in a directory containing a different LICENSE file. + +--- + +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--- + +Code generated by the command line utilities is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. + + +protons-runtime +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +receptacle +MIT + +retimer +MIT +The MIT License (MIT) + +Copyright (c) 2015 Matteo Collina + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +rxjs +Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) 2015-2018 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +sanitize-filename +WTFPL OR ISC +This project is licensed under the [WTFPL][] and [ISC][] licenses. + +[WTFPL]: https://en.wikipedia.org/wiki/WTFPL +[ISC]: https://opensource.org/licenses/ISC + +## WTFPL + +DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE +Version 2, December 2004 + +Copyright (C) 2004 Sam Hocevar \ + +Everyone is permitted to copy and distribute verbatim or modified copies +of this license document, and changing it is allowed as long as the name +is changed. + +DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR +COPYING, DISTRIBUTION AND MODIFICATION + +0. You just DO WHAT THE FUCK YOU WANT TO. + +## ISC + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +set-delayed-interval +MIT +MIT License + +Copyright (c) 2020 Vasco Santos + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +super-regex +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +timeout-abort-controller +MIT +MIT License + +Copyright (c) 2019 Jacob Heun + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +truncate-utf8-bytes +WTFPL + +tslib +0BSD +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +uint8-varint +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +uint8arraylist +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +uint8arrays +MIT + +utf8-byte-length +WTFPL + +uuid +MIT +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +varint +MIT + +wherearewe +Apache-2.0 OR MIT +This project is dual licensed under MIT and Apache-2.0. + +MIT: https://www.opensource.org/licenses/mit +Apache-2.0: https://www.apache.org/licenses/license-2.0 + + +yocto-queue +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +zone.js +MIT +The MIT License + +Copyright (c) 2010-2022 Google LLC. https://angular.io/license + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/relay-angular-chat/favicon.ico b/relay-angular-chat/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..997406ad22c29aae95893fb3d666c30258a09537 GIT binary patch literal 948 zcmV;l155mgP)CBYU7IjCFmI-B}4sMJt3^s9NVg!P0 z6hDQy(L`XWMkB@zOLgN$4KYz;j0zZxq9KKdpZE#5@k0crP^5f9KO};h)ZDQ%ybhht z%t9#h|nu0K(bJ ztIkhEr!*UyrZWQ1k2+YkGqDi8Z<|mIN&$kzpKl{cNP=OQzXHz>vn+c)F)zO|Bou>E z2|-d_=qY#Y+yOu1a}XI?cU}%04)zz%anD(XZC{#~WreV!a$7k2Ug`?&CUEc0EtrkZ zL49MB)h!_K{H(*l_93D5tO0;BUnvYlo+;yss%n^&qjt6fZOa+}+FDO(~2>G z2dx@=JZ?DHP^;b7*Y1as5^uphBsh*s*z&MBd?e@I>-9kU>63PjP&^#5YTOb&x^6Cf z?674rmSHB5Fk!{Gv7rv!?qX#ei_L(XtwVqLX3L}$MI|kJ*w(rhx~tc&L&xP#?cQow zX_|gx$wMr3pRZIIr_;;O|8fAjd;1`nOeu5K(pCu7>^3E&D2OBBq?sYa(%S?GwG&_0-s%_v$L@R!5H_fc)lOb9ZoOO#p`Nn`KU z3LTTBtjwo`7(HA6 z7gmO$yTR!5L>Bsg!X8616{JUngg_@&85%>W=mChTR;x4`P=?PJ~oPuy5 zU-L`C@_!34D21{fD~Y8NVnR3t;aqZI3fIhmgmx}$oc-dKDC6Ap$Gy>a!`A*x2L1v0 WcZ@i?LyX}70000 + + RelayAngularChat + + + + + + + + + \ No newline at end of file diff --git a/relay-angular-chat/main.12089dc23166e9e6.js b/relay-angular-chat/main.12089dc23166e9e6.js new file mode 100644 index 0000000..533fdd1 --- /dev/null +++ b/relay-angular-chat/main.12089dc23166e9e6.js @@ -0,0 +1 @@ +(self.webpackChunkrelay_angular_chat=self.webpackChunkrelay_angular_chat||[]).push([[179],{1873:(J,G,N)=>{"use strict";J.exports=N(4729)},4729:(J,G,N)=>{"use strict";var h=G;function u(){h.util._configure(),h.Writer._configure(h.BufferWriter),h.Reader._configure(h.BufferReader)}h.build="minimal",h.Writer=N(3542),h.BufferWriter=N(989),h.Reader=N(6913),h.BufferReader=N(1872),h.util=N(6138),h.rpc=N(9852),h.roots=N(935),h.configure=u,u()},6913:(J,G,N)=>{"use strict";J.exports=v;var u,h=N(6138),g=h.LongBits,b=h.utf8;function w(E,y){return RangeError("index out of range: "+E.pos+" + "+(y||1)+" > "+E.len)}function v(E){this.buf=E,this.pos=0,this.len=E.length}var y,l=typeof Uint8Array<"u"?function(y){if(y instanceof Uint8Array||Array.isArray(y))return new v(y);throw Error("illegal buffer")}:function(y){if(Array.isArray(y))return new v(y);throw Error("illegal buffer")},p=function(){return h.Buffer?function(f){return(v.create=function(A){return h.Buffer.isBuffer(A)?new u(A):l(A)})(f)}:l};function d(){var E=new g(0,0),y=0;if(!(this.len-this.pos>4)){for(;y<3;++y){if(this.pos>=this.len)throw w(this);if(E.lo=(E.lo|(127&this.buf[this.pos])<<7*y)>>>0,this.buf[this.pos++]<128)return E}return E.lo=(E.lo|(127&this.buf[this.pos++])<<7*y)>>>0,E}for(;y<4;++y)if(E.lo=(E.lo|(127&this.buf[this.pos])<<7*y)>>>0,this.buf[this.pos++]<128)return E;if(E.lo=(E.lo|(127&this.buf[this.pos])<<28)>>>0,E.hi=(E.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return E;if(y=0,this.len-this.pos>4){for(;y<5;++y)if(E.hi=(E.hi|(127&this.buf[this.pos])<<7*y+3)>>>0,this.buf[this.pos++]<128)return E}else for(;y<5;++y){if(this.pos>=this.len)throw w(this);if(E.hi=(E.hi|(127&this.buf[this.pos])<<7*y+3)>>>0,this.buf[this.pos++]<128)return E}throw Error("invalid varint encoding")}function _(E,y){return(E[y-4]|E[y-3]<<8|E[y-2]<<16|E[y-1]<<24)>>>0}function I(){if(this.pos+8>this.len)throw w(this,8);return new g(_(this.buf,this.pos+=4),_(this.buf,this.pos+=4))}v.create=p(),v.prototype._slice=h.Array.prototype.subarray||h.Array.prototype.slice,v.prototype.uint32=(y=4294967295,function(){if(y=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(y=(y|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(y=(y|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(y=(y|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(y=(y|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return y;if((this.pos+=5)>this.len)throw this.pos=this.len,w(this,10);return y}),v.prototype.int32=function(){return 0|this.uint32()},v.prototype.sint32=function(){var y=this.uint32();return y>>>1^-(1&y)|0},v.prototype.bool=function(){return 0!==this.uint32()},v.prototype.fixed32=function(){if(this.pos+4>this.len)throw w(this,4);return _(this.buf,this.pos+=4)},v.prototype.sfixed32=function(){if(this.pos+4>this.len)throw w(this,4);return 0|_(this.buf,this.pos+=4)},v.prototype.float=function(){if(this.pos+4>this.len)throw w(this,4);var y=h.float.readFloatLE(this.buf,this.pos);return this.pos+=4,y},v.prototype.double=function(){if(this.pos+8>this.len)throw w(this,4);var y=h.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,y},v.prototype.bytes=function(){var y=this.uint32(),f=this.pos,C=this.pos+y;if(C>this.len)throw w(this,y);return this.pos+=y,Array.isArray(this.buf)?this.buf.slice(f,C):f===C?new this.buf.constructor(0):this._slice.call(this.buf,f,C)},v.prototype.string=function(){var y=this.bytes();return b.read(y,0,y.length)},v.prototype.skip=function(y){if("number"==typeof y){if(this.pos+y>this.len)throw w(this,y);this.pos+=y}else do{if(this.pos>=this.len)throw w(this)}while(128&this.buf[this.pos++]);return this},v.prototype.skipType=function(E){switch(E){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(E=7&this.uint32());)this.skipType(E);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+E+" at offset "+this.pos)}return this},v._configure=function(E){u=E,v.create=p(),u._configure();var y=h.Long?"toLong":"toNumber";h.merge(v.prototype,{int64:function(){return d.call(this)[y](!1)},uint64:function(){return d.call(this)[y](!0)},sint64:function(){return d.call(this).zzDecode()[y](!1)},fixed64:function(){return I.call(this)[y](!0)},sfixed64:function(){return I.call(this)[y](!1)}})}},1872:(J,G,N)=>{"use strict";J.exports=g;var h=N(6913);(g.prototype=Object.create(h.prototype)).constructor=g;var u=N(6138);function g(b){h.call(this,b)}g._configure=function(){u.Buffer&&(g.prototype._slice=u.Buffer.prototype.slice)},g.prototype.string=function(){var w=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+w,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+w,this.len))},g._configure()},935:J=>{"use strict";J.exports={}},9852:(J,G,N)=>{"use strict";G.Service=N(3939)},3939:(J,G,N)=>{"use strict";J.exports=u;var h=N(6138);function u(g,b,w){if("function"!=typeof g)throw TypeError("rpcImpl must be a function");h.EventEmitter.call(this),this.rpcImpl=g,this.requestDelimited=Boolean(b),this.responseDelimited=Boolean(w)}(u.prototype=Object.create(h.EventEmitter.prototype)).constructor=u,u.prototype.rpcCall=function g(b,w,v,l,p){if(!l)throw TypeError("request must be specified");var d=this;if(!p)return h.asPromise(g,d,b,w,v,l);if(d.rpcImpl)try{return d.rpcImpl(b,w[d.requestDelimited?"encodeDelimited":"encode"](l).finish(),function(I,E){if(I)return d.emit("error",I,b),p(I);if(null!==E){if(!(E instanceof v))try{E=v[d.responseDelimited?"decodeDelimited":"decode"](E)}catch(y){return d.emit("error",y,b),p(y)}return d.emit("data",E,b),p(null,E)}d.end(!0)})}catch(_){return d.emit("error",_,b),void setTimeout(function(){p(_)},0)}else setTimeout(function(){p(Error("already ended"))},0)},u.prototype.end=function(b){return this.rpcImpl&&(b||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},6723:(J,G,N)=>{"use strict";J.exports=u;var h=N(6138);function u(v,l){this.lo=v>>>0,this.hi=l>>>0}var g=u.zero=new u(0,0);g.toNumber=function(){return 0},g.zzEncode=g.zzDecode=function(){return this},g.length=function(){return 1};var b=u.zeroHash="\0\0\0\0\0\0\0\0";u.fromNumber=function(l){if(0===l)return g;var p=l<0;p&&(l=-l);var d=l>>>0,_=(l-d)/4294967296>>>0;return p&&(_=~_>>>0,d=~d>>>0,++d>4294967295&&(d=0,++_>4294967295&&(_=0))),new u(d,_)},u.from=function(l){if("number"==typeof l)return u.fromNumber(l);if(h.isString(l)){if(!h.Long)return u.fromNumber(parseInt(l,10));l=h.Long.fromString(l)}return l.low||l.high?new u(l.low>>>0,l.high>>>0):g},u.prototype.toNumber=function(l){if(!l&&this.hi>>>31){var p=1+~this.lo>>>0,d=~this.hi>>>0;return p||(d=d+1>>>0),-(p+4294967296*d)}return this.lo+4294967296*this.hi},u.prototype.toLong=function(l){return h.Long?new h.Long(0|this.lo,0|this.hi,Boolean(l)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(l)}};var w=String.prototype.charCodeAt;u.fromHash=function(l){return l===b?g:new u((w.call(l,0)|w.call(l,1)<<8|w.call(l,2)<<16|w.call(l,3)<<24)>>>0,(w.call(l,4)|w.call(l,5)<<8|w.call(l,6)<<16|w.call(l,7)<<24)>>>0)},u.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},u.prototype.zzEncode=function(){var l=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^l)>>>0,this.lo=(this.lo<<1^l)>>>0,this},u.prototype.zzDecode=function(){var l=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^l)>>>0,this.hi=(this.hi>>>1^l)>>>0,this},u.prototype.length=function(){var l=this.lo,p=(this.lo>>>28|this.hi<<4)>>>0,d=this.hi>>>24;return 0===d?0===p?l<16384?l<128?1:2:l<2097152?3:4:p<16384?p<128?5:6:p<2097152?7:8:d<128?9:10}},6138:function(J,G,N){"use strict";var h=G;function u(b,w,v){for(var l=Object.keys(w),p=0;p0)},h.Buffer=function(){try{var b=h.inquire("buffer").Buffer;return b.prototype.utf8Write?b:null}catch{return null}}(),h._Buffer_from=null,h._Buffer_allocUnsafe=null,h.newBuffer=function(w){return"number"==typeof w?h.Buffer?h._Buffer_allocUnsafe(w):new h.Array(w):h.Buffer?h._Buffer_from(w):typeof Uint8Array>"u"?w:new Uint8Array(w)},h.Array=typeof Uint8Array<"u"?Uint8Array:Array,h.Long=h.global.dcodeIO&&h.global.dcodeIO.Long||h.global.Long||h.inquire("long"),h.key2Re=/^true|false|0|1$/,h.key32Re=/^-?(?:0|[1-9][0-9]*)$/,h.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,h.longToHash=function(w){return w?h.LongBits.from(w).toHash():h.LongBits.zeroHash},h.longFromHash=function(w,v){var l=h.LongBits.fromHash(w);return h.Long?h.Long.fromBits(l.lo,l.hi,v):l.toNumber(Boolean(v))},h.merge=u,h.lcFirst=function(w){return w.charAt(0).toLowerCase()+w.substring(1)},h.newError=g,h.ProtocolError=g("ProtocolError"),h.oneOfGetter=function(w){for(var v={},l=0;l-1;--d)if(1===v[p[d]]&&null!=this[p[d]])return p[d]}},h.oneOfSetter=function(w){return function(v){for(var l=0;l{"use strict";J.exports=d;var u,h=N(6138),g=h.LongBits,b=h.base64,w=h.utf8;function v(P,D,x){this.fn=P,this.len=D,this.next=void 0,this.val=x}function l(){}function p(P){this.head=P.head,this.tail=P.tail,this.len=P.len,this.next=P.states}function d(){this.len=0,this.head=new v(l,0,0),this.tail=this.head,this.states=null}var _=function(){return h.Buffer?function(){return(d.create=function(){return new u})()}:function(){return new d}};function I(P,D,x){D[x]=255&P}function y(P,D){this.len=P,this.next=void 0,this.val=D}function f(P,D,x){for(;P.hi;)D[x++]=127&P.lo|128,P.lo=(P.lo>>>7|P.hi<<25)>>>0,P.hi>>>=7;for(;P.lo>127;)D[x++]=127&P.lo|128,P.lo=P.lo>>>7;D[x++]=P.lo}function C(P,D,x){D[x]=255&P,D[x+1]=P>>>8&255,D[x+2]=P>>>16&255,D[x+3]=P>>>24}d.create=_(),d.alloc=function(D){return new h.Array(D)},h.Array!==Array&&(d.alloc=h.pool(d.alloc,h.Array.prototype.subarray)),d.prototype._push=function(D,x,M){return this.tail=this.tail.next=new v(D,x,M),this.len+=x,this},(y.prototype=Object.create(v.prototype)).fn=function E(P,D,x){for(;P>127;)D[x++]=127&P|128,P>>>=7;D[x]=P},d.prototype.uint32=function(D){return this.len+=(this.tail=this.tail.next=new y((D>>>=0)<128?1:D<16384?2:D<2097152?3:D<268435456?4:5,D)).len,this},d.prototype.int32=function(D){return D<0?this._push(f,10,g.fromNumber(D)):this.uint32(D)},d.prototype.sint32=function(D){return this.uint32((D<<1^D>>31)>>>0)},d.prototype.int64=d.prototype.uint64=function(D){var x=g.from(D);return this._push(f,x.length(),x)},d.prototype.sint64=function(D){var x=g.from(D).zzEncode();return this._push(f,x.length(),x)},d.prototype.bool=function(D){return this._push(I,1,D?1:0)},d.prototype.sfixed32=d.prototype.fixed32=function(D){return this._push(C,4,D>>>0)},d.prototype.sfixed64=d.prototype.fixed64=function(D){var x=g.from(D);return this._push(C,4,x.lo)._push(C,4,x.hi)},d.prototype.float=function(D){return this._push(h.float.writeFloatLE,4,D)},d.prototype.double=function(D){return this._push(h.float.writeDoubleLE,8,D)};var A=h.Array.prototype.set?function(D,x,M){x.set(D,M)}:function(D,x,M){for(var B=0;B>>0;if(!x)return this._push(I,1,0);if(h.isString(D)){var M=d.alloc(x=b.length(D));b.decode(D,M,0),D=M}return this.uint32(x)._push(A,x,D)},d.prototype.string=function(D){var x=w.length(D);return x?this.uint32(x)._push(w.write,x,D):this._push(I,1,0)},d.prototype.fork=function(){return this.states=new p(this),this.head=this.tail=new v(l,0,0),this.len=0,this},d.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new v(l,0,0),this.len=0),this},d.prototype.ldelim=function(){var D=this.head,x=this.tail,M=this.len;return this.reset().uint32(M),M&&(this.tail.next=D.next,this.tail=x,this.len+=M),this},d.prototype.finish=function(){for(var D=this.head.next,x=this.constructor.alloc(this.len),M=0;D;)D.fn(D.val,x,M),M+=D.len,D=D.next;return x},d._configure=function(P){u=P,d.create=_(),u._configure()}},989:(J,G,N)=>{"use strict";J.exports=g;var h=N(3542);(g.prototype=Object.create(h.prototype)).constructor=g;var u=N(6138);function g(){h.call(this)}function b(w,v,l){w.length<40?u.utf8.write(w,v,l):v.utf8Write?v.utf8Write(w,l):v.write(w,l)}g._configure=function(){g.alloc=u._Buffer_allocUnsafe,g.writeBytesBuffer=u.Buffer&&u.Buffer.prototype instanceof Uint8Array&&"set"===u.Buffer.prototype.set.name?function(v,l,p){l.set(v,p)}:function(v,l,p){if(v.copy)v.copy(l,p,0,v.length);else for(var d=0;d>>0;return this.uint32(l),l&&this._push(g.writeBytesBuffer,l,v),this},g.prototype.string=function(v){var l=u.Buffer.byteLength(v);return this.uint32(l),l&&this._push(b,l,v),this},g._configure()},623:(J,G,N)=>{"use strict";var h={};N.r(h),N.d(h,{identity:()=>cF});var u={};N.r(u),N.d(u,{base2:()=>uF});var g={};N.r(g),N.d(g,{base8:()=>lF});var b={};N.r(b),N.d(b,{base10:()=>fF});var w={};N.r(w),N.d(w,{base16:()=>dF,base16upper:()=>hF});var v={};N.r(v),N.d(v,{base32:()=>Ro,base32hex:()=>mF,base32hexpad:()=>EF,base32hexpadupper:()=>wF,base32hexupper:()=>vF,base32pad:()=>gF,base32padupper:()=>yF,base32upper:()=>pF,base32z:()=>bF});var l={};N.r(l),N.d(l,{base36:()=>_F,base36upper:()=>DF});var p={};N.r(p),N.d(p,{base58btc:()=>Ci,base58flickr:()=>SF});var d={};N.r(d),N.d(d,{base64:()=>Lh,base64pad:()=>IF,base64url:()=>CF,base64urlpad:()=>TF});var _={};N.r(_),N.d(_,{base256emoji:()=>NF});var I={};N.r(I),N.d(I,{sha256:()=>Li,sha512:()=>JF});var E={};N.r(E),N.d(E,{identity:()=>gu});var y={};N.r(y),N.d(y,{code:()=>nU,decode:()=>iU,encode:()=>rU,name:()=>tU});var f={};N.r(f),N.d(f,{code:()=>cU,decode:()=>lU,encode:()=>uU,name:()=>aU});var C={};N.r(C),N.d(C,{RsaPrivateKey:()=>qh,RsaPublicKey:()=>Ym,fromJwk:()=>eV,generateKeyPair:()=>tV,unmarshalRsaPrivateKey:()=>XU,unmarshalRsaPublicKey:()=>JU});var A={};N.r(A),N.d(A,{Ed25519PrivateKey:()=>ff,Ed25519PublicKey:()=>mv,generateKeyPair:()=>CV,generateKeyPairFromSeed:()=>TV,unmarshalEd25519PrivateKey:()=>SV,unmarshalEd25519PublicKey:()=>IV});var P={};function D(n){return"function"==typeof n}function x(n){const t=n(r=>{Error.call(r),r.stack=(new Error).stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}N.r(P),N.d(P,{Secp256k1PrivateKey:()=>Dv,Secp256k1PublicKey:()=>_v,generateKeyPair:()=>kV,unmarshalSecp256k1PrivateKey:()=>OV,unmarshalSecp256k1PublicKey:()=>LV});const M=x(n=>function(t){n(this),this.message=t?`${t.length} errors occurred during unsubscription:\n${t.map((r,i)=>`${i+1}) ${r.toString()}`).join("\n ")}`:"",this.name="UnsubscriptionError",this.errors=t});function B(n,e){if(n){const t=n.indexOf(e);0<=t&&n.splice(t,1)}}class F{constructor(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}unsubscribe(){let e;if(!this.closed){this.closed=!0;const{_parentage:t}=this;if(t)if(this._parentage=null,Array.isArray(t))for(const s of t)s.remove(this);else t.remove(this);const{initialTeardown:r}=this;if(D(r))try{r()}catch(s){e=s instanceof M?s.errors:[s]}const{_finalizers:i}=this;if(i){this._finalizers=null;for(const s of i)try{O(s)}catch(o){e=e??[],o instanceof M?e=[...e,...o.errors]:e.push(o)}}if(e)throw new M(e)}}add(e){var t;if(e&&e!==this)if(this.closed)O(e);else{if(e instanceof F){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(t=this._finalizers)&&void 0!==t?t:[]).push(e)}}_hasParent(e){const{_parentage:t}=this;return t===e||Array.isArray(t)&&t.includes(e)}_addParent(e){const{_parentage:t}=this;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e}_removeParent(e){const{_parentage:t}=this;t===e?this._parentage=null:Array.isArray(t)&&B(t,e)}remove(e){const{_finalizers:t}=this;t&&B(t,e),e instanceof F&&e._removeParent(this)}}F.EMPTY=(()=>{const n=new F;return n.closed=!0,n})();const z=F.EMPTY;function S(n){return n instanceof F||n&&"closed"in n&&D(n.remove)&&D(n.add)&&D(n.unsubscribe)}function O(n){D(n)?n():n.unsubscribe()}const H={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},L={setTimeout(n,e,...t){const{delegate:r}=L;return r?.setTimeout?r.setTimeout(n,e,...t):setTimeout(n,e,...t)},clearTimeout(n){const{delegate:e}=L;return(e?.clearTimeout||clearTimeout)(n)},delegate:void 0};function j(n){L.setTimeout(()=>{const{onUnhandledError:e}=H;if(!e)throw n;e(n)})}function re(){}const $=q("C",void 0,void 0);function q(n,e,t){return{kind:n,value:e,error:t}}let ne=null;function oe(n){if(H.useDeprecatedSynchronousErrorHandling){const e=!ne;if(e&&(ne={errorThrown:!1,error:null}),n(),e){const{errorThrown:t,error:r}=ne;if(ne=null,t)throw r}}else n()}class pe extends F{constructor(e){super(),this.isStopped=!1,e?(this.destination=e,S(e)&&e.add(this)):this.destination=Ce}static create(e,t,r){return new we(e,t,r)}next(e){this.isStopped?Ee(function Z(n){return q("N",n,void 0)}(e),this):this._next(e)}error(e){this.isStopped?Ee(function te(n){return q("E",void 0,n)}(e),this):(this.isStopped=!0,this._error(e))}complete(){this.isStopped?Ee($,this):(this.isStopped=!0,this._complete())}unsubscribe(){this.closed||(this.isStopped=!0,super.unsubscribe(),this.destination=null)}_next(e){this.destination.next(e)}_error(e){try{this.destination.error(e)}finally{this.unsubscribe()}}_complete(){try{this.destination.complete()}finally{this.unsubscribe()}}}const ke=Function.prototype.bind;function Se(n,e){return ke.call(n,e)}class Pe{constructor(e){this.partialObserver=e}next(e){const{partialObserver:t}=this;if(t.next)try{t.next(e)}catch(r){$e(r)}}error(e){const{partialObserver:t}=this;if(t.error)try{t.error(e)}catch(r){$e(r)}else $e(e)}complete(){const{partialObserver:e}=this;if(e.complete)try{e.complete()}catch(t){$e(t)}}}class we extends pe{constructor(e,t,r){let i;if(super(),D(e)||!e)i={next:e??void 0,error:t??void 0,complete:r??void 0};else{let s;this&&H.useDeprecatedNextContext?(s=Object.create(e),s.unsubscribe=()=>this.unsubscribe(),i={next:e.next&&Se(e.next,s),error:e.error&&Se(e.error,s),complete:e.complete&&Se(e.complete,s)}):i=e}this.destination=new Pe(i)}}function $e(n){H.useDeprecatedSynchronousErrorHandling?function de(n){H.useDeprecatedSynchronousErrorHandling&&ne&&(ne.errorThrown=!0,ne.error=n)}(n):j(n)}function Ee(n,e){const{onStoppedNotification:t}=H;t&&L.setTimeout(()=>t(n,e))}const Ce={closed:!0,next:re,error:function K(n){throw n},complete:re},xe="function"==typeof Symbol&&Symbol.observable||"@@observable";function Ke(n){return n}let Xe=(()=>{class n{constructor(t){t&&(this._subscribe=t)}lift(t){const r=new n;return r.source=this,r.operator=t,r}subscribe(t,r,i){const s=function Dt(n){return n&&n instanceof pe||function pt(n){return n&&D(n.next)&&D(n.error)&&D(n.complete)}(n)&&S(n)}(t)?t:new we(t,r,i);return oe(()=>{const{operator:o,source:a}=this;s.add(o?o.call(s,a):a?this._subscribe(s):this._trySubscribe(s))}),s}_trySubscribe(t){try{return this._subscribe(t)}catch(r){t.error(r)}}forEach(t,r){return new(r=Ot(r))((i,s)=>{const o=new we({next:a=>{try{t(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:i});this.subscribe(o)})}_subscribe(t){var r;return null===(r=this.source)||void 0===r?void 0:r.subscribe(t)}[xe](){return this}pipe(...t){return function Je(n){return 0===n.length?Ke:1===n.length?n[0]:function(t){return n.reduce((r,i)=>i(r),t)}}(t)(this)}toPromise(t){return new(t=Ot(t))((r,i)=>{let s;this.subscribe(o=>s=o,o=>i(o),()=>r(s))})}}return n.create=e=>new n(e),n})();function Ot(n){var e;return null!==(e=n??H.Promise)&&void 0!==e?e:Promise}const Wr=x(n=>function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"});let Sr=(()=>{class n extends Xe{constructor(){super(),this.closed=!1,this.currentObservers=null,this.observers=[],this.isStopped=!1,this.hasError=!1,this.thrownError=null}lift(t){const r=new ni(this,this);return r.operator=t,r}_throwIfClosed(){if(this.closed)throw new Wr}next(t){oe(()=>{if(this._throwIfClosed(),!this.isStopped){this.currentObservers||(this.currentObservers=Array.from(this.observers));for(const r of this.currentObservers)r.next(t)}})}error(t){oe(()=>{if(this._throwIfClosed(),!this.isStopped){this.hasError=this.isStopped=!0,this.thrownError=t;const{observers:r}=this;for(;r.length;)r.shift().error(t)}})}complete(){oe(()=>{if(this._throwIfClosed(),!this.isStopped){this.isStopped=!0;const{observers:t}=this;for(;t.length;)t.shift().complete()}})}unsubscribe(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null}get observed(){var t;return(null===(t=this.observers)||void 0===t?void 0:t.length)>0}_trySubscribe(t){return this._throwIfClosed(),super._trySubscribe(t)}_subscribe(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)}_innerSubscribe(t){const{hasError:r,isStopped:i,observers:s}=this;return r||i?z:(this.currentObservers=null,s.push(t),new F(()=>{this.currentObservers=null,B(s,t)}))}_checkFinalizedStatuses(t){const{hasError:r,thrownError:i,isStopped:s}=this;r?t.error(i):s&&t.complete()}asObservable(){const t=new Xe;return t.source=this,t}}return n.create=(e,t)=>new ni(e,t),n})();class ni extends Sr{constructor(e,t){super(),this.destination=e,this.source=t}next(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)}error(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)}complete(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)}_subscribe(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:z}}function fe(n){return e=>{if(function ie(n){return D(n?.lift)}(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function ye(n,e,t,r,i){return new me(n,e,t,r,i)}class me extends pe{constructor(e,t,r,i,s,o){super(e),this.onFinalize=s,this.shouldUnsubscribe=o,this._next=t?function(a){try{t(a)}catch(c){e.error(c)}}:super._next,this._error=i?function(a){try{i(a)}catch(c){e.error(c)}finally{this.unsubscribe()}}:super._error,this._complete=r?function(){try{r()}catch(a){e.error(a)}finally{this.unsubscribe()}}:super._complete}unsubscribe(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){const{closed:t}=this;super.unsubscribe(),!t&&(null===(e=this.onFinalize)||void 0===e||e.call(this))}}}function Bt(n){return this instanceof Bt?(this.v=n,this):new Bt(n)}function yn(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=t.apply(n,e||[]),s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(k){r[k]&&(i[k]=function(U){return new Promise(function(Q,X){s.push([k,U,Q,X])>1||a(k,U)})})}function a(k,U){try{!function c(k){k.value instanceof Bt?Promise.resolve(k.value.v).then(m,T):R(s[0][2],k)}(r[k](U))}catch(Q){R(s[0][3],Q)}}function m(k){a("next",k)}function T(k){a("throw",k)}function R(k,U){k(U),s.shift(),s.length&&a(s[0][0],s[0][1])}}function ft(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,e=n[Symbol.asyncIterator];return e?e.call(n):(n=function dt(n){var e="function"==typeof Symbol&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&"number"==typeof n.length)return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(n),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(o){return new Promise(function(a,c){!function i(s,o,a,c){Promise.resolve(c).then(function(m){s({value:m,done:a})},o)}(a,c,(o=n[s](o)).done,o.value)})}}}const bn=n=>n&&"number"==typeof n.length&&"function"!=typeof n;function vr(n){return D(n?.then)}function rr(n){return D(n[xe])}function _n(n){return Symbol.asyncIterator&&D(n?.[Symbol.asyncIterator])}function Ft(n){return new TypeError(`You provided ${null!==n&&"object"==typeof n?"an invalid object":`'${n}'`} where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`)}const ce=function ut(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}();function ve(n){return D(n?.[ce])}function yt(n){return yn(this,arguments,function*(){const t=n.getReader();try{for(;;){const{value:r,done:i}=yield Bt(t.read());if(i)return yield Bt(void 0);yield yield Bt(r)}}finally{t.releaseLock()}})}function St(n){return D(n?.getReader)}function mn(n){if(n instanceof Xe)return n;if(null!=n){if(rr(n))return function Ge(n){return new Xe(e=>{const t=n[xe]();if(D(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}(n);if(bn(n))return function Qe(n){return new Xe(e=>{for(let t=0;t{n.then(t=>{e.closed||(e.next(t),e.complete())},t=>e.error(t)).then(null,j)})}(n);if(_n(n))return ht(n);if(ve(n))return function ze(n){return new Xe(e=>{for(const t of n)if(e.next(t),e.closed)return;e.complete()})}(n);if(St(n))return function Et(n){return ht(yt(n))}(n)}throw Ft(n)}function ht(n){return new Xe(e=>{(function lt(n,e){var t,r,i,s;return function ge(n,e,t,r){return new(t||(t=Promise))(function(s,o){function a(T){try{m(r.next(T))}catch(R){o(R)}}function c(T){try{m(r.throw(T))}catch(R){o(R)}}function m(T){T.done?s(T.value):function i(s){return s instanceof t?s:new t(function(o){o(s)})}(T.value).then(a,c)}m((r=r.apply(n,e||[])).next())})}(this,void 0,void 0,function*(){try{for(t=ft(n);!(r=yield t.next()).done;)if(e.next(r.value),e.closed)return}catch(o){i={error:o}}finally{try{r&&!r.done&&(s=t.return)&&(yield s.call(t))}finally{if(i)throw i.error}}e.complete()})})(n,e).catch(t=>e.error(t))})}function It(n,e,t,r=0,i=!1){const s=e.schedule(function(){t(),i?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!i)return s}function Ut(n,e,t=1/0){return D(e)?Ut((r,i)=>function _e(n,e){return fe((t,r)=>{let i=0;t.subscribe(ye(r,s=>{r.next(n.call(e,s,i++))}))})}((s,o)=>e(r,s,i,o))(mn(n(r,i))),t):("number"==typeof e&&(t=e),fe((r,i)=>function jt(n,e,t,r,i,s,o,a){const c=[];let m=0,T=0,R=!1;const k=()=>{R&&!c.length&&!m&&e.complete()},U=X=>m{s&&e.next(X),m++;let ae=!1;mn(t(X,T++)).subscribe(ye(e,he=>{i?.(he),s?U(he):e.next(he)},()=>{ae=!0},void 0,()=>{if(ae)try{for(m--;c.length&&mQ(he)):Q(he)}k()}catch(he){e.error(he)}}))};return n.subscribe(ye(e,U,()=>{R=!0,k()})),()=>{a?.()}}(r,i,n,t)))}const Tn=new Xe(n=>n.complete());function Zo(n){return n[n.length-1]}function Y(n,e=0){return fe((t,r)=>{t.subscribe(ye(r,i=>It(r,n,()=>r.next(i),e),()=>It(r,n,()=>r.complete(),e),i=>It(r,n,()=>r.error(i),e)))})}function ee(n,e=0){return fe((t,r)=>{r.add(n.schedule(()=>t.subscribe(r),e))})}function Ze(n,e){if(!n)throw new Error("Iterable cannot be null");return new Xe(t=>{It(t,e,()=>{const r=n[Symbol.asyncIterator]();It(t,e,()=>{r.next().then(i=>{i.done?t.complete():t.next(i.value)})},0,!0)})})}function mi(...n){const e=function ka(n){return function La(n){return n&&D(n.schedule)}(Zo(n))?n.pop():void 0}(n),t=function W(n,e){return"number"==typeof Zo(n)?n.pop():e}(n,1/0),r=n;return r.length?1===r.length?mn(r[0]):function Nn(n=1/0){return Ut(Ke,n)}(t)(function Ri(n,e){return e?function Ir(n,e){if(null!=n){if(rr(n))return function le(n,e){return mn(n).pipe(ee(e),Y(e))}(n,e);if(bn(n))return function He(n,e){return new Xe(t=>{let r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}(n,e);if(vr(n))return function Oe(n,e){return mn(n).pipe(ee(e),Y(e))}(n,e);if(_n(n))return Ze(n,e);if(ve(n))return function tt(n,e){return new Xe(t=>{let r;return It(t,e,()=>{r=n[ce](),It(t,e,()=>{let i,s;try{({value:i,done:s}=r.next())}catch(o){return void t.error(o)}s?t.complete():t.next(i)},0,!0)}),()=>D(r?.return)&&r.return()})}(n,e);if(St(n))return function on(n,e){return Ze(yt(n),e)}(n,e)}throw Ft(n)}(n,e):mn(n)}(r,e)):Tn}function Xo(n,e,...t){if(!0===e)return void n();if(!1===e)return;const r=new we({next:()=>{r.unsubscribe(),n()}});return e(...t).subscribe(r)}function Xt(n){for(let e in n)if(n[e]===Xt)return e;throw Error("Could not find renamed property on target object.")}function Dn(n){if("string"==typeof n)return n;if(Array.isArray(n))return"["+n.map(Dn).join(", ")+"]";if(null==n)return""+n;if(n.overriddenName)return`${n.overriddenName}`;if(n.name)return`${n.name}`;const e=n.toString();if(null==e)return""+e;const t=e.indexOf("\n");return-1===t?e:e.substring(0,t)}function ns(n,e){return null==n||""===n?null===e?"":e:null==e||""===e?n:n+" "+e}const el=Xt({__forward_ref__:Xt});function ag(n){return n.__forward_ref__=ag,n.toString=function(){return Dn(this())},n}function Nt(n){return function cg(n){return"function"==typeof n&&n.hasOwnProperty(el)&&n.__forward_ref__===ag}(n)?n():n}class xt extends Error{constructor(e,t){super(function Yf(n,e){return`NG0${Math.abs(n)}${e?": "+e.trim():""}`}(e,t)),this.code=e}}function Vt(n){return"string"==typeof n?n:null==n?"":String(n)}function Zf(n,e){throw new xt(-201,!1)}function Ki(n,e){null==n&&function Mn(n,e,t,r){throw new Error(`ASSERTION ERROR: ${n}`+(null==r?"":` [Expected=> ${t} ${r} ${e} <=Actual]`))}(e,n,null,"!=")}function Jn(n){return{token:n.token,providedIn:n.providedIn||null,factory:n.factory,value:void 0}}function vc(n){return{providers:n.providers||[],imports:n.imports||[]}}function Xf(n){return bb(n,Jf)||bb(n,Db)}function bb(n,e){return n.hasOwnProperty(e)?n[e]:null}function _b(n){return n&&(n.hasOwnProperty(ug)||n.hasOwnProperty(bP))?n[ug]:null}const Jf=Xt({\u0275prov:Xt}),ug=Xt({\u0275inj:Xt}),Db=Xt({ngInjectableDef:Xt}),bP=Xt({ngInjectorDef:Xt});var Lt=(()=>((Lt=Lt||{})[Lt.Default=0]="Default",Lt[Lt.Host=1]="Host",Lt[Lt.Self=2]="Self",Lt[Lt.SkipSelf=4]="SkipSelf",Lt[Lt.Optional=8]="Optional",Lt))();let lg;function rs(n){const e=lg;return lg=n,e}function Sb(n,e,t){const r=Xf(n);return r&&"root"==r.providedIn?void 0===r.value?r.value=r.factory():r.value:t&Lt.Optional?null:void 0!==e?e:void Zf(Dn(n))}function Jo(n){return{toString:n}.toString()}var _s=(()=>((_s=_s||{})[_s.OnPush=0]="OnPush",_s[_s.Default=1]="Default",_s))(),zs=(()=>{return(n=zs||(zs={}))[n.Emulated=0]="Emulated",n[n.None=2]="None",n[n.ShadowDom=3]="ShadowDom",zs;var n})();const jn=(()=>typeof globalThis<"u"&&globalThis||typeof global<"u"&&global||typeof window<"u"&&window||typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&self)(),Ec={},xn=[],ed=Xt({\u0275cmp:Xt}),fg=Xt({\u0275dir:Xt}),dg=Xt({\u0275pipe:Xt}),Ib=Xt({\u0275mod:Xt}),po=Xt({\u0275fac:Xt}),tl=Xt({__NG_ELEMENT_ID__:Xt});let DP=0;function td(n){return Jo(()=>{const t=!0===n.standalone,r={},i={type:n.type,providersResolver:null,decls:n.decls,vars:n.vars,factory:null,template:n.template||null,consts:n.consts||null,ngContentSelectors:n.ngContentSelectors,hostBindings:n.hostBindings||null,hostVars:n.hostVars||0,hostAttrs:n.hostAttrs||null,contentQueries:n.contentQueries||null,declaredInputs:r,inputs:null,outputs:null,exportAs:n.exportAs||null,onPush:n.changeDetection===_s.OnPush,directiveDefs:null,pipeDefs:null,standalone:t,dependencies:t&&n.dependencies||null,getStandaloneInjector:null,selectors:n.selectors||xn,viewQuery:n.viewQuery||null,features:n.features||null,data:n.data||{},encapsulation:n.encapsulation||zs.Emulated,id:"c"+DP++,styles:n.styles||xn,_:null,setInput:null,schemas:n.schemas||null,tView:null},s=n.dependencies,o=n.features;return i.inputs=Ab(n.inputs,r),i.outputs=Ab(n.outputs),o&&o.forEach(a=>a(i)),i.directiveDefs=s?()=>("function"==typeof s?s():s).map(Cb).filter(Tb):null,i.pipeDefs=s?()=>("function"==typeof s?s():s).map(wi).filter(Tb):null,i})}function Cb(n){return kn(n)||Ei(n)}function Tb(n){return null!==n}function nl(n){return Jo(()=>({type:n.type,bootstrap:n.bootstrap||xn,declarations:n.declarations||xn,imports:n.imports||xn,exports:n.exports||xn,transitiveCompileScopes:null,schemas:n.schemas||null,id:n.id||null}))}function Ab(n,e){if(null==n)return Ec;const t={};for(const r in n)if(n.hasOwnProperty(r)){let i=n[r],s=i;Array.isArray(i)&&(s=i[1],i=i[0]),t[i]=r,e&&(e[i]=s)}return t}const is=td;function kn(n){return n[ed]||null}function Ei(n){return n[fg]||null}function wi(n){return n[dg]||null}function Ni(n){return Array.isArray(n)&&"object"==typeof n[1]}function Ss(n){return Array.isArray(n)&&!0===n[1]}function gg(n){return 0!=(8&n.flags)}function sd(n){return 2==(2&n.flags)}function od(n){return 1==(1&n.flags)}function Is(n){return null!==n.template}function xP(n){return 0!=(256&n[2])}function Ha(n,e){return n.hasOwnProperty(po)?n[po]:null}class NP{constructor(e,t,r){this.previousValue=e,this.currentValue=t,this.firstChange=r}isFirstChange(){return this.firstChange}}function Pb(n){return n.type.prototype.ngOnChanges&&(n.setInput=OP),MP}function MP(){const n=Mb(this),e=n?.current;if(e){const t=n.previous;if(t===Ec)n.previous=e;else for(let r in e)t[r]=e[r];n.current=null,this.ngOnChanges(e)}}function OP(n,e,t,r){const i=Mb(n)||function LP(n,e){return n[Nb]=e}(n,{previous:Ec,current:null}),s=i.current||(i.current={}),o=i.previous,a=this.declaredInputs[t],c=o[a];s[a]=new NP(c&&c.currentValue,e,o===Ec),n[r]=e}const Nb="__ngSimpleChanges__";function Mb(n){return n[Nb]||null}function Cr(n){for(;Array.isArray(n);)n=n[0];return n}function as(n,e){return Cr(e[n.index])}function wg(n,e){return n.data[e]}function Gi(n,e){const t=e[n];return Ni(t)?t:t[0]}function ud(n){return 64==(64&n[2])}function ea(n,e){return null==e?null:n[e]}function Lb(n){n[18]=0}function bg(n,e){n[5]+=e;let t=n,r=n[3];for(;null!==r&&(1===e&&1===t[5]||-1===e&&0===t[5]);)r[5]+=e,t=r,r=r[3]}const kt={lFrame:$b(null),bindingsEnabled:!0};function Bb(){return kt.bindingsEnabled}function Ve(){return kt.lFrame.lView}function pn(){return kt.lFrame.tView}function Lr(){let n=Fb();for(;null!==n&&64===n.type;)n=n.parent;return n}function Fb(){return kt.lFrame.currentTNode}function Ws(n,e){const t=kt.lFrame;t.currentTNode=n,t.isParent=e}function _g(){return kt.lFrame.isParent}function Ic(){return kt.lFrame.bindingIndex++}function ZP(n,e){const t=kt.lFrame;t.bindingIndex=t.bindingRootIndex=n,Sg(e)}function Sg(n){kt.lFrame.currentDirectiveIndex=n}function Cg(n){kt.lFrame.currentQueryIndex=n}function JP(n){const e=n[1];return 2===e.type?e.declTNode:1===e.type?n[6]:null}function Kb(n,e,t){if(t&Lt.SkipSelf){let i=e,s=n;for(;!(i=i.parent,null!==i||t&Lt.Host||(i=JP(s),null===i||(s=s[15],10&i.type))););if(null===i)return!1;e=i,n=s}const r=kt.lFrame=jb();return r.currentTNode=e,r.lView=n,!0}function Tg(n){const e=jb(),t=n[1];kt.lFrame=e,e.currentTNode=t.firstChild,e.lView=n,e.tView=t,e.contextLView=n,e.bindingIndex=t.bindingStartIndex,e.inI18n=!1}function jb(){const n=kt.lFrame,e=null===n?null:n.child;return null===e?$b(n):e}function $b(n){const e={currentTNode:null,isParent:!0,lView:null,tView:null,selectedIndex:-1,contextLView:null,elementDepthCount:0,currentNamespace:null,currentDirectiveIndex:-1,bindingRootIndex:-1,bindingIndex:-1,currentQueryIndex:0,parent:n,child:null,inI18n:!1};return null!==n&&(n.child=e),e}function Gb(){const n=kt.lFrame;return kt.lFrame=n.parent,n.currentTNode=null,n.lView=null,n}const zb=Gb;function Ag(){const n=Gb();n.isParent=!0,n.tView=null,n.selectedIndex=-1,n.contextLView=null,n.elementDepthCount=0,n.currentDirectiveIndex=-1,n.currentNamespace=null,n.bindingRootIndex=-1,n.bindingIndex=-1,n.currentQueryIndex=0}function _i(){return kt.lFrame.selectedIndex}function ta(n){kt.lFrame.selectedIndex=n}function fd(n,e){for(let t=e.directiveStart,r=e.directiveEnd;t=r)break}else e[c]<0&&(n[18]+=65536),(a>11>16&&(3&n[2])===e){n[2]+=2048;try{s.call(a)}finally{}}}else try{s.call(a)}finally{}}class cl{constructor(e,t,r){this.factory=e,this.resolving=!1,this.canSeeViewProviders=t,this.injectImpl=r}}function pd(n,e,t){let r=0;for(;re){o=s-1;break}}}for(;s>16}(n),r=e;for(;t>0;)r=r[15],t--;return r}let Pg=!0;function yd(n){const e=Pg;return Pg=n,e}let pN=0;const qs={};function ll(n,e){const t=Mg(n,e);if(-1!==t)return t;const r=e[1];r.firstCreatePass&&(n.injectorIndex=e.length,Ng(r.data,n),Ng(e,null),Ng(r.blueprint,null));const i=md(n,e),s=n.injectorIndex;if(Zb(i)){const o=Cc(i),a=Tc(i,e),c=a[1].data;for(let m=0;m<8;m++)e[s+m]=a[o+m]|c[o+m]}return e[s+8]=i,s}function Ng(n,e){n.push(0,0,0,0,0,0,0,0,e)}function Mg(n,e){return-1===n.injectorIndex||n.parent&&n.parent.injectorIndex===n.injectorIndex||null===e[n.injectorIndex+8]?-1:n.injectorIndex}function md(n,e){if(n.parent&&-1!==n.parent.injectorIndex)return n.parent.injectorIndex;let t=0,r=null,i=e;for(;null!==i;){if(r=o_(i),null===r)return-1;if(t++,i=i[15],-1!==r.injectorIndex)return r.injectorIndex|t<<16}return-1}function vd(n,e,t){!function gN(n,e,t){let r;"string"==typeof t?r=t.charCodeAt(0)||0:t.hasOwnProperty(tl)&&(r=t[tl]),null==r&&(r=t[tl]=pN++);const i=255&r;e.data[n+(i>>5)]|=1<=0?255&e:EN:e}(t);if("function"==typeof s){if(!Kb(e,n,r))return r&Lt.Host?e_(i,0,r):t_(e,t,r,i);try{const o=s(r);if(null!=o||r&Lt.Optional)return o;Zf()}finally{zb()}}else if("number"==typeof s){let o=null,a=Mg(n,e),c=-1,m=r&Lt.Host?e[16][6]:null;for((-1===a||r&Lt.SkipSelf)&&(c=-1===a?md(n,e):e[a+8],-1!==c&&s_(r,!1)?(o=e[1],a=Cc(c),e=Tc(c,e)):a=-1);-1!==a;){const T=e[1];if(i_(s,a,T.data)){const R=mN(a,e,t,o,r,m);if(R!==qs)return R}c=e[a+8],-1!==c&&s_(r,e[1].data[a+8]===m)&&i_(s,a,e)?(o=T,a=Cc(c),e=Tc(c,e)):a=-1}}return i}function mN(n,e,t,r,i,s){const o=e[1],a=o.data[n+8],T=function Ed(n,e,t,r,i){const s=n.providerIndexes,o=e.data,a=1048575&s,c=n.directiveStart,T=s>>20,k=i?a+T:n.directiveEnd;for(let U=r?a:a+T;U=c&&Q.type===t)return U}if(i){const U=o[c];if(U&&Is(U)&&U.type===t)return c}return null}(a,o,t,null==r?sd(a)&&Pg:r!=o&&0!=(3&a.type),i&Lt.Host&&s===a);return null!==T?fl(e,o,T,a):qs}function fl(n,e,t,r){let i=n[t];const s=e.data;if(function uN(n){return n instanceof cl}(i)){const o=i;o.resolving&&function pP(n,e){const t=e?`. Dependency path: ${e.join(" > ")} > ${n}`:"";throw new xt(-200,`Circular dependency in DI detected for ${n}${t}`)}(function An(n){return"function"==typeof n?n.name||n.toString():"object"==typeof n&&null!=n&&"function"==typeof n.type?n.type.name||n.type.toString():Vt(n)}(s[t]));const a=yd(o.canSeeViewProviders);o.resolving=!0;const c=o.injectImpl?rs(o.injectImpl):null;Kb(n,r,Lt.Default);try{i=n[t]=o.factory(void 0,s,n,r),e.firstCreatePass&&t>=r.directiveStart&&function aN(n,e,t){const{ngOnChanges:r,ngOnInit:i,ngDoCheck:s}=e.type.prototype;if(r){const o=Pb(e);(t.preOrderHooks||(t.preOrderHooks=[])).push(n,o),(t.preOrderCheckHooks||(t.preOrderCheckHooks=[])).push(n,o)}i&&(t.preOrderHooks||(t.preOrderHooks=[])).push(0-n,i),s&&((t.preOrderHooks||(t.preOrderHooks=[])).push(n,s),(t.preOrderCheckHooks||(t.preOrderCheckHooks=[])).push(n,s))}(t,s[t],e)}finally{null!==c&&rs(c),yd(a),o.resolving=!1,zb()}}return i}function i_(n,e,t){return!!(t[e+(n>>5)]&1<{const r=function kg(n){return function(...t){if(n){const r=n(...t);for(const i in r)this[i]=r[i]}}}(e);function i(...s){if(this instanceof i)return r.apply(this,s),this;const o=new i(...s);return a.annotation=o,a;function a(c,m,T){const R=c.hasOwnProperty(Rc)?c[Rc]:Object.defineProperty(c,Rc,{value:[]})[Rc];for(;R.length<=T;)R.push(null);return(R[T]=R[T]||[]).push(o),c}}return t&&(i.prototype=Object.create(t.prototype)),i.prototype.ngMetadataName=n,i.annotationCls=i,i})}class an{constructor(e,t){this._desc=e,this.ngMetadataName="InjectionToken",this.\u0275prov=void 0,"number"==typeof t?this.__NG_ELEMENT_ID__=t:void 0!==t&&(this.\u0275prov=Jn({token:this,providedIn:t.providedIn||"root",factory:t.factory}))}get multi(){return this}toString(){return`InjectionToken ${this._desc}`}}function mo(n,e){n.forEach(t=>Array.isArray(t)?mo(t,e):e(t))}function c_(n,e,t){e>=n.length?n.push(t):n.splice(e,0,t)}function wd(n,e){return e>=n.length-1?n.pop():n.splice(e,1)[0]}const gl={},Vg="__NG_DI_FLAG__",_d="ngTempTokenPath",MN=/\n/gm,d_="__source";let yl;function Oc(n){const e=yl;return yl=n,e}function LN(n,e=Lt.Default){if(void 0===yl)throw new xt(-203,!1);return null===yl?Sb(n,void 0,e):yl.get(n,e&Lt.Optional?null:void 0,e)}function On(n,e=Lt.Default){return(function _P(){return lg}()||LN)(Nt(n),e)}function Hg(n){const e=[];for(let t=0;t{const o=s;Yg(o,t,[],r)&&(i||(i=[]),i.push(o))}),void 0!==i&&V_(i,t),t}function V_(n,e){for(let t=0;t{e.push(s)})}}function Yg(n,e,t,r){if(!(n=Nt(n)))return!1;let i=null,s=_b(n);const o=!s&&kn(n);if(s||o){if(o&&!o.standalone)return!1;i=n}else{const c=n.ngModule;if(s=_b(c),!s)return!1;i=c}const a=r.has(i);if(o){if(a)return!1;if(r.add(i),o.dependencies){const c="function"==typeof o.dependencies?o.dependencies():o.dependencies;for(const m of c)Yg(m,e,t,r)}}else{if(!s)return!1;{if(null!=s.imports&&!a){let m;r.add(i);try{mo(s.imports,T=>{Yg(T,e,t,r)&&(m||(m=[]),m.push(T))})}finally{}void 0!==m&&V_(m,e)}if(!a){const m=Ha(i)||(()=>new i);e.push({provide:i,useFactory:m,deps:xn},{provide:B_,useValue:i,multi:!0},{provide:L_,useValue:()=>On(i),multi:!0})}const c=s.providers;null==c||a||mo(c,T=>{e.push(T)})}}return i!==n&&void 0!==n.providers}const _M=Xt({provide:String,useValue:Xt});function Zg(n){return null!==n&&"object"==typeof n&&_M in n}function Ka(n){return"function"==typeof n}const Xg=new an("Set Injector scope."),Pd={},SM={};let Jg;function Nd(){return void 0===Jg&&(Jg=new F_),Jg}class Bc{}class j_ extends Bc{constructor(e,t,r,i){super(),this.parent=t,this.source=r,this.scopes=i,this.records=new Map,this._ngOnDestroyHooks=new Set,this._onDestroyHooks=[],this._destroyed=!1,ty(e,o=>this.processProvider(o)),this.records.set(k_,Fc(void 0,this)),i.has("environment")&&this.records.set(Bc,Fc(void 0,this));const s=this.records.get(Xg);null!=s&&"string"==typeof s.value&&this.scopes.add(s.value),this.injectorDefTypes=new Set(this.get(B_.multi,xn,Lt.Self))}get destroyed(){return this._destroyed}destroy(){this.assertNotDestroyed(),this._destroyed=!0;try{for(const e of this._ngOnDestroyHooks)e.ngOnDestroy();for(const e of this._onDestroyHooks)e()}finally{this.records.clear(),this._ngOnDestroyHooks.clear(),this.injectorDefTypes.clear(),this._onDestroyHooks.length=0}}onDestroy(e){this._onDestroyHooks.push(e)}runInContext(e){this.assertNotDestroyed();const t=Oc(this),r=rs(void 0);try{return e()}finally{Oc(t),rs(r)}}get(e,t=gl,r=Lt.Default){this.assertNotDestroyed();const i=Oc(this),s=rs(void 0);try{if(!(r&Lt.SkipSelf)){let a=this.records.get(e);if(void 0===a){const c=function xM(n){return"function"==typeof n||"object"==typeof n&&n instanceof an}(e)&&Xf(e);a=c&&this.injectableDefInScope(c)?Fc(ey(e),Pd):null,this.records.set(e,a)}if(null!=a)return this.hydrate(e,a)}return(r&Lt.Self?Nd():this.parent).get(e,t=r&Lt.Optional&&t===gl?null:t)}catch(o){if("NullInjectorError"===o.name){if((o[_d]=o[_d]||[]).unshift(Dn(e)),i)throw o;return function FN(n,e,t,r){const i=n[_d];throw e[d_]&&i.unshift(e[d_]),n.message=function UN(n,e,t,r=null){n=n&&"\n"===n.charAt(0)&&"\u0275"==n.charAt(1)?n.slice(2):n;let i=Dn(e);if(Array.isArray(e))i=e.map(Dn).join(" -> ");else if("object"==typeof e){let s=[];for(let o in e)if(e.hasOwnProperty(o)){let a=e[o];s.push(o+":"+("string"==typeof a?JSON.stringify(a):Dn(a)))}i=`{${s.join(", ")}}`}return`${t}${r?"("+r+")":""}[${i}]: ${n.replace(MN,"\n ")}`}("\n"+n.message,i,t,r),n.ngTokenPath=i,n[_d]=null,n}(o,e,"R3InjectorError",this.source)}throw o}finally{rs(s),Oc(i)}}resolveInjectorInitializers(){const e=Oc(this),t=rs(void 0);try{const r=this.get(L_.multi,xn,Lt.Self);for(const i of r)i()}finally{Oc(e),rs(t)}}toString(){const e=[],t=this.records;for(const r of t.keys())e.push(Dn(r));return`R3Injector[${e.join(", ")}]`}assertNotDestroyed(){if(this._destroyed)throw new xt(205,!1)}processProvider(e){let t=Ka(e=Nt(e))?e:Nt(e&&e.provide);const r=function CM(n){return Zg(n)?Fc(void 0,n.useValue):Fc(function $_(n,e,t){let r;if(Ka(n)){const i=Nt(n);return Ha(i)||ey(i)}if(Zg(n))r=()=>Nt(n.useValue);else if(function K_(n){return!(!n||!n.useFactory)}(n))r=()=>n.useFactory(...Hg(n.deps||[]));else if(function H_(n){return!(!n||!n.useExisting)}(n))r=()=>On(Nt(n.useExisting));else{const i=Nt(n&&(n.useClass||n.provide));if(!function TM(n){return!!n.deps}(n))return Ha(i)||ey(i);r=()=>new i(...Hg(n.deps))}return r}(n),Pd)}(e);if(Ka(e)||!0!==e.multi)this.records.get(t);else{let i=this.records.get(t);i||(i=Fc(void 0,Pd,!0),i.factory=()=>Hg(i.multi),this.records.set(t,i)),t=e,i.multi.push(e)}this.records.set(t,r)}hydrate(e,t){return t.value===Pd&&(t.value=SM,t.value=t.factory()),"object"==typeof t.value&&t.value&&function AM(n){return null!==n&&"object"==typeof n&&"function"==typeof n.ngOnDestroy}(t.value)&&this._ngOnDestroyHooks.add(t.value),t.value}injectableDefInScope(e){if(!e.providedIn)return!1;const t=Nt(e.providedIn);return"string"==typeof t?"any"===t||this.scopes.has(t):this.injectorDefTypes.has(t)}}function ey(n){const e=Xf(n),t=null!==e?e.factory:Ha(n);if(null!==t)return t;if(n instanceof an)throw new xt(204,!1);if(n instanceof Function)return function IM(n){const e=n.length;if(e>0)throw function pl(n,e){const t=[];for(let r=0;rt.factory(n):()=>new n}(n);throw new xt(204,!1)}function Fc(n,e,t=!1){return{factory:n,value:e,multi:t?[]:void 0}}function RM(n){return!!n.\u0275providers}function ty(n,e){for(const t of n)Array.isArray(t)?ty(t,e):RM(t)?ty(t.\u0275providers,e):e(t)}class G_{}class MM{resolveComponentFactory(e){throw function NM(n){const e=Error(`No component factory found for ${Dn(n)}. Did you add it to @NgModule.entryComponents?`);return e.ngComponent=n,e}(e)}}let Md=(()=>{class n{}return n.NULL=new MM,n})();function OM(){return Uc(Lr(),Ve())}function Uc(n,e){return new Vc(as(n,e))}let Vc=(()=>{class n{constructor(t){this.nativeElement=t}}return n.__NG_ELEMENT_ID__=OM,n})();class W_{}let BM=(()=>{class n{}return n.\u0275prov=Jn({token:n,providedIn:"root",factory:()=>null}),n})();class ny{constructor(e){this.full=e,this.major=e.split(".")[0],this.minor=e.split(".")[1],this.patch=e.split(".").slice(2).join(".")}}const FM=new ny("14.2.0"),ry={};function cy(n){return n.ngOriginalError}class Hc{constructor(){this._console=console}handleError(e){const t=this._findOriginalError(e);this._console.error("ERROR",e),t&&this._console.error("ORIGINAL ERROR",t)}_findOriginalError(e){let t=e&&cy(e);for(;t&&cy(t);)t=cy(t);return t||null}}const uy=new Map;let YM=0;const fy="__ngContext__";function si(n,e){Ni(e)?(n[fy]=e[20],function XM(n){uy.set(n[20],n)}(e)):n[fy]=e}function Dl(n){const e=n[fy];return"number"==typeof e?function e1(n){return uy.get(n)||null}(e):e||null}function dy(n){const e=Dl(n);return e?Ni(e)?e:e.lView:null}var Mi=(()=>((Mi=Mi||{})[Mi.Important=1]="Important",Mi[Mi.DashCase=2]="DashCase",Mi))();function py(n,e){return undefined(n,e)}function Sl(n){const e=n[3];return Ss(e)?e[3]:e}function gy(n){return a1(n[13])}function yy(n){return a1(n[4])}function a1(n){for(;null!==n&&!Ss(n);)n=n[4];return n}function jc(n,e,t,r,i){if(null!=r){let s,o=!1;Ss(r)?s=r:Ni(r)&&(o=!0,r=r[0]);const a=Cr(r);0===n&&null!==t?null==i?h1(e,t,a):ja(e,t,a,i||null,!0):1===n&&null!==t?ja(e,t,a,i||null,!0):2===n?function w1(n,e,t){const r=Od(n,e);r&&function I3(n,e,t,r){n.removeChild(e,t,r)}(n,r,e,t)}(e,a,o):3===n&&e.destroyNode(a),null!=s&&function A3(n,e,t,r,i){const s=t[7];s!==Cr(t)&&jc(e,n,r,s,i);for(let a=10;a0&&(n[t-1][4]=r[4]);const s=wd(n,10+e);!function m3(n,e){Il(n,e,e[11],2,null,null),e[0]=null,e[6]=null}(r[1],r);const o=s[19];null!==o&&o.detachView(s[1]),r[3]=null,r[4]=null,r[2]&=-65}return r}function l1(n,e){if(!(128&e[2])){const t=e[11];t.destroyNode&&Il(n,e,t,3,null,null),function w3(n){let e=n[13];if(!e)return wy(n[1],n);for(;e;){let t=null;if(Ni(e))t=e[13];else{const r=e[10];r&&(t=r)}if(!t){for(;e&&!e[4]&&e!==n;)Ni(e)&&wy(e[1],e),e=e[3];null===e&&(e=n),Ni(e)&&wy(e[1],e),t=e&&e[4]}e=t}}(e)}}function wy(n,e){if(!(128&e[2])){e[2]&=-65,e[2]|=128,function S3(n,e){let t;if(null!=n&&null!=(t=n.destroyHooks))for(let r=0;r=0?r[i=m]():r[i=-m].unsubscribe(),s+=2}else{const o=r[i=t[s+1]];t[s].call(o)}if(null!==r){for(let s=i+1;ss?"":i[R+1].toLowerCase();const U=8&r?k:null;if(U&&-1!==D1(U,m,0)||2&r&&m!==k){if(Cs(r))return!1;o=!0}}}}else{if(!o&&!Cs(r)&&!Cs(c))return!1;if(o&&Cs(c))continue;o=!1,r=c|1&r}}return Cs(r)||o}function Cs(n){return 0==(1&n)}function M3(n,e,t,r){if(null===e)return-1;let i=0;if(r||!t){let s=!1;for(;i-1)for(t++;t0?'="'+a+'"':"")+"]"}else 8&r?i+="."+o:4&r&&(i+=" "+o);else""!==i&&!Cs(o)&&(e+=T1(s,i),i=""),r=o,s=s||!Cs(r);t++}return""!==i&&(e+=T1(s,i)),e}const Ht={};function Cl(n){A1(pn(),Ve(),_i()+n,!1)}function A1(n,e,t,r){if(!r)if(3==(3&e[2])){const s=n.preOrderCheckHooks;null!==s&&dd(e,s,t)}else{const s=n.preOrderHooks;null!==s&&hd(e,s,0,t)}ta(t)}function N1(n,e=null,t=null,r){const i=M1(n,e,t,r);return i.resolveInjectorInitializers(),i}function M1(n,e=null,t=null,r,i=new Set){const s=[t||xn,bM(n)];return r=r||("object"==typeof n?void 0:Dn(n)),new j_(s,e||Nd(),r||null,i)}let $a=(()=>{class n{static create(t,r){if(Array.isArray(t))return N1({name:""},r,t,"");{const i=t.name??"";return N1({name:i},t.parent,t.providers,i)}}}return n.THROW_IF_NOT_FOUND=gl,n.NULL=new F_,n.\u0275prov=Jn({token:n,providedIn:"any",factory:()=>On(k_)}),n.__NG_ELEMENT_ID__=-1,n})();function qt(n,e=Lt.Default){const t=Ve();return null===t?On(n,e):n_(Lr(),t,Nt(n),e)}function Y1(n,e){const t=n.contentQueries;if(null!==t)for(let r=0;r22&&A1(n,e,22,!1),t(r,i)}finally{ta(s)}}function Vy(n,e,t){!Bb()||(function TO(n,e,t,r){const i=t.directiveStart,s=t.directiveEnd;n.firstCreatePass||ll(t,e),si(r,e);const o=t.initialInputs;for(let a=i;a0;){const t=n[--e];if("number"==typeof t&&t<0)return t}return 0})(a)!=c&&a.push(c),a.push(r,i,o)}}function sD(n,e){null!==n.hostBindings&&n.hostBindings(1,e)}function oD(n,e){e.flags|=2,(n.components||(n.components=[])).push(e.index)}function PO(n,e,t){if(t){if(e.exportAs)for(let r=0;r0&&Gy(t)}}function Gy(n){for(let r=gy(n);null!==r;r=yy(r))for(let i=10;i0&&Gy(s)}const t=n[1].components;if(null!==t)for(let r=0;r0&&Gy(i)}}function FO(n,e){const t=Gi(e,n),r=t[1];(function UO(n,e){for(let t=e.length;t-1&&(Ey(e,r),wd(t,r))}this._attachedToViewContainer=!1}l1(this._lView[1],this._lView)}onDestroy(e){!function eD(n,e,t,r){const i=fD(e);null===t?i.push(r):(i.push(t),n.firstCreatePass&&dD(n).push(r,i.length-1))}(this._lView[1],this._lView,null,e)}markForCheck(){zy(this._cdRefInjectingView||this._lView)}detach(){this._lView[2]&=-65}reattach(){this._lView[2]|=64}detectChanges(){!function Wy(n,e,t){const r=e[10];r.begin&&r.begin();try{Tl(n,e,n.template,t)}catch(i){throw pD(e,i),i}finally{r.end&&r.end()}}(this._lView[1],this._lView,this.context)}checkNoChanges(){}attachToViewContainerRef(){if(this._appRef)throw new xt(902,!1);this._attachedToViewContainer=!0}detachFromAppRef(){this._appRef=null,function E3(n,e){Il(n,e,e[11],2,null,null)}(this._lView[1],this._lView)}attachToAppRef(e){if(this._attachedToViewContainer)throw new xt(902,!1);this._appRef=e}}class HO extends Al{constructor(e){super(e),this._view=e}detectChanges(){!function lD(n){!function VO(n){for(let e=0;e0&&Sy(m,R,Re.join(" "))}if(he=wg(Q,22),void 0!==t){const ue=he.projection=[];for(let Re=0;Rea(Cr(Le[r.index])):r.index;let Re=null;if(!a&&c&&(Re=function pL(n,e,t,r){const i=n.cleanup;if(null!=i)for(let s=0;sc?a[c]:null}"string"==typeof o&&(s+=2)}return null}(n,e,i,r.index)),null!==Re)(Re.__ngLastListenerFn__||Re).__ngNextListenerFn__=s,Re.__ngLastListenerFn__=s,U=!1;else{s=OD(r,e,R,s,!1);const Le=t.listen(he,i,s);k.push(s,Le),T&&T.push(i,ue,Ae,Ae+1)}}else s=OD(r,e,R,s,!1);const Q=r.outputs;let X;if(U&&null!==Q&&(X=Q[i])){const ae=X.length;if(ae)for(let he=0;het()),this.destroyCbs=null}onDestroy(e){this.destroyCbs.push(e)}}class y0 extends class n4{}{constructor(e){super(),this.moduleType=e}create(e){return new ZS(this.moduleType,e)}}function v0(n){return e=>{setTimeout(n,void 0,e)}}const Do=class M4 extends Sr{constructor(e=!1){super(),this.__isAsync=e}emit(e){super.next(e)}subscribe(e,t,r){let i=e,s=t||(()=>null),o=r;if(e&&"object"==typeof e){const c=e;i=c.next?.bind(c),s=c.error?.bind(c),o=c.complete?.bind(c)}this.__isAsync&&(s=v0(s),i&&(i=v0(i)),o&&(o=v0(o)));const a=super.subscribe({next:i,error:s,complete:o});return e instanceof F&&e.add(a),a}};let So=(()=>{class n{}return n.__NG_ELEMENT_ID__=B4,n})();const L4=So,k4=class extends L4{constructor(e,t,r){super(),this._declarationLView=e,this._declarationTContainer=t,this.elementRef=r}createEmbeddedView(e,t){const r=this._declarationTContainer.tViews,i=Hd(this._declarationLView,r,e,16,null,r.declTNode,null,null,null,null,t||null);i[17]=this._declarationLView[this._declarationTContainer.index];const o=this._declarationLView[19];return null!==o&&(i[19]=o.createEmbeddedView(r)),Kd(r,i,e),new Al(i)}};function B4(){return function th(n,e){return 4&n.type?new k4(e,n,Uc(n,e)):null}(Lr(),Ve())}let eo=(()=>{class n{}return n.__NG_ELEMENT_ID__=F4,n})();function F4(){return function dI(n,e){let t;const r=e[n.index];if(Ss(r))t=r;else{let i;if(8&n.type)i=Cr(r);else{const s=e[11];i=s.createComment("");const o=as(n,e);ja(s,Od(s,o),i,function C3(n,e){return n.nextSibling(e)}(s,o),!1)}e[n.index]=t=uD(r,e,i,n),jd(e,t)}return new lI(t,n,e)}(Lr(),Ve())}const U4=eo,lI=class extends U4{constructor(e,t,r){super(),this._lContainer=e,this._hostTNode=t,this._hostLView=r}get element(){return Uc(this._hostTNode,this._hostLView)}get injector(){return new Ac(this._hostTNode,this._hostLView)}get parentInjector(){const e=md(this._hostTNode,this._hostLView);if(Zb(e)){const t=Tc(e,this._hostLView),r=Cc(e);return new Ac(t[1].data[r+8],t)}return new Ac(null,this._hostLView)}clear(){for(;this.length>0;)this.remove(this.length-1)}get(e){const t=fI(this._lContainer);return null!==t&&t[e]||null}get length(){return this._lContainer.length-10}createEmbeddedView(e,t,r){let i,s;"number"==typeof r?i=r:null!=r&&(i=r.index,s=r.injector);const o=e.createEmbeddedView(t||{},s);return this.insert(o,i),o}createComponent(e,t,r,i,s){const o=e&&!function hl(n){return"function"==typeof n}(e);let a;if(o)a=t;else{const R=t||{};a=R.index,r=R.injector,i=R.projectableNodes,s=R.environmentInjector||R.ngModuleRef}const c=o?e:new xl(kn(e)),m=r||this.parentInjector;if(!s&&null==c.ngModule){const k=(o?m:this.parentInjector).get(Bc,null);k&&(s=k)}const T=c.create(m,i,void 0,s);return this.insert(T.hostView,a),T}insert(e,t){const r=e._lView,i=r[1];if(function HP(n){return Ss(n[3])}(r)){const T=this.indexOf(e);if(-1!==T)this.detach(T);else{const R=r[3],k=new lI(R,R[6],R[3]);k.detach(k.indexOf(e))}}const s=this._adjustIndex(t),o=this._lContainer;!function b3(n,e,t,r){const i=10+r,s=t.length;r>0&&(t[i-1][4]=e),r{class n{constructor(t){this.appInits=t,this.resolve=rh,this.reject=rh,this.initialized=!1,this.done=!1,this.donePromise=new Promise((r,i)=>{this.resolve=r,this.reject=i})}runInitializers(){if(this.initialized)return;const t=[],r=()=>{this.done=!0,this.resolve()};if(this.appInits)for(let i=0;i{s.subscribe({complete:a,error:c})});t.push(o)}}Promise.all(t).then(()=>{r()}).catch(i=>{this.reject(i)}),0===t.length&&r(),this.initialized=!0}}return n.\u0275fac=function(t){return new(t||n)(On(kI,8))},n.\u0275prov=Jn({token:n,factory:n.\u0275fac,providedIn:"root"}),n})();const Vl=new an("AppId",{providedIn:"root",factory:function BI(){return`${R0()}${R0()}${R0()}`}});function R0(){return String.fromCharCode(97+Math.floor(25*Math.random()))}const FI=new an("Platform Initializer"),UI=new an("Platform ID",{providedIn:"platform",factory:()=>"unknown"}),vk=new an("appBootstrapListener"),Io=new an("LocaleId",{providedIn:"root",factory:()=>function kN(n,e=Lt.Default){return"number"!=typeof e&&(e=0|(e.optional&&8)|(e.host&&1)|(e.self&&2)|(e.skipSelf&&4)),On(n,e)}(Io,Lt.Optional|Lt.SkipSelf)||function Ek(){return typeof $localize<"u"&&$localize.locale||su}()}),Sk=(()=>Promise.resolve(0))();function P0(n){typeof Zone>"u"?Sk.then(()=>{n&&n.apply(null,null)}):Zone.current.scheduleMicroTask("scheduleMicrotask",n)}class ai{constructor({enableLongStackTrace:e=!1,shouldCoalesceEventChangeDetection:t=!1,shouldCoalesceRunChangeDetection:r=!1}){if(this.hasPendingMacrotasks=!1,this.hasPendingMicrotasks=!1,this.isStable=!0,this.onUnstable=new Do(!1),this.onMicrotaskEmpty=new Do(!1),this.onStable=new Do(!1),this.onError=new Do(!1),typeof Zone>"u")throw new xt(908,!1);Zone.assertZonePatched();const i=this;if(i._nesting=0,i._outer=i._inner=Zone.current,Zone.AsyncStackTaggingZoneSpec){const s=Zone.AsyncStackTaggingZoneSpec;i._inner=i._inner.fork(new s("Angular"))}Zone.TaskTrackingZoneSpec&&(i._inner=i._inner.fork(new Zone.TaskTrackingZoneSpec)),e&&Zone.longStackTraceZoneSpec&&(i._inner=i._inner.fork(Zone.longStackTraceZoneSpec)),i.shouldCoalesceEventChangeDetection=!r&&t,i.shouldCoalesceRunChangeDetection=r,i.lastRequestAnimationFrameId=-1,i.nativeRequestAnimationFrame=function Ik(){let n=jn.requestAnimationFrame,e=jn.cancelAnimationFrame;if(typeof Zone<"u"&&n&&e){const t=n[Zone.__symbol__("OriginalDelegate")];t&&(n=t);const r=e[Zone.__symbol__("OriginalDelegate")];r&&(e=r)}return{nativeRequestAnimationFrame:n,nativeCancelAnimationFrame:e}}().nativeRequestAnimationFrame,function Ak(n){const e=()=>{!function Tk(n){n.isCheckStableRunning||-1!==n.lastRequestAnimationFrameId||(n.lastRequestAnimationFrameId=n.nativeRequestAnimationFrame.call(jn,()=>{n.fakeTopEventTask||(n.fakeTopEventTask=Zone.root.scheduleEventTask("fakeTopEventTask",()=>{n.lastRequestAnimationFrameId=-1,M0(n),n.isCheckStableRunning=!0,N0(n),n.isCheckStableRunning=!1},void 0,()=>{},()=>{})),n.fakeTopEventTask.invoke()}),M0(n))}(n)};n._inner=n._inner.fork({name:"angular",properties:{isAngularZone:!0},onInvokeTask:(t,r,i,s,o,a)=>{try{return KI(n),t.invokeTask(i,s,o,a)}finally{(n.shouldCoalesceEventChangeDetection&&"eventTask"===s.type||n.shouldCoalesceRunChangeDetection)&&e(),jI(n)}},onInvoke:(t,r,i,s,o,a,c)=>{try{return KI(n),t.invoke(i,s,o,a,c)}finally{n.shouldCoalesceRunChangeDetection&&e(),jI(n)}},onHasTask:(t,r,i,s)=>{t.hasTask(i,s),r===i&&("microTask"==s.change?(n._hasPendingMicrotasks=s.microTask,M0(n),N0(n)):"macroTask"==s.change&&(n.hasPendingMacrotasks=s.macroTask))},onHandleError:(t,r,i,s)=>(t.handleError(i,s),n.runOutsideAngular(()=>n.onError.emit(s)),!1)})}(i)}static isInAngularZone(){return typeof Zone<"u"&&!0===Zone.current.get("isAngularZone")}static assertInAngularZone(){if(!ai.isInAngularZone())throw new xt(909,!1)}static assertNotInAngularZone(){if(ai.isInAngularZone())throw new xt(909,!1)}run(e,t,r){return this._inner.run(e,t,r)}runTask(e,t,r,i){const s=this._inner,o=s.scheduleEventTask("NgZoneEvent: "+i,e,Ck,rh,rh);try{return s.runTask(o,t,r)}finally{s.cancelTask(o)}}runGuarded(e,t,r){return this._inner.runGuarded(e,t,r)}runOutsideAngular(e){return this._outer.run(e)}}const Ck={};function N0(n){if(0==n._nesting&&!n.hasPendingMicrotasks&&!n.isStable)try{n._nesting++,n.onMicrotaskEmpty.emit(null)}finally{if(n._nesting--,!n.hasPendingMicrotasks)try{n.runOutsideAngular(()=>n.onStable.emit(null))}finally{n.isStable=!0}}}function M0(n){n.hasPendingMicrotasks=!!(n._hasPendingMicrotasks||(n.shouldCoalesceEventChangeDetection||n.shouldCoalesceRunChangeDetection)&&-1!==n.lastRequestAnimationFrameId)}function KI(n){n._nesting++,n.isStable&&(n.isStable=!1,n.onUnstable.emit(null))}function jI(n){n._nesting--,N0(n)}class xk{constructor(){this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new Do,this.onMicrotaskEmpty=new Do,this.onStable=new Do,this.onError=new Do}run(e,t,r){return e.apply(t,r)}runGuarded(e,t,r){return e.apply(t,r)}runOutsideAngular(e){return e()}runTask(e,t,r,i){return e.apply(t,r)}}const $I=new an(""),sh=new an("");let k0,O0=(()=>{class n{constructor(t,r,i){this._ngZone=t,this.registry=r,this._pendingCount=0,this._isZoneStable=!0,this._didWork=!1,this._callbacks=[],this.taskTrackingZone=null,k0||(function Rk(n){k0=n}(i),i.addToWindow(r)),this._watchAngularEvents(),t.run(()=>{this.taskTrackingZone=typeof Zone>"u"?null:Zone.current.get("TaskTrackingZone")})}_watchAngularEvents(){this._ngZone.onUnstable.subscribe({next:()=>{this._didWork=!0,this._isZoneStable=!1}}),this._ngZone.runOutsideAngular(()=>{this._ngZone.onStable.subscribe({next:()=>{ai.assertNotInAngularZone(),P0(()=>{this._isZoneStable=!0,this._runCallbacksIfReady()})}})})}increasePendingRequestCount(){return this._pendingCount+=1,this._didWork=!0,this._pendingCount}decreasePendingRequestCount(){if(this._pendingCount-=1,this._pendingCount<0)throw new Error("pending async requests below zero");return this._runCallbacksIfReady(),this._pendingCount}isStable(){return this._isZoneStable&&0===this._pendingCount&&!this._ngZone.hasPendingMacrotasks}_runCallbacksIfReady(){if(this.isStable())P0(()=>{for(;0!==this._callbacks.length;){let t=this._callbacks.pop();clearTimeout(t.timeoutId),t.doneCb(this._didWork)}this._didWork=!1});else{let t=this.getPendingTasks();this._callbacks=this._callbacks.filter(r=>!r.updateCb||!r.updateCb(t)||(clearTimeout(r.timeoutId),!1)),this._didWork=!0}}getPendingTasks(){return this.taskTrackingZone?this.taskTrackingZone.macroTasks.map(t=>({source:t.source,creationLocation:t.creationLocation,data:t.data})):[]}addCallback(t,r,i){let s=-1;r&&r>0&&(s=setTimeout(()=>{this._callbacks=this._callbacks.filter(o=>o.timeoutId!==s),t(this._didWork,this.getPendingTasks())},r)),this._callbacks.push({doneCb:t,timeoutId:s,updateCb:i})}whenStable(t,r,i){if(i&&!this.taskTrackingZone)throw new Error('Task tracking zone is required when passing an update callback to whenStable(). Is "zone.js/plugins/task-tracking" loaded?');this.addCallback(t,r,i),this._runCallbacksIfReady()}getPendingRequestCount(){return this._pendingCount}registerApplication(t){this.registry.registerApplication(t,this)}unregisterApplication(t){this.registry.unregisterApplication(t)}findProviders(t,r,i){return[]}}return n.\u0275fac=function(t){return new(t||n)(On(ai),On(L0),On(sh))},n.\u0275prov=Jn({token:n,factory:n.\u0275fac}),n})(),L0=(()=>{class n{constructor(){this._applications=new Map}registerApplication(t,r){this._applications.set(t,r)}unregisterApplication(t){this._applications.delete(t)}unregisterAllApplications(){this._applications.clear()}getTestability(t){return this._applications.get(t)||null}getAllTestabilities(){return Array.from(this._applications.values())}getAllRootElements(){return Array.from(this._applications.keys())}findTestabilityInTree(t,r=!0){return k0?.findTestabilityInTree(this,t,r)??null}}return n.\u0275fac=function(t){return new(t||n)},n.\u0275prov=Jn({token:n,factory:n.\u0275fac,providedIn:"platform"}),n})(),oa=null;const GI=new an("AllowMultipleToken"),B0=new an("PlatformDestroyListeners");function WI(n,e,t=[]){const r=`Platform: ${e}`,i=new an(r);return(s=[])=>{let o=F0();if(!o||o.injector.get(GI,!1)){const a=[...t,...s,{provide:i,useValue:!0}];n?n(a):function Mk(n){if(oa&&!oa.get(GI,!1))throw new xt(400,!1);oa=n;const e=n.get(QI);(function zI(n){const e=n.get(FI,null);e&&e.forEach(t=>t())})(n)}(function qI(n=[],e){return $a.create({name:e,providers:[{provide:Xg,useValue:"platform"},{provide:B0,useValue:new Set([()=>oa=null])},...n]})}(a,r))}return function Lk(n){const e=F0();if(!e)throw new xt(401,!1);return e}()}}function F0(){return oa?.get(QI)??null}let QI=(()=>{class n{constructor(t){this._injector=t,this._modules=[],this._destroyListeners=[],this._destroyed=!1}bootstrapModuleFactory(t,r){const i=function ZI(n,e){let t;return t="noop"===n?new xk:("zone.js"===n?void 0:n)||new ai(e),t}(r?.ngZone,function YI(n){return{enableLongStackTrace:!1,shouldCoalesceEventChangeDetection:!(!n||!n.ngZoneEventCoalescing)||!1,shouldCoalesceRunChangeDetection:!(!n||!n.ngZoneRunCoalescing)||!1}}(r)),s=[{provide:ai,useValue:i}];return i.run(()=>{const o=$a.create({providers:s,parent:this.injector,name:t.moduleType.name}),a=t.create(o),c=a.injector.get(Hc,null);if(!c)throw new xt(402,!1);return i.runOutsideAngular(()=>{const m=i.onError.subscribe({next:T=>{c.handleError(T)}});a.onDestroy(()=>{oh(this._modules,a),m.unsubscribe()})}),function XI(n,e,t){try{const r=t();return r0(r)?r.catch(i=>{throw e.runOutsideAngular(()=>n.handleError(i)),i}):r}catch(r){throw e.runOutsideAngular(()=>n.handleError(r)),r}}(c,i,()=>{const m=a.injector.get(ih);return m.runInitializers(),m.donePromise.then(()=>(function CS(n){Ki(n,"Expected localeId to be defined"),"string"==typeof n&&(IS=n.toLowerCase().replace(/_/g,"-"))}(a.injector.get(Io,su)||su),this._moduleDoBootstrap(a),a))})})}bootstrapModule(t,r=[]){const i=JI({},r);return function Pk(n,e,t){const r=new y0(t);return Promise.resolve(r)}(0,0,t).then(s=>this.bootstrapModuleFactory(s,i))}_moduleDoBootstrap(t){const r=t.injector.get(U0);if(t._bootstrapComponents.length>0)t._bootstrapComponents.forEach(i=>r.bootstrap(i));else{if(!t.instance.ngDoBootstrap)throw new xt(403,!1);t.instance.ngDoBootstrap(r)}this._modules.push(t)}onDestroy(t){this._destroyListeners.push(t)}get injector(){return this._injector}destroy(){if(this._destroyed)throw new xt(404,!1);this._modules.slice().forEach(r=>r.destroy()),this._destroyListeners.forEach(r=>r());const t=this._injector.get(B0,null);t&&(t.forEach(r=>r()),t.clear()),this._destroyed=!0}get destroyed(){return this._destroyed}}return n.\u0275fac=function(t){return new(t||n)(On($a))},n.\u0275prov=Jn({token:n,factory:n.\u0275fac,providedIn:"platform"}),n})();function JI(n,e){return Array.isArray(e)?e.reduce(JI,n):{...n,...e}}let U0=(()=>{class n{constructor(t,r,i){this._zone=t,this._injector=r,this._exceptionHandler=i,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._stable=!0,this._destroyed=!1,this._destroyListeners=[],this.componentTypes=[],this.components=[],this._onMicrotaskEmptySubscription=this._zone.onMicrotaskEmpty.subscribe({next:()=>{this._zone.run(()=>{this.tick()})}});const s=new Xe(a=>{this._stable=this._zone.isStable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks,this._zone.runOutsideAngular(()=>{a.next(this._stable),a.complete()})}),o=new Xe(a=>{let c;this._zone.runOutsideAngular(()=>{c=this._zone.onStable.subscribe(()=>{ai.assertNotInAngularZone(),P0(()=>{!this._stable&&!this._zone.hasPendingMacrotasks&&!this._zone.hasPendingMicrotasks&&(this._stable=!0,a.next(!0))})})});const m=this._zone.onUnstable.subscribe(()=>{ai.assertInAngularZone(),this._stable&&(this._stable=!1,this._zone.runOutsideAngular(()=>{a.next(!1)}))});return()=>{c.unsubscribe(),m.unsubscribe()}});this.isStable=mi(s,o.pipe(function bs(n={}){const{connector:e=(()=>new Sr),resetOnError:t=!0,resetOnComplete:r=!0,resetOnRefCountZero:i=!0}=n;return s=>{let o,a,c,m=0,T=!1,R=!1;const k=()=>{a?.unsubscribe(),a=void 0},U=()=>{k(),o=c=void 0,T=R=!1},Q=()=>{const X=o;U(),X?.unsubscribe()};return fe((X,ae)=>{m++,!R&&!T&&k();const he=c=c??e();ae.add(()=>{m--,0===m&&!R&&!T&&(a=Xo(Q,i))}),he.subscribe(ae),!o&&m>0&&(o=new we({next:Ae=>he.next(Ae),error:Ae=>{R=!0,k(),a=Xo(U,t,Ae),he.error(Ae)},complete:()=>{T=!0,k(),a=Xo(U,r),he.complete()}}),mn(X).subscribe(o))})(s)}}()))}get destroyed(){return this._destroyed}get injector(){return this._injector}bootstrap(t,r){const i=t instanceof G_;if(!this._injector.get(ih).done)throw!i&&function rl(n){const e=kn(n)||Ei(n)||wi(n);return null!==e&&e.standalone}(t),new xt(405,false);let o;o=i?t:this._injector.get(Md).resolveComponentFactory(t),this.componentTypes.push(o.componentType);const a=function Nk(n){return n.isBoundToModule}(o)?void 0:this._injector.get(au),m=o.create($a.NULL,[],r||o.selector,a),T=m.location.nativeElement,R=m.injector.get($I,null);return R?.registerApplication(T),m.onDestroy(()=>{this.detachView(m.hostView),oh(this.components,m),R?.unregisterApplication(T)}),this._loadComponent(m),m}tick(){if(this._runningTick)throw new xt(101,!1);try{this._runningTick=!0;for(let t of this._views)t.detectChanges()}catch(t){this._zone.runOutsideAngular(()=>this._exceptionHandler.handleError(t))}finally{this._runningTick=!1}}attachView(t){const r=t;this._views.push(r),r.attachToAppRef(this)}detachView(t){const r=t;oh(this._views,r),r.detachFromAppRef()}_loadComponent(t){this.attachView(t.hostView),this.tick(),this.components.push(t),this._injector.get(vk,[]).concat(this._bootstrapListeners).forEach(i=>i(t))}ngOnDestroy(){if(!this._destroyed)try{this._destroyListeners.forEach(t=>t()),this._views.slice().forEach(t=>t.destroy()),this._onMicrotaskEmptySubscription.unsubscribe()}finally{this._destroyed=!0,this._views=[],this._bootstrapListeners=[],this._destroyListeners=[]}}onDestroy(t){return this._destroyListeners.push(t),()=>oh(this._destroyListeners,t)}destroy(){if(this._destroyed)throw new xt(406,!1);const t=this._injector;t.destroy&&!t.destroyed&&t.destroy()}get viewCount(){return this._views.length}warnIfDestroyed(){}}return n.\u0275fac=function(t){return new(t||n)(On(ai),On(Bc),On(Hc))},n.\u0275prov=Jn({token:n,factory:n.\u0275fac,providedIn:"root"}),n})();function oh(n,e){const t=n.indexOf(e);t>-1&&n.splice(t,1)}let tC=!0;class oC{constructor(){}supports(e){return Rl(e)}create(e){return new zk(e)}}const Gk=(n,e)=>e;class zk{constructor(e){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=e||Gk}forEachItem(e){let t;for(t=this._itHead;null!==t;t=t._next)e(t)}forEachOperation(e){let t=this._itHead,r=this._removalsHead,i=0,s=null;for(;t||r;){const o=!r||t&&t.currentIndex{o=this._trackByFn(i,a),null!==t&&Object.is(t.trackById,o)?(r&&(t=this._verifyReinsertion(t,a,o,i)),Object.is(t.item,a)||this._addIdentityChange(t,a)):(t=this._mismatch(t,a,o,i),r=!0),t=t._next,i++}),this.length=i;return this._truncate(t),this.collection=e,this.isDirty}get isDirty(){return null!==this._additionsHead||null!==this._movesHead||null!==this._removalsHead||null!==this._identityChangesHead}_reset(){if(this.isDirty){let e;for(e=this._previousItHead=this._itHead;null!==e;e=e._next)e._nextPrevious=e._next;for(e=this._additionsHead;null!==e;e=e._nextAdded)e.previousIndex=e.currentIndex;for(this._additionsHead=this._additionsTail=null,e=this._movesHead;null!==e;e=e._nextMoved)e.previousIndex=e.currentIndex;this._movesHead=this._movesTail=null,this._removalsHead=this._removalsTail=null,this._identityChangesHead=this._identityChangesTail=null}}_mismatch(e,t,r,i){let s;return null===e?s=this._itTail:(s=e._prev,this._remove(e)),null!==(e=null===this._unlinkedRecords?null:this._unlinkedRecords.get(r,null))?(Object.is(e.item,t)||this._addIdentityChange(e,t),this._reinsertAfter(e,s,i)):null!==(e=null===this._linkedRecords?null:this._linkedRecords.get(r,i))?(Object.is(e.item,t)||this._addIdentityChange(e,t),this._moveAfter(e,s,i)):e=this._addAfter(new Wk(t,r),s,i),e}_verifyReinsertion(e,t,r,i){let s=null===this._unlinkedRecords?null:this._unlinkedRecords.get(r,null);return null!==s?e=this._reinsertAfter(s,e._prev,i):e.currentIndex!=i&&(e.currentIndex=i,this._addToMoves(e,i)),e}_truncate(e){for(;null!==e;){const t=e._next;this._addToRemovals(this._unlink(e)),e=t}null!==this._unlinkedRecords&&this._unlinkedRecords.clear(),null!==this._additionsTail&&(this._additionsTail._nextAdded=null),null!==this._movesTail&&(this._movesTail._nextMoved=null),null!==this._itTail&&(this._itTail._next=null),null!==this._removalsTail&&(this._removalsTail._nextRemoved=null),null!==this._identityChangesTail&&(this._identityChangesTail._nextIdentityChange=null)}_reinsertAfter(e,t,r){null!==this._unlinkedRecords&&this._unlinkedRecords.remove(e);const i=e._prevRemoved,s=e._nextRemoved;return null===i?this._removalsHead=s:i._nextRemoved=s,null===s?this._removalsTail=i:s._prevRemoved=i,this._insertAfter(e,t,r),this._addToMoves(e,r),e}_moveAfter(e,t,r){return this._unlink(e),this._insertAfter(e,t,r),this._addToMoves(e,r),e}_addAfter(e,t,r){return this._insertAfter(e,t,r),this._additionsTail=null===this._additionsTail?this._additionsHead=e:this._additionsTail._nextAdded=e,e}_insertAfter(e,t,r){const i=null===t?this._itHead:t._next;return e._next=i,e._prev=t,null===i?this._itTail=e:i._prev=e,null===t?this._itHead=e:t._next=e,null===this._linkedRecords&&(this._linkedRecords=new aC),this._linkedRecords.put(e),e.currentIndex=r,e}_remove(e){return this._addToRemovals(this._unlink(e))}_unlink(e){null!==this._linkedRecords&&this._linkedRecords.remove(e);const t=e._prev,r=e._next;return null===t?this._itHead=r:t._next=r,null===r?this._itTail=t:r._prev=t,e}_addToMoves(e,t){return e.previousIndex===t||(this._movesTail=null===this._movesTail?this._movesHead=e:this._movesTail._nextMoved=e),e}_addToRemovals(e){return null===this._unlinkedRecords&&(this._unlinkedRecords=new aC),this._unlinkedRecords.put(e),e.currentIndex=null,e._nextRemoved=null,null===this._removalsTail?(this._removalsTail=this._removalsHead=e,e._prevRemoved=null):(e._prevRemoved=this._removalsTail,this._removalsTail=this._removalsTail._nextRemoved=e),e}_addIdentityChange(e,t){return e.item=t,this._identityChangesTail=null===this._identityChangesTail?this._identityChangesHead=e:this._identityChangesTail._nextIdentityChange=e,e}}class Wk{constructor(e,t){this.item=e,this.trackById=t,this.currentIndex=null,this.previousIndex=null,this._nextPrevious=null,this._prev=null,this._next=null,this._prevDup=null,this._nextDup=null,this._prevRemoved=null,this._nextRemoved=null,this._nextAdded=null,this._nextMoved=null,this._nextIdentityChange=null}}class qk{constructor(){this._head=null,this._tail=null}add(e){null===this._head?(this._head=this._tail=e,e._nextDup=null,e._prevDup=null):(this._tail._nextDup=e,e._prevDup=this._tail,e._nextDup=null,this._tail=e)}get(e,t){let r;for(r=this._head;null!==r;r=r._nextDup)if((null===t||t<=r.currentIndex)&&Object.is(r.trackById,e))return r;return null}remove(e){const t=e._prevDup,r=e._nextDup;return null===t?this._head=r:t._nextDup=r,null===r?this._tail=t:r._prevDup=t,null===this._head}}class aC{constructor(){this.map=new Map}put(e){const t=e.trackById;let r=this.map.get(t);r||(r=new qk,this.map.set(t,r)),r.add(e)}get(e,t){const i=this.map.get(e);return i?i.get(e,t):null}remove(e){const t=e.trackById;return this.map.get(t).remove(e)&&this.map.delete(t),e}get isEmpty(){return 0===this.map.size}clear(){this.map.clear()}}function cC(n,e,t){const r=n.previousIndex;if(null===r)return r;let i=0;return t&&r{class n{constructor(t){this.factories=t}static create(t,r){if(null!=r){const i=r.factories.slice();t=t.concat(i)}return new n(t)}static extend(t){return{provide:n,useFactory:r=>n.create(t,r||lC()),deps:[[n,new Sd,new Dd]]}}find(t){const r=this.factories.find(i=>i.supports(t));if(null!=r)return r;throw new xt(901,!1)}}return n.\u0275prov=Jn({token:n,providedIn:"root",factory:lC}),n})();const Jk=WI(null,"core",[]);let e6=(()=>{class n{constructor(t){}}return n.\u0275fac=function(t){return new(t||n)(On(U0))},n.\u0275mod=nl({type:n}),n.\u0275inj=vc({}),n})(),lh=null;function Kl(){return lh}const To=new an("DocumentToken");class G6{constructor(e,t,r,i){this.$implicit=e,this.ngForOf=t,this.index=r,this.count=i}get first(){return 0===this.index}get last(){return this.index===this.count-1}get even(){return this.index%2==0}get odd(){return!this.even}}let DC=(()=>{class n{constructor(t,r,i){this._viewContainer=t,this._template=r,this._differs=i,this._ngForOf=null,this._ngForOfDirty=!0,this._differ=null}set ngForOf(t){this._ngForOf=t,this._ngForOfDirty=!0}set ngForTrackBy(t){this._trackByFn=t}get ngForTrackBy(){return this._trackByFn}set ngForTemplate(t){t&&(this._template=t)}ngDoCheck(){if(this._ngForOfDirty){this._ngForOfDirty=!1;const t=this._ngForOf;!this._differ&&t&&(this._differ=this._differs.find(t).create(this.ngForTrackBy))}if(this._differ){const t=this._differ.diff(this._ngForOf);t&&this._applyChanges(t)}}_applyChanges(t){const r=this._viewContainer;t.forEachOperation((i,s,o)=>{if(null==i.previousIndex)r.createEmbeddedView(this._template,new G6(i.item,this._ngForOf,-1,-1),null===o?void 0:o);else if(null==o)r.remove(null===s?void 0:s);else if(null!==s){const a=r.get(s);r.move(a,o),SC(a,i)}});for(let i=0,s=r.length;i{SC(r.get(i.currentIndex),i)})}static ngTemplateContextGuard(t,r){return!0}}return n.\u0275fac=function(t){return new(t||n)(qt(eo),qt(So),qt(uh))},n.\u0275dir=is({type:n,selectors:[["","ngFor","","ngForOf",""]],inputs:{ngForOf:"ngForOf",ngForTrackBy:"ngForTrackBy",ngForTemplate:"ngForTemplate"},standalone:!0}),n})();function SC(n,e){n.context.$implicit=e.item}let bB=(()=>{class n{}return n.\u0275fac=function(t){return new(t||n)},n.\u0275mod=nl({type:n}),n.\u0275inj=vc({}),n})();class sm extends class $B extends class r6{}{constructor(){super(...arguments),this.supportsDOMEvents=!0}}{static makeCurrent(){!function n6(n){lh||(lh=n)}(new sm)}onAndCancel(e,t,r){return e.addEventListener(t,r,!1),()=>{e.removeEventListener(t,r,!1)}}dispatchEvent(e,t){e.dispatchEvent(t)}remove(e){e.parentNode&&e.parentNode.removeChild(e)}createElement(e,t){return(t=t||this.getDefaultDocument()).createElement(e)}createHtmlDocument(){return document.implementation.createHTMLDocument("fakeTitle")}getDefaultDocument(){return document}isElementNode(e){return e.nodeType===Node.ELEMENT_NODE}isShadowRoot(e){return e instanceof DocumentFragment}getGlobalEventTarget(e,t){return"window"===t?window:"document"===t?e:"body"===t?e.body:null}getBaseHref(e){const t=function GB(){return zl=zl||document.querySelector("base"),zl?zl.getAttribute("href"):null}();return null==t?null:function zB(n){bh=bh||document.createElement("a"),bh.setAttribute("href",n);const e=bh.pathname;return"/"===e.charAt(0)?e:`/${e}`}(t)}resetBaseElement(){zl=null}getUserAgent(){return window.navigator.userAgent}getCookie(e){return function K6(n,e){e=encodeURIComponent(e);for(const t of n.split(";")){const r=t.indexOf("="),[i,s]=-1==r?[t,""]:[t.slice(0,r),t.slice(r+1)];if(i.trim()===e)return decodeURIComponent(s)}return null}(document.cookie,e)}}let bh,zl=null;const MC=new an("TRANSITION_ID"),qB=[{provide:kI,useFactory:function WB(n,e,t){return()=>{t.get(ih).donePromise.then(()=>{const r=Kl(),i=e.querySelectorAll(`style[ng-transition="${n}"]`);for(let s=0;s{class n{build(){return new XMLHttpRequest}}return n.\u0275fac=function(t){return new(t||n)},n.\u0275prov=Jn({token:n,factory:n.\u0275fac}),n})();const _h=new an("EventManagerPlugins");let Dh=(()=>{class n{constructor(t,r){this._zone=r,this._eventNameToPlugin=new Map,t.forEach(i=>i.manager=this),this._plugins=t.slice().reverse()}addEventListener(t,r,i){return this._findPluginFor(r).addEventListener(t,r,i)}addGlobalEventListener(t,r,i){return this._findPluginFor(r).addGlobalEventListener(t,r,i)}getZone(){return this._zone}_findPluginFor(t){const r=this._eventNameToPlugin.get(t);if(r)return r;const i=this._plugins;for(let s=0;s{class n{constructor(){this._stylesSet=new Set}addStyles(t){const r=new Set;t.forEach(i=>{this._stylesSet.has(i)||(this._stylesSet.add(i),r.add(i))}),this.onStylesAdded(r)}onStylesAdded(t){}getAllStyles(){return Array.from(this._stylesSet)}}return n.\u0275fac=function(t){return new(t||n)},n.\u0275prov=Jn({token:n,factory:n.\u0275fac}),n})(),Wl=(()=>{class n extends LC{constructor(t){super(),this._doc=t,this._hostNodes=new Map,this._hostNodes.set(t.head,[])}_addStylesToHost(t,r,i){t.forEach(s=>{const o=this._doc.createElement("style");o.textContent=s,i.push(r.appendChild(o))})}addHost(t){const r=[];this._addStylesToHost(this._stylesSet,t,r),this._hostNodes.set(t,r)}removeHost(t){const r=this._hostNodes.get(t);r&&r.forEach(kC),this._hostNodes.delete(t)}onStylesAdded(t){this._hostNodes.forEach((r,i)=>{this._addStylesToHost(t,i,r)})}ngOnDestroy(){this._hostNodes.forEach(t=>t.forEach(kC))}}return n.\u0275fac=function(t){return new(t||n)(On(To))},n.\u0275prov=Jn({token:n,factory:n.\u0275fac}),n})();function kC(n){Kl().remove(n)}const om={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/",math:"http://www.w3.org/1998/MathML/"},am=/%COMP%/g;function Sh(n,e,t){for(let r=0;r{if("__ngUnwrap__"===e)return n;!1===n(e)&&(e.preventDefault(),e.returnValue=!1)}}let cm=(()=>{class n{constructor(t,r,i){this.eventManager=t,this.sharedStylesHost=r,this.appId=i,this.rendererByCompId=new Map,this.defaultRenderer=new um(t)}createRenderer(t,r){if(!t||!r)return this.defaultRenderer;switch(r.encapsulation){case zs.Emulated:{let i=this.rendererByCompId.get(r.id);return i||(i=new n5(this.eventManager,this.sharedStylesHost,r,this.appId),this.rendererByCompId.set(r.id,i)),i.applyToHost(t),i}case 1:case zs.ShadowDom:return new r5(this.eventManager,this.sharedStylesHost,t,r);default:if(!this.rendererByCompId.has(r.id)){const i=Sh(r.id,r.styles,[]);this.sharedStylesHost.addStyles(i),this.rendererByCompId.set(r.id,this.defaultRenderer)}return this.defaultRenderer}}begin(){}end(){}}return n.\u0275fac=function(t){return new(t||n)(On(Dh),On(Wl),On(Vl))},n.\u0275prov=Jn({token:n,factory:n.\u0275fac}),n})();class um{constructor(e){this.eventManager=e,this.data=Object.create(null),this.destroyNode=null}destroy(){}createElement(e,t){return t?document.createElementNS(om[t]||t,e):document.createElement(e)}createComment(e){return document.createComment(e)}createText(e){return document.createTextNode(e)}appendChild(e,t){(HC(e)?e.content:e).appendChild(t)}insertBefore(e,t,r){e&&(HC(e)?e.content:e).insertBefore(t,r)}removeChild(e,t){e&&e.removeChild(t)}selectRootElement(e,t){let r="string"==typeof e?document.querySelector(e):e;if(!r)throw new Error(`The selector "${e}" did not match any elements`);return t||(r.textContent=""),r}parentNode(e){return e.parentNode}nextSibling(e){return e.nextSibling}setAttribute(e,t,r,i){if(i){t=i+":"+t;const s=om[i];s?e.setAttributeNS(s,t,r):e.setAttribute(t,r)}else e.setAttribute(t,r)}removeAttribute(e,t,r){if(r){const i=om[r];i?e.removeAttributeNS(i,t):e.removeAttribute(`${r}:${t}`)}else e.removeAttribute(t)}addClass(e,t){e.classList.add(t)}removeClass(e,t){e.classList.remove(t)}setStyle(e,t,r,i){i&(Mi.DashCase|Mi.Important)?e.style.setProperty(t,r,i&Mi.Important?"important":""):e.style[t]=r}removeStyle(e,t,r){r&Mi.DashCase?e.style.removeProperty(t):e.style[t]=""}setProperty(e,t,r){e[t]=r}setValue(e,t){e.nodeValue=t}listen(e,t,r){return"string"==typeof e?this.eventManager.addGlobalEventListener(e,t,UC(r)):this.eventManager.addEventListener(e,t,UC(r))}}function HC(n){return"TEMPLATE"===n.tagName&&void 0!==n.content}class n5 extends um{constructor(e,t,r,i){super(e),this.component=r;const s=Sh(i+"-"+r.id,r.styles,[]);t.addStyles(s),this.contentAttr=function JB(n){return"_ngcontent-%COMP%".replace(am,n)}(i+"-"+r.id),this.hostAttr=function e5(n){return"_nghost-%COMP%".replace(am,n)}(i+"-"+r.id)}applyToHost(e){super.setAttribute(e,this.hostAttr,"")}createElement(e,t){const r=super.createElement(e,t);return super.setAttribute(r,this.contentAttr,""),r}}class r5 extends um{constructor(e,t,r,i){super(e),this.sharedStylesHost=t,this.hostEl=r,this.shadowRoot=r.attachShadow({mode:"open"}),this.sharedStylesHost.addHost(this.shadowRoot);const s=Sh(i.id,i.styles,[]);for(let o=0;o{class n extends OC{constructor(t){super(t)}supports(t){return!0}addEventListener(t,r,i){return t.addEventListener(r,i,!1),()=>this.removeEventListener(t,r,i)}removeEventListener(t,r,i){return t.removeEventListener(r,i)}}return n.\u0275fac=function(t){return new(t||n)(On(To))},n.\u0275prov=Jn({token:n,factory:n.\u0275fac}),n})();const KC=["alt","control","meta","shift"],s5={"\b":"Backspace","\t":"Tab","\x7f":"Delete","\x1b":"Escape",Del:"Delete",Esc:"Escape",Left:"ArrowLeft",Right:"ArrowRight",Up:"ArrowUp",Down:"ArrowDown",Menu:"ContextMenu",Scroll:"ScrollLock",Win:"OS"},o5={alt:n=>n.altKey,control:n=>n.ctrlKey,meta:n=>n.metaKey,shift:n=>n.shiftKey};let a5=(()=>{class n extends OC{constructor(t){super(t)}supports(t){return null!=n.parseEventName(t)}addEventListener(t,r,i){const s=n.parseEventName(r),o=n.eventCallback(s.fullKey,i,this.manager.getZone());return this.manager.getZone().runOutsideAngular(()=>Kl().onAndCancel(t,s.domEventName,o))}static parseEventName(t){const r=t.toLowerCase().split("."),i=r.shift();if(0===r.length||"keydown"!==i&&"keyup"!==i)return null;const s=n._normalizeKey(r.pop());let o="",a=r.indexOf("code");if(a>-1&&(r.splice(a,1),o="code."),KC.forEach(m=>{const T=r.indexOf(m);T>-1&&(r.splice(T,1),o+=m+".")}),o+=s,0!=r.length||0===s.length)return null;const c={};return c.domEventName=i,c.fullKey=o,c}static matchEventFullKeyCode(t,r){let i=s5[t.key]||t.key,s="";return r.indexOf("code.")>-1&&(i=t.code,s="code."),!(null==i||!i)&&(i=i.toLowerCase()," "===i?i="space":"."===i&&(i="dot"),KC.forEach(o=>{o!==i&&(0,o5[o])(t)&&(s+=o+".")}),s+=i,s===r)}static eventCallback(t,r,i){return s=>{n.matchEventFullKeyCode(s,t)&&i.runGuarded(()=>r(s))}}static _normalizeKey(t){return"esc"===t?"escape":t}}return n.\u0275fac=function(t){return new(t||n)(On(To))},n.\u0275prov=Jn({token:n,factory:n.\u0275fac}),n})();const $C=[{provide:UI,useValue:"browser"},{provide:FI,useValue:function c5(){sm.makeCurrent()},multi:!0},{provide:To,useFactory:function l5(){return function QN(n){jg=n}(document),document},deps:[]}],f5=WI(Jk,"browser",$C),GC=new an(""),zC=[{provide:sh,useClass:class QB{addToWindow(e){jn.getAngularTestability=(r,i=!0)=>{const s=e.findTestabilityInTree(r,i);if(null==s)throw new Error("Could not find testability for element.");return s},jn.getAllAngularTestabilities=()=>e.getAllTestabilities(),jn.getAllAngularRootElements=()=>e.getAllRootElements(),jn.frameworkStabilizers||(jn.frameworkStabilizers=[]),jn.frameworkStabilizers.push(r=>{const i=jn.getAllAngularTestabilities();let s=i.length,o=!1;const a=function(c){o=o||c,s--,0==s&&r(o)};i.forEach(function(c){c.whenStable(a)})})}findTestabilityInTree(e,t,r){return null==t?null:e.getTestability(t)??(r?Kl().isShadowRoot(t)?this.findTestabilityInTree(e,t.host,!0):this.findTestabilityInTree(e,t.parentElement,!0):null)}},deps:[]},{provide:$I,useClass:O0,deps:[ai,L0,sh]},{provide:O0,useClass:O0,deps:[ai,L0,sh]}],WC=[{provide:Xg,useValue:"root"},{provide:Hc,useFactory:function u5(){return new Hc},deps:[]},{provide:_h,useClass:i5,multi:!0,deps:[To,ai,UI]},{provide:_h,useClass:a5,multi:!0,deps:[To]},{provide:cm,useClass:cm,deps:[Dh,Wl,Vl]},{provide:W_,useExisting:cm},{provide:LC,useExisting:Wl},{provide:Wl,useClass:Wl,deps:[To]},{provide:Dh,useClass:Dh,deps:[_h,ai]},{provide:class CB{},useClass:YB,deps:[]},[]];let d5=(()=>{class n{constructor(t){}static withServerTransition(t){return{ngModule:n,providers:[{provide:Vl,useValue:t.appId},{provide:MC,useExisting:Vl},qB]}}}return n.\u0275fac=function(t){return new(t||n)(On(GC,12))},n.\u0275mod=nl({type:n}),n.\u0275inj=vc({providers:[...WC,...zC],imports:[bB,e6]}),n})();typeof window<"u"&&window;class _5 extends Sr{constructor(e){super(),this._value=e}get value(){return this.getValue()}_subscribe(e){const t=super._subscribe(e);return!t.closed&&e.next(this._value),t}getValue(){const{hasError:e,thrownError:t,_value:r}=this;if(e)throw t;return this._throwIfClosed(),r}next(e){super.next(this._value=e)}}function YC(n,e,t,r,i,s,o){try{var a=n[s](o),c=a.value}catch(m){return void t(m)}a.done?e(c):Promise.resolve(c).then(r,i)}function V(n){return function(){var e=this,t=arguments;return new Promise(function(r,i){var s=n.apply(e,t);function o(c){YC(s,r,i,o,a,"next",c)}function a(c){YC(s,r,i,o,a,"throw",c)}o(void 0)})}}function ZC(n){this.wrapped=n}function ql(n){var e,t;function i(o,a){try{var c=n[o](a),m=c.value,T=m instanceof ZC;Promise.resolve(T?m.wrapped:m).then(function(R){T?i("return"===o?"return":"next",R):s(c.done?"return":"normal",R)},function(R){i("throw",R)})}catch(R){s("throw",R)}}function s(o,a){switch(o){case"return":e.resolve({value:a,done:!0});break;case"throw":e.reject(a);break;default:e.resolve({value:a,done:!1})}(e=e.next)?i(e.key,e.arg):t=null}this._invoke=function r(o,a){return new Promise(function(c,m){var T={key:o,arg:a,resolve:c,reject:m,next:null};t?t=t.next=T:(e=t=T,i(o,a))})},"function"!=typeof n.return&&(this.return=void 0)}function un(n){return function(){return new ql(n.apply(this,arguments))}}function ct(n){return new ZC(n)}function Tt(n){var e,t,r,i=2;for(typeof Symbol<"u"&&(t=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(t&&null!=(e=n[t]))return e.call(n);if(r&&null!=(e=n[r]))return new Ih(e.call(n));t="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function Ih(n){function e(t){if(Object(t)!==t)return Promise.reject(new TypeError(t+" is not an object."));var r=t.done;return Promise.resolve(t.value).then(function(i){return{value:i,done:r}})}return(Ih=function(r){this.s=r,this.n=r.next}).prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(r){var i=this.s.return;return void 0===i?Promise.resolve({value:r,done:!0}):e(i.apply(this.s,arguments))},throw:function(r){var i=this.s.return;return void 0===i?Promise.reject(r):e(i.apply(this.s,arguments))}},new Ih(n)}function jr(n,e){var t={},r=!1;function i(s,o){return r=!0,o=new Promise(function(a){a(n[s](o))}),{done:!1,value:e(o)}}return t[typeof Symbol<"u"&&Symbol.iterator||"@@iterator"]=function(){return this},t.next=function(s){return r?(r=!1,s):i("next",s)},"function"==typeof n.throw&&(t.throw=function(s){if(r)throw r=!1,s;return i("throw",s)}),"function"==typeof n.return&&(t.return=function(s){return r?(r=!1,s):i("return",s)}),t}function ca(n=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.alloc?globalThis.Buffer.alloc(n):new Uint8Array(n)}function xo(n=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?globalThis.Buffer.allocUnsafe(n):new Uint8Array(n)}function or(n,e){e||(e=n.reduce((i,s)=>i+s.length,0));const t=xo(e);let r=0;for(const i of n)t.set(i,r),r+=i.length;return t}function $r(n,e){if(n===e)return!0;if(n.byteLength!==e.byteLength)return!1;for(let t=0;t0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!dm(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!dm(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=JC(this.bufs,e);return t.buf[t.index]}set(e,t){const r=JC(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}slice(e,t){const{bufs:r,length:i}=this._subList(e,t);return or(r,i)}subarray(e,t){const{bufs:r,length:i}=this._subList(e,t);return 1===r.length?r[0]:or(r,i)}sublist(e,t){const{bufs:r,length:i}=this._subList(e,t),s=new $n;return s.length=i,s.bufs=r,s}_subList(e,t){if((e=e??0)<0&&(e=this.length+e),(t=t??this.length)<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:[...this.bufs],length:this.length};const r=[];let i=0;for(let s=0;s=c)continue;const m=e>=a&&ea&&t<=c;if(m&&T){if(e===a&&t===c){r.push(o);break}const R=e-a;r.push(o.subarray(R,R+(t-e)));break}if(m){if(0===e){r.push(o);continue}r.push(o.subarray(e-a))}else{if(T){if(t===c){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}}return{bufs:r,length:t-e}}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=xo(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const i=ca(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,r),this.write(i,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const i=ca(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,r),this.write(i,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const i=ca(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,r),this.write(i,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=xo(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const i=ca(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,r),this.write(i,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const i=ca(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,r),this.write(i,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const i=ca(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,r),this.write(i,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const i=ca(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,r),this.write(i,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const i=ca(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,r),this.write(i,e)}equals(e){if(null==e||!(e instanceof $n)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;ti+s.byteLength,0)),r.length=t,r}}class e2{constructor(e){if(!(e>0)||0!=(e-1&e))throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class hm{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new e2(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){null!=e?.value&&(this.size+=this.calculateSize(e.value)),this.head.push(e)||(this.head=this.head.next=new e2(2*this.head.buffer.length),this.head.push(e))}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}function lu(n={}){return t2(t=>{const r=t.shift();if(null==r)return{done:!0};if(null!=r.error)throw r.error;return{done:!0===r.done,value:r.value}},n)}function t2(n,e){let i,s,o,t=(e=e??{}).onEnd,r=new hm;const a=function(){var X=V(function*(){return r.isEmpty()?o?{done:!0}:yield new Promise((ae,he)=>{s=Ae=>{s=null,r.push(Ae);try{ae(n(r))}catch(ue){he(ue)}return i}}):n(r)});return function(){return X.apply(this,arguments)}}(),c=X=>null!=s?s(X):(r.push(X),i),T=X=>{if(o)return i;if(!0!==e?.objectMode&&null==X?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:X})},R=X=>o?i:(o=!0,null!=X?(X=>(r=new hm,null!=s?s({error:X}):(r.push({error:X}),i)))(X):c({done:!0}));if(i={[Symbol.asyncIterator](){return this},next:a,return:()=>(r=new hm,R(),{done:!0}),throw:X=>(R(X),{done:!0}),push:T,end:R,get readableLength(){return r.size}},null==t)return i;const Q=i;return i={[Symbol.asyncIterator](){return this},next:()=>Q.next(),throw:X=>(Q.throw(X),null!=t&&(t(X),t=void 0),{done:!0}),return:()=>(Q.return(),null!=t&&(t(),t=void 0),{done:!0}),push:T,end:X=>(Q.end(X),null!=t&&(t(X),t=void 0),i),get readableLength(){return Q.readableLength}},i}function pm(){const n={};return n.promise=new Promise((e,t)=>{n.resolve=e,n.reject=t}),n}function Ch(n){const e=lu(),t=function D5(n){const e=un(function*(){let t=yield,r=new $n;var o,i=!1,s=!1;try{for(var c,a=Tt(n);i=!(c=yield ct(a.next())).done;i=!1){const m=c.value;if(null!=t)for(r.append(m);r.length>=t;){const T=r.sublist(0,t);if(r.consume(t),t=yield T,null==t){r.length>0&&(t=yield r,r=new $n);break}}else r.append(m),t=yield r,r=new $n}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield ct(a.return()))}finally{if(s)throw o}}if(null!=t)throw Object.assign(new Error(`stream ended before ${t} bytes became available`),{code:"ERR_UNDER_READ",buffer:r})})();return e.next(),e}(n.source),r=pm();let i;const s=n.sink(un(function*(){yield*jr(Tt(e),ct);const a=yield ct(r.promise);yield*jr(Tt(a),ct)})());s.catch(a=>{i=a});const o={sink:(a=V(function*(c){return null!=i?yield Promise.reject(i):(r.resolve(c),yield s)}),function(m){return a.apply(this,arguments)}),source:t};var a;return{reader:t,writer:e,stream:o,rest:()=>e.end(),write:e.push,read:function(){var a=V(function*(){const c=yield t.next();if(null!=c.value)return c.value});return function(){return a.apply(this,arguments)}}()}}function gm(n){return n instanceof Uint8Array?{get:e=>n[e],set(e,t){n[e]=t}}:{get:e=>n.get(e),set(e,t){n.set(e,t)}}}const n2=4294967296;class qr{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(!0===e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const t=1+~this.lo>>>0;let r=~this.hi>>>0;return 0===t&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){const e=-(1&this.lo);return new qr((this.hi>>>1^e)>>>0,((this.lo>>>1|this.hi<<31)^e)>>>0)}zzEncode(){const e=this.hi>>31;return new qr(((this.hi<<1|this.lo>>>31)^e)>>>0,(this.lo<<1^e)>>>0)}toBytes(e,t=0){const r=gm(e);for(;this.hi>0;)r.set(t++,127&this.lo|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)r.set(t++,127&this.lo|128),this.lo=this.lo>>>7;r.set(t++,this.lo)}static fromBigInt(e){if(0n===e)return new qr;const t=e<0;t&&(e=-e);let r=0|Number(e>>32n),i=0|Number(e-(BigInt(r)<<32n));return t&&(r=~r>>>0,i=~i>>>0,++i>n2&&(i=0,++r>n2&&(r=0))),new qr(r,i)}static fromNumber(e){if(0===e)return new qr;const t=e<0;t&&(e=-e);let r=e>>>0,i=(e-r)/4294967296>>>0;return t&&(i=~i>>>0,r=~r>>>0,++r>4294967295&&(r=0,++i>4294967295&&(i=0))),new qr(i,r)}static fromBytes(e,t=0){const r=gm(e),i=new qr;let s=0;if(e.length-t>4){for(;s<4;++s)if(i.lo=(i.lo|(127&r.get(t))<<7*s)>>>0,r.get(t++)<128)return i;if(i.lo=(i.lo|(127&r.get(t))<<28)>>>0,i.hi=(i.hi|(127&r.get(t))>>4)>>>0,r.get(t++)<128)return i;s=0}else for(;s<4;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(127&r.get(t))<<7*s)>>>0,r.get(t++)<128)return i}if(e.length-t>4){for(;s<5;++s)if(i.hi=(i.hi|(127&r.get(t))<<7*s+3)>>>0,r.get(t++)<128)return i}else if(t=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(127&r.get(t))<<7*s+3)>>>0,r.get(t++)<128)return i}throw RangeError("invalid varint encoding")}}const I5=Math.pow(2,7),C5=Math.pow(2,14),T5=Math.pow(2,21),A5=Math.pow(2,28),x5=Math.pow(2,35),R5=Math.pow(2,42),P5=Math.pow(2,49),N5=Math.pow(2,56),M5=Math.pow(2,63),Qt={encodingLength:n=>nNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return null==e&&(e=xo(Qt.encodingLength(n))),qr.fromNumber(n).toBytes(e,t),e},decode:(n,e=0)=>qr.fromBytes(n,e).toNumber(!0)},Th={encodingLength:n=>n<0?10:Qt.encodingLength(n),encode:(n,e,t)=>(null==e&&(e=xo(Th.encodingLength(n))),n<0?(qr.fromNumber(n).toBytes(e,t),e):Qt.encode(n,e,t)),decode:(n,e=0)=>qr.fromBytes(n,e).toNumber(!1)},ym={encodingLength:n=>Qt.encodingLength(n>=0?2*n:-2*n-1),encode:(n,e,t)=>Qt.encode(n=n>=0?2*n:-2*n-1,e,t),decode(n,e=0){const t=Qt.decode(n,e);return 0!=(1&t)?(t+1)/-2:t/2}},Ah=n=>{const e=Qt.encodingLength(n),t=function O5(n){return null!=globalThis?.Buffer?.allocUnsafe?globalThis.Buffer.allocUnsafe(n):new Uint8Array(n)}(e);return Qt.encode(n,t),Ah.bytes=e,t};function to(n){const e=(n=n??{}).lengthEncoder??Ah;return function(){var r=un(function*(i){var a,s=!1,o=!1;try{for(var m,c=Tt(i);s=!(m=yield ct(c.next())).done;s=!1){const T=m.value,R=e(T.byteLength);R instanceof Uint8Array?yield R:yield*jr(Tt(R),ct),T instanceof Uint8Array?yield T:yield*jr(Tt(T),ct)}}catch(T){o=!0,a=T}finally{try{s&&null!=c.return&&(yield ct(c.return()))}finally{if(o)throw a}}});return function(s){return r.apply(this,arguments)}}()}Ah.bytes=0,to.single=(n,e)=>new $n(((e=e??{}).lengthEncoder??Ah)(n.byteLength),n);var se=N(2535),ua=(()=>{return(n=ua||(ua={}))[n.LENGTH=0]="LENGTH",n[n.DATA=1]="DATA",ua;var n})();const mm=n=>{const e=Qt.decode(n);return mm.bytes=Qt.encodingLength(e),e};function Ms(n){return function(){var t=un(function*(r){const i=new $n;let s=ua.LENGTH,o=-1;const a=n?.lengthDecoder??mm,c=n?.maxLengthLength??8,m=n?.maxDataLength??4194304;var k,T=!1,R=!1;try{for(var Q,U=Tt(r);T=!(Q=yield ct(U.next())).done;T=!1)for(i.append(Q.value);i.byteLength>0;){if(s===ua.LENGTH)try{if(o=a(i),o<0)throw se(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>m)throw se(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");i.consume(a.bytes),null!=n?.onLength&&n.onLength(o),s=ua.DATA}catch(ae){if(ae instanceof RangeError){if(i.byteLength>c)throw se(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw ae}if(s===ua.DATA){if(i.byteLength0)throw se(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")});return function(i){return t.apply(this,arguments)}}()}function r2(n,e={}){const t=Ch(n),r=Ms.fromReader(t.reader,e),i={read:(s=V(function*(o){const{value:a}=yield t.reader.next(o);if(null==a)throw new Error("Value is null");return a}),function(a){return s.apply(this,arguments)}),readLP:function(){var s=V(function*(){const{value:o}=yield r.next();if(null==o)throw new Error("Value is null");return o});return function(){return s.apply(this,arguments)}}(),readPB:function(){var s=V(function*(o){const a=yield i.readLP();if(null==a)throw new Error("Value is null");const c=a instanceof Uint8Array?a:a.slice();return o.decode(c)});return function(a){return s.apply(this,arguments)}}(),write:s=>{s instanceof Uint8Array?t.writer.push(s):t.writer.push(s.slice())},writeLP:s=>{i.write(to.single(s,e))},writePB:(s,o)=>{i.writeLP(o.encode(s))},pb:s=>{return{read:(o=V(function*(){return yield i.readPB(s)}),function(){return o.apply(this,arguments)}),write:o=>i.writePB(o,s)};var o},unwrap:()=>(t.rest(),t.stream)};var s;return i}function i2(){const n=pm();let e=!1;return{sink:(t=V(function*(r){if(e)throw new Error("already piped");e=!0,n.resolve(r)}),function(i){return t.apply(this,arguments)}),source:un(function*(){const t=yield ct(n.promise);yield*jr(Tt(t),ct)})()};var t}mm.bytes=0,Ms.fromReader=(n,e)=>{let t=1;const r=un(function*(){for(;;)try{const{done:s,value:o}=yield ct(n.next(t));if(!0===s)return;null!=o&&(yield o)}catch(s){if("ERR_UNDER_READ"===s.code)return{done:!0,value:null};throw s}finally{t=1}})();return Ms({...e??{},onLength:s=>{t=s}})(r)};var xh=N(5061);const s2=n=>null!=n&&("function"==typeof n[Symbol.asyncIterator]||"function"==typeof n[Symbol.iterator]||"function"==typeof n.next),vm=n=>null!=n&&"function"==typeof n.sink&&s2(n.source),U5=n=>e=>{const t=n.sink(e);if(null!=t.then){const r=lu({objectMode:!0});return t.then(()=>{r.end()},s=>{r.end(s)}),xh(r,function(){var s=un(function*(){yield*jr(Tt(n.source),ct),r.end()});return function(){return s.apply(this,arguments)}}()())}return n.source};function Ln(n,...e){if(vm(n)){const r=n;n=()=>r.source}else if(s2(n)){const r=n;n=()=>r}const t=[n,...e];if(t.length>1&&vm(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let r=1;r{let e;for(;n.length>0;)e=n.shift()(e);return e})(...t)}const Ql=65535,V5=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);var H5=N(5705),Em=N(5006),a2=N(893),c2=N(5876);const K5={hashSHA256:n=>(0,a2.vp)(n),getHKDF(n,e){const i=new H5.t(a2.mE,e,n).expand(96);return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){const n=Em.Au();return{publicKey:n.publicKey,privateKey:n.secretKey}},generateX25519KeyPairFromSeed(n){const e=Em._w(n);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey:(n,e)=>Em.gi(n,e),chaCha20Poly1305Encrypt:(n,e,t,r)=>new c2.OK(r).seal(e,n,t),chaCha20Poly1305Decrypt:(n,e,t,r)=>new c2.OK(r).open(e,n,t)},Rh=n=>{const e=globalThis.Buffer?globalThis.Buffer.allocUnsafe(2):new Uint8Array(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,n,!1),e};Rh.bytes=2;const Ph=n=>{if(n.length<2)throw RangeError("Could not decode int16BE");return n instanceof Uint8Array?new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,!1):n.getUint16(0)};function u2(n){return or([n.ne,n.ciphertext],n.ne.length+n.ciphertext.length)}function l2(n){return or([n.ne,n.ns,n.ciphertext],n.ne.length+n.ns.length+n.ciphertext.length)}function wm(n){if(n.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:n.subarray(0,32),ciphertext:n.subarray(32,n.length),ns:new Uint8Array(0)}}function bm(n){if(n.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:n.subarray(0,32),ns:n.subarray(32,80),ciphertext:n.subarray(80,n.length)}}Ph.bytes=2;var _m=N(3863),Dm=N.n(_m);const Sm=_m.Reader;function ui(n,e){const t=Sm.create(n instanceof Uint8Array?n:n.subarray());return e.decode(t)}["uint64","int64","sint64","fixed64","sfixed64"].forEach(n=>{const e=Sm.prototype[n];Sm.prototype[n]=function(){return BigInt(e.call(this).toString())}});const Im=_m.Writer;function li(n,e){const t=Im.create();return e.encode(n,t,{lengthDelimited:!1}),t.finish()}["uint64","int64","sint64","fixed64","sfixed64"].forEach(n=>{const e=Im.prototype[n];Im.prototype[n]=function(t){return e.call(this,t.toString())}});var Yl=(()=>{return(n=Yl||(Yl={}))[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32",Yl;var n})();function f2(n,e,t,r){return{name:n,type:e,encode:t,decode:r}}function Nh(n){function e(i){if(null==n[i.toString()])throw new Error("Invalid enum value");return n[i]}return f2("enum",Yl.VARINT,function(s,o){const a=e(s);o.int32(a)},function(s){return e(s.uint32())})}function fi(n,e){return f2("message",Yl.LENGTH_DELIMITED,n,e)}var fu,du,dr=(()=>{return(n=dr||(dr={})).RSA="RSA",n.Ed25519="Ed25519",n.Secp256k1="Secp256k1",dr;var n})(),Mh=(()=>{return(n=Mh||(Mh={}))[n.RSA=0]="RSA",n[n.Ed25519=1]="Ed25519",n[n.Secp256k1=2]="Secp256k1",Mh;var n})();(dr||(dr={})).codec=()=>Nh(Mh),function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.Type)throw new Error('Protocol error: required field "Type" was not found in object');if(r.uint32(8),dr.codec().encode(t.Type,r),null==t.Data)throw new Error('Protocol error: required field "Data" was not found in object');r.uint32(18),r.bytes(t.Data),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={Type:dr.RSA,Data:new Uint8Array(0)},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:i.Type=dr.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(7&o)}}if(null==i.Type)throw new Error('Protocol error: value for required field "Type" was not found in protobuf');if(null==i.Data)throw new Error('Protocol error: value for required field "Data" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(fu||(fu={})),function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.Type)throw new Error('Protocol error: required field "Type" was not found in object');if(r.uint32(8),dr.codec().encode(t.Type,r),null==t.Data)throw new Error('Protocol error: required field "Data" was not found in object');r.uint32(18),r.bytes(t.Data),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={Type:dr.RSA,Data:new Uint8Array(0)},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:i.Type=dr.codec().decode(t);break;case 2:i.Data=t.bytes();break;default:t.skipType(7&o)}}if(null==i.Type)throw new Error('Protocol error: value for required field "Type" was not found in protobuf');if(null==i.Data)throw new Error('Protocol error: value for required field "Data" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(du||(du={})),N(7791),N(2158);var Gn=N(8659);const Z5=function q5(n,e){if(n.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r>>0,ue=new Uint8Array(Ae);Q[X];){var Re=t[Q.charCodeAt(X)];if(255===Re)return;for(var Le=0,Fe=Ae-1;(0!==Re||Le>>0)%256>>>0,Re=Re/256>>>0;if(0!==Re)throw new Error("Non-zero carry");he=Le,X++}if(" "!==Q[X]){for(var wt=Ae-he;wt!==Ae&&0===ue[wt];)wt++;for(var mt=new Uint8Array(ae+(Ae-wt)),Zt=ae;wt!==Ae;)mt[Zt++]=ue[wt++];return mt}}}return{encode:function R(Q){if(Q instanceof Uint8Array||(ArrayBuffer.isView(Q)?Q=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength):Array.isArray(Q)&&(Q=Uint8Array.from(Q))),!(Q instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===Q.length)return"";for(var X=0,ae=0,he=0,Ae=Q.length;he!==Ae&&0===Q[he];)he++,X++;for(var ue=(Ae-he)*T+1>>>0,Re=new Uint8Array(ue);he!==Ae;){for(var Le=Q[he],Fe=0,wt=ue-1;(0!==Le||Fe>>0)%a>>>0,Le=Le/a>>>0;if(0!==Le)throw new Error("Non-zero carry");ae=Fe,he++}for(var mt=ue-ae;mt!==ue&&0===Re[mt];)mt++;for(var Zt=c.repeat(X);mt{if(n instanceof Uint8Array&&"Uint8Array"===n.constructor.name)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw new Error("Unknown type, must be binary type")});class nF{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class rF{constructor(e,t,r){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return d2(this,e)}}class iF{constructor(e){this.decoders=e}or(e){return d2(this,e)}decode(e){const r=this.decoders[e[0]];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const d2=(n,e)=>new iF({...n.decoders||{[n.prefix]:n},...e.decoders||{[e.prefix]:e}});class sF{constructor(e,t,r,i){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=i,this.encoder=new nF(e,t,r),this.decoder=new rF(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Oh=({name:n,prefix:e,encode:t,decode:r})=>new sF(n,e,t,r),Zl=({prefix:n,name:e,alphabet:t})=>{const{encode:r,decode:i}=Z5(t,e);return Oh({prefix:n,name:e,encode:r,decode:s=>hu(i(s))})},Qr=({name:n,prefix:e,bitsPerChar:t,alphabet:r})=>Oh({prefix:e,name:n,encode:i=>((n,e,t)=>{const r="="===e[e.length-1],i=(1<t;)o-=t,s+=e[i&a>>o];if(o&&(s+=e[i&a<((n,e,t,r)=>{const i={};for(let T=0;T=8&&(a-=8,o[m++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(i,r,t,n)}),cF=Oh({prefix:"\0",name:"identity",encode:n=>(n=>(new TextDecoder).decode(n))(n),decode:n=>(n=>(new TextEncoder).encode(n))(n)}),uF=Qr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),lF=Qr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),fF=Zl({prefix:"9",name:"base10",alphabet:"0123456789"}),dF=Qr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),hF=Qr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Ro=Qr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),pF=Qr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gF=Qr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yF=Qr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mF=Qr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vF=Qr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),EF=Qr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wF=Qr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bF=Qr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),_F=Zl({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),DF=Zl({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Ci=Zl({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),SF=Zl({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Lh=Qr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),IF=Qr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),CF=Qr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),TF=Qr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),h2=Array.from("\u{1f680}\u{1fa90}\u2604\u{1f6f0}\u{1f30c}\u{1f311}\u{1f312}\u{1f313}\u{1f314}\u{1f315}\u{1f316}\u{1f317}\u{1f318}\u{1f30d}\u{1f30f}\u{1f30e}\u{1f409}\u2600\u{1f4bb}\u{1f5a5}\u{1f4be}\u{1f4bf}\u{1f602}\u2764\u{1f60d}\u{1f923}\u{1f60a}\u{1f64f}\u{1f495}\u{1f62d}\u{1f618}\u{1f44d}\u{1f605}\u{1f44f}\u{1f601}\u{1f525}\u{1f970}\u{1f494}\u{1f496}\u{1f499}\u{1f622}\u{1f914}\u{1f606}\u{1f644}\u{1f4aa}\u{1f609}\u263a\u{1f44c}\u{1f917}\u{1f49c}\u{1f614}\u{1f60e}\u{1f607}\u{1f339}\u{1f926}\u{1f389}\u{1f49e}\u270c\u2728\u{1f937}\u{1f631}\u{1f60c}\u{1f338}\u{1f64c}\u{1f60b}\u{1f497}\u{1f49a}\u{1f60f}\u{1f49b}\u{1f642}\u{1f493}\u{1f929}\u{1f604}\u{1f600}\u{1f5a4}\u{1f603}\u{1f4af}\u{1f648}\u{1f447}\u{1f3b6}\u{1f612}\u{1f92d}\u2763\u{1f61c}\u{1f48b}\u{1f440}\u{1f62a}\u{1f611}\u{1f4a5}\u{1f64b}\u{1f61e}\u{1f629}\u{1f621}\u{1f92a}\u{1f44a}\u{1f973}\u{1f625}\u{1f924}\u{1f449}\u{1f483}\u{1f633}\u270b\u{1f61a}\u{1f61d}\u{1f634}\u{1f31f}\u{1f62c}\u{1f643}\u{1f340}\u{1f337}\u{1f63b}\u{1f613}\u2b50\u2705\u{1f97a}\u{1f308}\u{1f608}\u{1f918}\u{1f4a6}\u2714\u{1f623}\u{1f3c3}\u{1f490}\u2639\u{1f38a}\u{1f498}\u{1f620}\u261d\u{1f615}\u{1f33a}\u{1f382}\u{1f33b}\u{1f610}\u{1f595}\u{1f49d}\u{1f64a}\u{1f639}\u{1f5e3}\u{1f4ab}\u{1f480}\u{1f451}\u{1f3b5}\u{1f91e}\u{1f61b}\u{1f534}\u{1f624}\u{1f33c}\u{1f62b}\u26bd\u{1f919}\u2615\u{1f3c6}\u{1f92b}\u{1f448}\u{1f62e}\u{1f646}\u{1f37b}\u{1f343}\u{1f436}\u{1f481}\u{1f632}\u{1f33f}\u{1f9e1}\u{1f381}\u26a1\u{1f31e}\u{1f388}\u274c\u270a\u{1f44b}\u{1f630}\u{1f928}\u{1f636}\u{1f91d}\u{1f6b6}\u{1f4b0}\u{1f353}\u{1f4a2}\u{1f91f}\u{1f641}\u{1f6a8}\u{1f4a8}\u{1f92c}\u2708\u{1f380}\u{1f37a}\u{1f913}\u{1f619}\u{1f49f}\u{1f331}\u{1f616}\u{1f476}\u{1f974}\u25b6\u27a1\u2753\u{1f48e}\u{1f4b8}\u2b07\u{1f628}\u{1f31a}\u{1f98b}\u{1f637}\u{1f57a}\u26a0\u{1f645}\u{1f61f}\u{1f635}\u{1f44e}\u{1f932}\u{1f920}\u{1f927}\u{1f4cc}\u{1f535}\u{1f485}\u{1f9d0}\u{1f43e}\u{1f352}\u{1f617}\u{1f911}\u{1f30a}\u{1f92f}\u{1f437}\u260e\u{1f4a7}\u{1f62f}\u{1f486}\u{1f446}\u{1f3a4}\u{1f647}\u{1f351}\u2744\u{1f334}\u{1f4a3}\u{1f438}\u{1f48c}\u{1f4cd}\u{1f940}\u{1f922}\u{1f445}\u{1f4a1}\u{1f4a9}\u{1f450}\u{1f4f8}\u{1f47b}\u{1f910}\u{1f92e}\u{1f3bc}\u{1f975}\u{1f6a9}\u{1f34e}\u{1f34a}\u{1f47c}\u{1f48d}\u{1f4e3}\u{1f942}"),AF=h2.reduce((n,e,t)=>(n[t]=e,n),[]),xF=h2.reduce((n,e,t)=>(n[e.codePointAt(0)]=t,n),[]),NF=Oh({prefix:"\u{1f680}",name:"base256emoji",encode:function RF(n){return n.reduce((e,t)=>e+AF[t],"")},decode:function PF(n){const e=[];for(const t of n){const r=xF[t.codePointAt(0)];if(void 0===r)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}});var kF=Math.pow(2,31),UF=Math.pow(2,7),VF=Math.pow(2,14),HF=Math.pow(2,21),KF=Math.pow(2,28),jF=Math.pow(2,35),$F=Math.pow(2,42),GF=Math.pow(2,49),zF=Math.pow(2,56),WF=Math.pow(2,63),QF={encode:function g2(n,e,t){e=e||[];for(var r=t=t||0;n>=kF;)e[t++]=255&n|128,n/=128;for(;-128&n;)e[t++]=255&n|128,n>>>=7;return e[t]=0|n,g2.bytes=t-r+1,e},decode:function Cm(n,r){var o,t=0,i=0,s=r=r||0,a=n.length;do{if(s>=a)throw Cm.bytes=0,new RangeError("Could not decode varint");o=n[s++],t+=i<28?(127&o)<=128);return Cm.bytes=s-r,t},encodingLength:function(n){return n[kh.decode(n),kh.decode.bytes],Bh=(n,e,t=0)=>(kh.encode(n,e,t),e),Fh=n=>kh.encodingLength(n),pu=(n,e)=>{const t=e.byteLength,r=Fh(n),i=r+Fh(t),s=new Uint8Array(i+t);return Bh(n,s,0),Bh(t,s,r),s.set(e,i),new Am(n,t,e,s)},Uh=n=>{const e=hu(n),[t,r]=Tm(e),[i,s]=Tm(e.subarray(r)),o=e.subarray(r+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Am(t,i,o,e)};class Am{constructor(e,t,r,i){this.code=e,this.size=t,this.digest=r,this.bytes=i}}const m2=({name:n,code:e,encode:t})=>new XF(n,e,t);class XF{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?pu(this.code,t):t.then(r=>pu(this.code,r))}throw Error("Unknown type, must be binary type")}}const v2=n=>function(){var e=V(function*(t){return new Uint8Array(yield crypto.subtle.digest(n,t))});return function(t){return e.apply(this,arguments)}}(),Li=m2({name:"sha2-256",code:18,encode:v2("SHA-256")}),JF=m2({name:"sha2-512",code:19,encode:v2("SHA-512")}),w2=hu,gu={code:0,name:"identity",encode:w2,digest:n=>pu(0,w2(n))},tU="raw",nU=85,rU=n=>hu(n),iU=n=>hu(n),sU=new TextEncoder,oU=new TextDecoder,aU="json",cU=512,uU=n=>sU.encode(JSON.stringify(n)),lU=n=>JSON.parse(oU.decode(n));class Rr{constructor(e,t,r,i){this.code=t,this.version=e,this.multihash=r,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Hh,byteLength:Hh,code:Vh,version:Vh,multihash:Vh,bytes:Vh,_baseCache:Hh,asCID:Hh})}toV0(){if(0===this.version)return this;{const{code:e,multihash:t}=this;if(e!==Xl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==pU)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Rr.createV0(t)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=pu(e,t);return Rr.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&((n,e)=>n===e||n.code===e.code&&n.size===e.size&&((n,e)=>{if(n===e)return!0;if(n.byteLength!==e.byteLength)return!1;for(let t=0;t{const[R,k]=Tm(e.subarray(t));return t+=k,R};let i=r(),s=Xl;if(18===i?(i=0,t=0):1===i&&(s=r()),0!==i&&1!==i)throw new RangeError(`Invalid CID version ${i}`);const o=t,a=r(),c=r(),m=t+c;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:m-o,size:m}}static parse(e,t){const[r,i]=fU(e,t),s=Rr.decode(i);return s._baseCache.set(r,e),s}}const fU=(n,e)=>{switch(n[0]){case"Q":return[Ci.prefix,(e||Ci).decode(`${Ci.prefix}${n}`)];case Ci.prefix:return[Ci.prefix,(e||Ci).decode(n)];case Ro.prefix:return[Ro.prefix,(e||Ro).decode(n)];default:if(null==e)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[n[0],e.decode(n)]}},dU=(n,e,t)=>{const{prefix:r}=t;if(r!==Ci.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);const i=e.get(r);if(null==i){const s=t.encode(n).slice(1);return e.set(r,s),s}return i},hU=(n,e,t)=>{const{prefix:r}=t,i=e.get(r);if(null==i){const s=t.encode(n);return e.set(r,s),s}return i},Xl=112,pU=18,b2=(n,e,t)=>{const r=Fh(n),i=r+Fh(e),s=new Uint8Array(i+t.byteLength);return Bh(n,s,0),Bh(e,s,r),s.set(t,i),s},_2=Symbol.for("@ipld/js-cid/CID"),Vh={writable:!1,configurable:!1,enumerable:!0},Hh={writable:!1,enumerable:!1,configurable:!1},yU=(n,e)=>{if(!n.test("0.0.0-dev"))throw new Error(e);console.warn(e)},mU="CID.isCID(v) is deprecated and will be removed in the next major release.\nFollowing code pattern:\n\nif (CID.isCID(value)) {\n doSomethingWithCID(value)\n}\n\nIs replaced with:\n\nconst cid = CID.asCID(value)\nif (cid) {\n // Make sure to use cid instead of value\n doSomethingWithCID(cid)\n}\n",Jl={...h,...u,...g,...b,...w,...v,...l,...p,...d,..._};function D2(n,e,t,r){return{name:n,prefix:e,encoder:{name:n,prefix:e,encode:t},decoder:{decode:r}}}const S2=D2("utf8","u",n=>"u"+new TextDecoder("utf8").decode(n),n=>(new TextEncoder).encode(n.substring(1))),xm=D2("ascii","a",n=>{let e="a";for(let t=0;t{const e=xo((n=n.substring(1)).length);for(let t=0;te)throw new Error("byte array longer than desired length");t=or([new Uint8Array(e-t.length),t])}return Mt(t,"base64url")}function Os(n){const e=function bU(n,e){let t=_t(n,"base64urlpad");if(null!=e){if(t.length>e)throw new Error("byte array longer than desired length");t=or([new Uint8Array(e-t.length),t])}return t}(n);return new Gn.jsbn.BigInteger(Mt(e,"base16"),16)}N(730);function R2(n){const e=n?.algorithm??"AES-GCM";let t=n?.keyLength??16;const r=n?.nonceLength??12,i=n?.digest??"SHA-256",s=n?.saltLength??16,o=n?.iterations??32767,a=no.get();function m(){return(m=V(function*(U,Q){const X=a.getRandomValues(new Uint8Array(s)),ae=a.getRandomValues(new Uint8Array(r)),he={name:e,iv:ae};"string"==typeof Q&&(Q=_t(Q));const Ae={name:"PBKDF2",salt:X,iterations:o,hash:{name:i}},ue=yield a.subtle.importKey("raw",Q,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),Re=yield a.subtle.deriveKey(Ae,ue,{name:e,length:t},!0,["encrypt"]),Le=yield a.subtle.encrypt(he,Re,U);return or([X,he.iv,new Uint8Array(Le)])})).apply(this,arguments)}function R(){return(R=V(function*(U,Q){const X=U.slice(0,s),ae=U.slice(s,s+r),he=U.slice(s+r),Ae={name:e,iv:ae};"string"==typeof Q&&(Q=_t(Q));const ue={name:"PBKDF2",salt:X,iterations:o,hash:{name:i}},Re=yield a.subtle.importKey("raw",Q,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]),Le=yield a.subtle.deriveKey(ue,Re,{name:e,length:t},!0,["decrypt"]),Fe=yield a.subtle.decrypt(Ae,Le,he);return new Uint8Array(Fe)})).apply(this,arguments)}return t*=8,{encrypt:function c(U,Q){return m.apply(this,arguments)},decrypt:function T(U,Q){return R.apply(this,arguments)}}}function SU(n,e){return Om.apply(this,arguments)}function Om(){return(Om=V(function*(n,e){const t=Lh.decode(n);return yield R2().decrypt(t,e)})).apply(this,arguments)}Object.keys({"P-256":256,"P-384":384,"P-521":521}).join(" / "),N(8985);var IU=N(5856),CU=N.t(IU,2);const gn=BigInt(0),Un=BigInt(1),br=BigInt(2),ef=BigInt(3),TU=BigInt(8),Lm=br**BigInt(256),Sn={a:gn,b:BigInt(7),P:Lm-br**BigInt(32)-BigInt(977),n:Lm-BigInt("432420386565659656852420866394968145599"),h:Un,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")};function P2(n){const{a:e,b:t}=Sn,r=it(n*n),i=it(r*n);return it(i+e*n+t)}const Kh=Sn.a===gn;class Bn{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof dn))throw new TypeError("JacobianPoint#fromAffine: expected Point");return new Bn(e.x,e.y,Un)}static toAffineBatch(e){const t=function PU(n,e=Sn.P){const t=new Array(n.length),i=Eu(n.reduce((s,o,a)=>o===gn?s:(t[a]=s,it(s*o,e)),Un),e);return n.reduceRight((s,o,a)=>o===gn?s:(t[a]=it(s*t[a],e),it(s*o,e)),i),t}(e.map(r=>r.z));return e.map((r,i)=>r.toAffine(t[i]))}static normalizeZ(e){return Bn.toAffineBatch(e).map(Bn.fromAffine)}equals(e){if(!(e instanceof Bn))throw new TypeError("JacobianPoint expected");const{x:t,y:r,z:i}=this,{x:s,y:o,z:a}=e,c=it(i**br),m=it(a**br),T=it(t*m),R=it(s*c),k=it(it(r*a)*m),U=it(it(o*i)*c);return T===R&&k===U}negate(){return new Bn(this.x,it(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,i=it(e**br),s=it(t**br),o=it(s**br),a=it(br*(it((e+s)**br)-i-o)),c=it(ef*i),m=it(c**br),T=it(m-br*a),R=it(c*(a-T)-TU*o),k=it(br*t*r);return new Bn(T,R,k)}add(e){if(!(e instanceof Bn))throw new TypeError("JacobianPoint expected");const{x:t,y:r,z:i}=this,{x:s,y:o,z:a}=e;if(s===gn||o===gn)return this;if(t===gn||r===gn)return e;const c=it(i**br),m=it(a**br),T=it(t*m),R=it(s*c),k=it(it(r*a)*m),U=it(it(o*i)*c),Q=it(R-T),X=it(U-k);if(Q===gn)return X===gn?this.double():Bn.ZERO;const ae=it(Q**br),he=it(Q*ae),Ae=it(T*ae),ue=it(X**br-he-br*Ae),Re=it(X*(Ae-ue)-k*he),Le=it(i*a*Q);return new Bn(ue,Re,Le)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=Bn.ZERO;if("bigint"==typeof e&&e===gn)return t;let r=O2(e);if(r===Un)return this;if(!Kh){let R=t,k=this;for(;r>gn;)r&Un&&(R=R.add(k)),k=k.double(),r>>=Un;return R}let{k1neg:i,k1:s,k2neg:o,k2:a}=k2(r),c=t,m=t,T=this;for(;s>gn||a>gn;)s&Un&&(c=c.add(T)),a&Un&&(m=m.add(T)),T=T.double(),s>>=Un,a>>=Un;return i&&(c=c.negate()),o&&(m=m.negate()),m=new Bn(it(m.x*Sn.beta),m.y,m.z),c.add(m)}precomputeWindow(e){const t=Kh?128/e+1:256/e+1,r=[];let i=this,s=i;for(let o=0;o>=R,Q>c&&(Q-=T,e+=Un),0===Q){let X=i[U];k%2&&(X=X.negate()),o=o.add(X)}else{let X=i[U+Math.abs(Q)-1];Q<0&&(X=X.negate()),s=s.add(X)}}return{p:s,f:o}}multiply(e,t){let i,s,r=O2(e);if(Kh){const{k1neg:o,k1:a,k2neg:c,k2:m}=k2(r);let{p:T,f:R}=this.wNAF(a,t),{p:k,f:U}=this.wNAF(m,t);o&&(T=T.negate()),c&&(k=k.negate()),k=new Bn(it(k.x*Sn.beta),k.y,k.z),i=T.add(k),s=R.add(U)}else{const{p:o,f:a}=this.wNAF(r,t);i=o,s=a}return Bn.normalizeZ([i,s])[0]}toAffine(e=Eu(this.z)){const{x:t,y:r,z:i}=this,s=e,o=it(s*s),a=it(o*s),c=it(t*o),m=it(r*a);if(it(i*s)!==Un)throw new Error("invZ was invalid");return new dn(c,m)}}Bn.BASE=new Bn(Sn.Gx,Sn.Gy,Un),Bn.ZERO=new Bn(gn,Un,gn);const km=new WeakMap;class dn{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,km.delete(this)}static fromCompressedHex(e){const t=32===e.length,r=Ti(t?e:e.subarray(1));if(!Gh(r))throw new Error("Point is not on curve");let s=function RU(n){const{P:e}=Sn,t=BigInt(6),r=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=n*n*n%e,m=c*c*n%e,T=fs(m,ef)*m%e,R=fs(T,ef)*m%e,k=fs(R,br)*c%e,U=fs(k,r)*k%e,Q=fs(U,i)*U%e,X=fs(Q,o)*Q%e,ae=fs(X,a)*X%e,he=fs(ae,o)*Q%e,Ae=fs(he,ef)*m%e,ue=fs(Ae,s)*U%e,Re=fs(ue,t)*c%e;return fs(Re,br)}(P2(r));const o=(s&Un)===Un;t?o&&(s=it(-s)):1==(1&e[0])!==o&&(s=it(-s));const a=new dn(r,s);return a.assertValidity(),a}static fromUncompressedHex(e){const t=Ti(e.subarray(1,33)),r=Ti(e.subarray(33,65)),i=new dn(t,r);return i.assertValidity(),i}static fromHex(e){const t=Ls(e),r=t.length,i=t[0];if(32===r||33===r&&(2===i||3===i))return this.fromCompressedHex(t);if(65===r&&4===i)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return dn.BASE.multiply(io(e))}static fromSignature(e,t,r){const i=B2(e=Ls(e)),{r:s,s:o}=V2(t);if(0!==r&&1!==r)throw new Error("Cannot recover signature: invalid recovery bit");const c=dn.fromHex((1&r?"03":"02")+No(s)),{n:m}=Sn,T=Eu(s,m),R=it(-i*T,m),k=it(o*T,m),U=dn.BASE.multiplyAndAddUnsafe(c,R,k);if(!U)throw new Error("Cannot recover signature: point at infinify");return U.assertValidity(),U}toRawBytes(e=!1){return Mo(this.toHex(e))}toHex(e=!1){const t=No(this.x);return e?`${this.y&Un?"03":"02"}${t}`:`04${t}${No(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!Gh(t)||!Gh(r))throw new Error(e);const i=it(r*r);if(it(i-P2(t))!==gn)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new dn(this.x,it(-this.y))}double(){return Bn.fromAffine(this).double().toAffine()}add(e){return Bn.fromAffine(this).add(Bn.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Bn.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const i=Bn.fromAffine(this),s=t===gn||t===Un||this!==dn.BASE?i.multiplyUnsafe(t):i.multiply(t),o=Bn.fromAffine(e).multiplyUnsafe(r),a=s.add(o);return a.equals(Bn.ZERO)?void 0:a.toAffine()}}function N2(n){return Number.parseInt(n[0],16)>=8?"00"+n:n}function M2(n){if(n.length<2||2!==n[0])throw new Error(`Invalid signature integer tag: ${mu(n)}`);const e=n[1],t=n.subarray(2,e+2);if(!e||t.length!==e)throw new Error("Invalid signature integer: wrong length");if(0===t[0]&&t[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Ti(t),left:n.subarray(e+2)}}dn.BASE=new dn(Sn.Gx,Sn.Gy),dn.ZERO=new dn(gn,gn);class Po{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=tf(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const i=t?mu(e):e;if(128!==i.length)throw new Error(`${r}: Expected 64-byte hex`);return new Po(jh(i.slice(0,64)),jh(i.slice(64,128)))}static fromDER(e){const t=tf(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r,s:i}=function AU(n){if(n.length<2||48!=n[0])throw new Error(`Invalid signature tag: ${mu(n)}`);if(n[1]!==n.length-2)throw new Error("Invalid signature: incorrect length");const{data:e,left:t}=M2(n.subarray(2)),{data:r,left:i}=M2(t);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${mu(i)}`);return{r:e,s:r}}(t?e:Mo(e));return new Po(r,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!wu(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!wu(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){return this.s>Sn.n>>Un}normalizeS(){return this.hasHighS()?new Po(this.r,Sn.n-this.s):this}toDERRawBytes(e=!1){return Mo(this.toDERHex(e))}toDERHex(e=!1){const t=N2(nf(this.s));if(e)return t;const r=N2(nf(this.r)),i=nf(r.length/2),s=nf(t.length/2);return`30${nf(r.length/2+t.length/2+4)}02${i}${r}02${s}${t}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Mo(this.toCompactHex())}toCompactHex(){return No(this.r)+No(this.s)}}function yu(...n){if(!n.every(tf))throw new Error("Uint8Array list expected");if(1===n.length)return n[0];const e=n.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e);for(let r=0,i=0;re.toString(16).padStart(2,"0"));function mu(n){if(!(n instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let t=0;tLm)throw new Error("Expected number < 2^256");return n.toString(16).padStart(64,"0")}function vu(n){return Mo(No(n))}function nf(n){const e=n.toString(16);return 1&e.length?`0${e}`:e}function jh(n){if("string"!=typeof n)throw new TypeError("hexToNumber: expected string, got "+typeof n);return BigInt(`0x${n}`)}function Mo(n){if("string"!=typeof n)throw new TypeError("hexToBytes: expected string, got "+typeof n);if(n.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+n.length);const e=new Uint8Array(n.length/2);for(let t=0;t0)return BigInt(n);if("bigint"==typeof n&&wu(n))return n;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function it(n,e=Sn.P){const t=n%e;return t>=gn?t:e+t}function fs(n,e){const{P:t}=Sn;let r=n;for(;e-- >gn;)r*=r,r%=t;return r}function Eu(n,e=Sn.P){if(n===gn||e<=gn)throw new Error(`invert: expected positive integers, got n=${n} mod=${e}`);let t=it(n,e),r=e,i=gn,s=Un,o=Un,a=gn;for(;t!==gn;){const m=r/t,T=r%t,R=i-o*m,k=s-a*m;r=t,t=T,i=o,s=a,o=R,a=k}if(r!==Un)throw new Error("invert: does not exist");return it(i,e)}const L2=(n,e)=>(n+e/br)/e,$h=br**BigInt(128);function k2(n){const{n:e}=Sn,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Un*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,o=L2(s*n,e),a=L2(-r*n,e);let c=it(n-o*t-a*i,e),m=it(-o*r-a*s,e);const T=c>$h,R=m>$h;if(T&&(c=e-c),R&&(m=e-m),c>$h||m>$h)throw new Error("splitScalarEndo: Endomorphism failed, k="+n);return{k1neg:T,k1:c,k2neg:R,k2:m}}function B2(n){const{n:e}=Sn,r=8*n.length-256;let i=Ti(n);return r>0&&(i>>=BigInt(r)),i>=e&&(i-=e),i}class F2{constructor(){this.v=new Uint8Array(32).fill(1),this.k=new Uint8Array(32).fill(0),this.counter=0}hmac(...e){return er.hmacSha256(this.k,...e)}hmacSync(...e){if("function"!=typeof er.hmacSha256Sync)throw new Error("utils.hmacSha256Sync is undefined, you need to set it");const t=er.hmacSha256Sync(this.k,...e);if(t instanceof Promise)throw new Error("To use sync sign(), ensure utils.hmacSha256 is sync");return t}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}reseed(e=new Uint8Array){var t=this;return V(function*(){t.k=yield t.hmac(t.v,Uint8Array.from([0]),e),t.v=yield t.hmac(t.v),0!==e.length&&(t.k=yield t.hmac(t.v,Uint8Array.from([1]),e),t.v=yield t.hmac(t.v))})()}reseedSync(e=new Uint8Array){this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}generate(){var e=this;return V(function*(){return e.incr(),e.v=yield e.hmac(e.v),e.v})()}generateSync(){return this.incr(),this.v=this.hmacSync(this.v),this.v}}function wu(n){return gn0)e=BigInt(n);else if("string"==typeof n){if(64!==n.length)throw new Error("Expected 32 bytes of private key");e=jh(n)}else{if(!tf(n))throw new TypeError("Expected valid private key");if(32!==n.length)throw new Error("Expected 32 bytes of private key");e=Ti(n)}if(!wu(e))throw new Error("Expected private key: 0 < key < n");return e}function Bm(n){return n instanceof dn?(n.assertValidity(),n):dn.fromHex(n)}function V2(n){if(n instanceof Po)return n.assertValidity(),n;try{return Po.fromDER(n)}catch{return Po.fromCompact(n)}}function rf(n,e=!1){return dn.fromPrivateKey(n).toRawBytes(e)}function H2(n){const e=tf(n),t="string"==typeof n,r=(e||t)&&n.length;return e?33===r||65===r:t?66===r||130===r:n instanceof dn}function K2(n){return Ti(n.length>32?n.slice(0,32):n)}function OU(n){const e=K2(n),t=it(e,Sn.n);return j2(tvu(it(io(n)+io(e),Sn.n)),privateNegate:n=>{const e=io(n);return vu(Sn.n-e)},pointAddScalar:(n,e,t)=>{const r=dn.fromHex(n),i=io(e),s=dn.BASE.multiplyAndAddUnsafe(r,i,Un);if(!s)throw new Error("Tweaked point at infinity");return s.toRawBytes(t)},pointMultiply:(n,e,t)=>{const r=dn.fromHex(n),i=Ti(Ls(e));return r.multiply(i).toRawBytes(t)},hashToPrivateKey:n=>{if((n=Ls(n)).length<40||n.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return vu(it(Ti(n),Sn.n-Un)+Un)},randomBytes:(n=32)=>{if(Qi.web)return Qi.web.getRandomValues(new Uint8Array(n));if(Qi.node){const{randomBytes:e}=Qi.node;return Uint8Array.from(e(n))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>er.hashToPrivateKey(er.randomBytes(40)),bytesToHex:mu,hexToBytes:Mo,concatBytes:yu,mod:it,invert:Eu,sha256:(n=V(function*(...e){if(Qi.web){const t=yield Qi.web.subtle.digest("SHA-256",yu(...e));return new Uint8Array(t)}if(Qi.node){const{createHash:t}=Qi.node,r=t("sha256");return e.forEach(i=>r.update(i)),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have sha256 function")}),function(){return n.apply(this,arguments)}),hmacSha256:function(){var n=V(function*(e,...t){if(Qi.web){const r=yield Qi.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),i=yu(...t),s=yield Qi.web.subtle.sign("HMAC",r,i);return new Uint8Array(s)}if(Qi.node){const{createHmac:r}=Qi.node,i=r("sha256",e);return t.forEach(s=>i.update(s)),Uint8Array.from(i.digest())}throw new Error("The environment doesn't have hmac-sha256 function")});return function(t){return n.apply(this,arguments)}}(),sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:function(){var n=V(function*(e,...t){let r=Wh[e];if(void 0===r){const i=yield er.sha256(Uint8Array.from(e,s=>s.charCodeAt(0)));r=yu(i,i),Wh[e]=r}return er.sha256(r,...t)});return function(t){return n.apply(this,arguments)}}(),taggedHashSync:(n,...e)=>{if("function"!=typeof er.sha256Sync)throw new Error("utils.sha256Sync is undefined, you need to set it");let t=Wh[n];if(void 0===t){const r=er.sha256Sync(Uint8Array.from(n,i=>i.charCodeAt(0)));t=yu(r,r),Wh[n]=t}return er.sha256Sync(t,...e)},precompute(n=8,e=dn.BASE){const t=e===dn.BASE?e:new dn(e.x,e.y);return t._setWindowSize(n),t.multiply(ef),t}};var n;function sf(n){if(isNaN(n)||n<=0)throw se(new Error("random bytes length must be a Number bigger than 0"),"ERR_INVALID_LENGTH");return er.randomBytes(n)}function VU(n){const e=Gn.asn1.fromDer(Mt(n,"ascii")),t=Gn.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:ro(t.n),e:ro(t.e),d:ro(t.d),p:ro(t.p),q:ro(t.q),dp:ro(t.dP),dq:ro(t.dQ),qi:ro(t.qInv),alg:"RS256"}}function tT(n,e){return e.map(t=>Os(n[t]))}function zU(n){return Km.apply(this,arguments)}function Km(){return Km=V(function*(n){const e=yield no.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:n,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=yield rT(e);return{privateKey:t[0],publicKey:t[1]}}),Km.apply(this,arguments)}function nT(n){return jm.apply(this,arguments)}function jm(){return jm=V(function*(n){const t=[yield no.get().subtle.importKey("jwk",n,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),yield QU(n)],r=yield rT({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}),jm.apply(this,arguments)}function $m(){return $m=V(function*(n,e){const t=yield no.get().subtle.importKey("jwk",n,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),r=yield no.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,Uint8Array.from(e));return new Uint8Array(r,0,r.byteLength)}),$m.apply(this,arguments)}function Gm(){return Gm=V(function*(n,e,t){const r=yield no.get().subtle.importKey("jwk",n,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return yield no.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},r,e,t)}),Gm.apply(this,arguments)}function rT(n){return zm.apply(this,arguments)}function zm(){return zm=V(function*(n){if(null==n.privateKey||null==n.publicKey)throw se(new Error("Private and public key are required"),"ERR_INVALID_PARAMETERS");return yield Promise.all([no.get().subtle.exportKey("jwk",n.privateKey),no.get().subtle.exportKey("jwk",n.publicKey)])}),zm.apply(this,arguments)}function QU(n){return Wm.apply(this,arguments)}function Wm(){return Wm=V(function*(n){return yield no.get().subtle.importKey("jwk",{kty:n.kty,n:n.n,e:n.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}),Wm.apply(this,arguments)}function iT(n,e,t,r){const i=e?function GU(n){return Gn.pki.setRsaPublicKey(...tT(n,["n","e"]))}(n):function $U(n){return Gn.pki.setRsaPrivateKey(...tT(n,["n","e","d","p","q","dp","dq","qi"]))}(n);return _t(r(Mt(Uint8Array.from(t),"ascii"),i),"ascii")}function qm(n,e){return Qm.apply(this,arguments)}function Qm(){return Qm=V(function*(n,e){const r=yield R2().encrypt(n,e);return Lh.encode(r)}),Qm.apply(this,arguments)}N(5517);class Ym{constructor(e){this._key=e}verify(e,t){var r=this;return V(function*(){return yield function qU(n,e,t){return Gm.apply(this,arguments)}(r._key,t,e)})()}marshal(){return function jU(n){if(null==n.n||null==n.e)throw se(new Error("JWK was missing components"),"ERR_INVALID_PARAMETERS");const e=Gn.pki.publicKeyToAsn1({n:Os(n.n),e:Os(n.e)});return _t(Gn.asn1.toDer(e).getBytes(),"ascii")}(this._key)}get bytes(){return fu.encode({Type:dr.RSA,Data:this.marshal()}).subarray()}encrypt(e){return function YU(n,e){return iT(n,!0,e,(t,r)=>r.encrypt(t))}(this._key,e)}equals(e){return $r(this.bytes,e.bytes)}hash(){var e=this;return V(function*(){const{bytes:t}=yield Li.digest(e.bytes);return t})()}}class qh{constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return sf(16)}sign(e){var t=this;return V(function*(){return yield function WU(n,e){return $m.apply(this,arguments)}(t._key,e)})()}get public(){if(null==this._publicKey)throw se(new Error("public key not provided"),"ERR_PUBKEY_NOT_PROVIDED");return new Ym(this._publicKey)}decrypt(e){return function ZU(n,e){return iT(n,!1,e,(t,r)=>r.decrypt(t))}(this._key,e)}marshal(){return function HU(n){if(null==n.n||null==n.e||null==n.d||null==n.p||null==n.q||null==n.dp||null==n.dq||null==n.qi)throw se(new Error("JWK was missing components"),"ERR_INVALID_PARAMETERS");const e=Gn.pki.privateKeyToAsn1({n:Os(n.n),e:Os(n.e),d:Os(n.d),p:Os(n.p),q:Os(n.q),dP:Os(n.dp),dQ:Os(n.dq),qInv:Os(n.qi)});return _t(Gn.asn1.toDer(e).getBytes(),"ascii")}(this._key)}get bytes(){return du.encode({Type:dr.RSA,Data:this.marshal()}).subarray()}equals(e){return $r(this.bytes,e.bytes)}hash(){var e=this;return V(function*(){const{bytes:t}=yield Li.digest(e.bytes);return t})()}id(){var e=this;return V(function*(){return Mt(yield e.public.hash(),"base58btc")})()}export(e,t="pkcs-8"){var r=this;return V(function*(){if("pkcs-8"===t){const i=new Gn.util.ByteBuffer(r.marshal()),s=Gn.asn1.fromDer(i),o=Gn.pki.privateKeyFromAsn1(s);return Gn.pki.encryptRsaPrivateKey(o,e,{algorithm:"aes256",count:1e4,saltSize:16,prfAlgorithm:"sha512"})}if("libp2p-key"===t)return yield qm(r.bytes,e);throw se(new Error(`export format '${t}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")})()}}function XU(n){return Zm.apply(this,arguments)}function Zm(){return Zm=V(function*(n){const e=VU(n),t=yield nT(e);return new qh(t.privateKey,t.publicKey)}),Zm.apply(this,arguments)}function JU(n){const e=function KU(n){const e=Gn.asn1.fromDer(Mt(n,"ascii")),t=Gn.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:ro(t.n),e:ro(t.e)}}(n);return new Ym(e)}function eV(n){return Xm.apply(this,arguments)}function Xm(){return Xm=V(function*(n){const e=yield nT(n);return new qh(e.privateKey,e.publicKey)}),Xm.apply(this,arguments)}function tV(n){return Jm.apply(this,arguments)}function Jm(){return Jm=V(function*(n){const e=yield zU(n);return new qh(e.privateKey,e.publicKey)}),Jm.apply(this,arguments)}var nV=N(7420),rV=N.t(nV,2);const mr=BigInt(0),nn=BigInt(1),Yr=BigInt(2),sT=BigInt(255),oT=Yr**BigInt(252)+BigInt("27742317777372353535851937790883648493"),zn=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:Yr**sT-BigInt(19),l:oT,n:oT,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")}),aT=Yr**BigInt(256),of=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),iV=(BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235")),sV=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),oV=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),aV=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");class In{constructor(e,t,r,i){this.x=e,this.y=t,this.z=r,this.t=i}static fromAffine(e){if(!(e instanceof hr))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(hr.ZERO)?In.ZERO:new In(e.x,e.y,nn,Me(e.x*e.y))}static toAffineBatch(e){const t=function uV(n,e=zn.P){const t=new Array(n.length),i=Qh(n.reduce((s,o,a)=>o===mr?s:(t[a]=s,Me(s*o,e)),nn),e);return n.reduceRight((s,o,a)=>o===mr?s:(t[a]=Me(s*t[a],e),Me(s*o,e)),i),t}(e.map(r=>r.z));return e.map((r,i)=>r.toAffine(t[i]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){cT(e);const{x:t,y:r,z:i}=this,{x:s,y:o,z:a}=e,c=Me(t*a),m=Me(s*i),T=Me(r*a),R=Me(o*i);return c===m&&T===R}negate(){return new In(Me(-this.x),this.y,this.z,Me(-this.t))}double(){const{x:e,y:t,z:r}=this,{a:i}=zn,s=Me(e**Yr),o=Me(t**Yr),a=Me(Yr*Me(r**Yr)),c=Me(i*s),m=Me(Me((e+t)**Yr)-s-o),T=c+o,R=T-a,k=c-o,U=Me(m*R),Q=Me(T*k),X=Me(m*k),ae=Me(R*T);return new In(U,Q,ae,X)}add(e){cT(e);const{x:t,y:r,z:i,t:s}=this,{x:o,y:a,z:c,t:m}=e,T=Me((r-t)*(a+o)),R=Me((r+t)*(a-o)),k=Me(R-T);if(k===mr)return this.double();const U=Me(i*Yr*m),Q=Me(s*Yr*c),X=Q+U,ae=R+T,he=Q-U,Ae=Me(X*k),ue=Me(ae*he),Re=Me(X*he),Le=Me(k*ae);return new In(Ae,ue,Le,Re)}subtract(e){return this.add(e.negate())}precomputeWindow(e){const t=1+256/e,r=[];let i=this,s=i;for(let o=0;o>=R,Q>c&&(Q-=T,e+=nn),0===Q){let X=i[U];k%2&&(X=X.negate()),o=o.add(X)}else{let X=i[U+Math.abs(Q)-1];Q<0&&(X=X.negate()),s=s.add(X)}}return In.normalizeZ([s,o])[0]}multiply(e,t){return this.wNAF(Iu(e,zn.l),t)}multiplyUnsafe(e){let t=Iu(e,zn.l,!1);const r=In.BASE,i=In.ZERO;if(t===mr)return i;if(this.equals(i)||t===nn)return this;if(this.equals(r))return this.wNAF(t);let s=i,o=this;for(;t>mr;)t&nn&&(s=s.add(o)),o=o.double(),t>>=nn;return s}isSmallOrder(){return this.multiplyUnsafe(zn.h).equals(In.ZERO)}isTorsionFree(){return this.multiplyUnsafe(zn.l).equals(In.ZERO)}toAffine(e=Qh(this.z)){const{x:t,y:r,z:i}=this,s=Me(t*e),o=Me(r*e);if(Me(i*e)!==nn)throw new Error("invZ was invalid");return new hr(s,o)}fromRistrettoBytes(){tv()}toRistrettoBytes(){tv()}fromRistrettoHash(){tv()}}function cT(n){if(!(n instanceof In))throw new TypeError("ExtendedPoint expected")}function ev(n){if(!(n instanceof ds))throw new TypeError("RistrettoPoint expected")}function tv(){throw new Error("Legacy method: switch to RistrettoPoint")}In.BASE=new In(zn.Gx,zn.Gy,nn,Me(zn.Gx*zn.Gy)),In.ZERO=new In(mr,nn,nn,mr);class ds{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){const{d:t}=zn,r=Me(of*e*e),i=Me((r+nn)*oV);let s=BigInt(-1);const o=Me((s-t*r)*Me(r+t));let{isValid:a,value:c}=sv(i,o),m=Me(c*e);fa(m)||(m=Me(-m)),a||(c=m),a||(s=r);const T=Me(s*(r-nn)*aV-o),R=c*c,k=Me((c+c)*o),U=Me(T*iV),Q=Me(nn-R),X=Me(nn+R);return new In(Me(k*X),Me(Q*U),Me(U*X),Me(k*Q))}static hashToCurve(e){const t=iv((e=Bs(e,64)).slice(0,32)),r=this.calcElligatorRistrettoMap(t),i=iv(e.slice(32,64)),s=this.calcElligatorRistrettoMap(i);return new ds(r.add(s))}static fromHex(e){e=Bs(e,32);const{a:t,d:r}=zn,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=iv(e);if(!function lV(n,e){if(n.length!==e.length)return!1;for(let t=0;t=i)throw new Error("Expected 0 < hex < P");if(!t&&o>=aT)throw new Error("Expected 0 < hex < 2**256");const a=Me(o*o),c=Me(a-nn),m=Me(r*a+nn);let{isValid:T,value:R}=sv(c,m);if(!T)throw new Error("Point.fromHex: invalid y coordinate");return 0!=(128&e[31])!=((R&nn)===nn)&&(R=Me(-R)),new hr(R,o)}static fromPrivateKey(e){return V(function*(){return(yield uf(e)).point})()}toRawBytes(){const e=Du(this.y);return e[31]|=this.x&nn?128:0,e}toHex(){return af(this.toRawBytes())}toX25519(){const{y:e}=this;return Du(Me((nn+e)*Qh(nn-e)))}isTorsionFree(){return In.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new hr(Me(-this.x),this.y)}add(e){return In.fromAffine(this).add(In.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return In.fromAffine(this).multiply(e,this).toAffine()}}hr.BASE=new hr(zn.Gx,zn.Gy),hr.ZERO=new hr(mr,nn);class _u{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){const t=Bs(e,64),r=hr.fromHex(t.slice(0,32),!1),i=Qa(t.slice(32,64));return new _u(r,i)}assertValidity(){const{r:e,s:t}=this;if(!(e instanceof hr))throw new Error("Expected Point instance");return Iu(t,zn.l,!1),this}toRawBytes(){const e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Du(this.s),32),e}toHex(){return af(this.toRawBytes())}}function uT(...n){if(!n.every(r=>r instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(1===n.length)return n[0];const e=n.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e);for(let r=0,i=0;re.toString(16).padStart(2,"0"));function af(n){if(!(n instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let t=0;t=mr?t:e+t}function Qh(n,e=zn.P){if(n===mr||e<=mr)throw new Error(`invert: expected positive integers, got n=${n} mod=${e}`);let t=Me(n,e),r=e,i=mr,s=nn,o=nn,a=mr;for(;t!==mr;){const m=r/t,T=r%t,R=i-o*m,k=s-a*m;r=t,t=T,i=o,s=a,o=R,a=k}if(r!==nn)throw new Error("invert: does not exist");return Me(i,e)}function ks(n,e){const{P:t}=zn;let r=n;for(;e-- >mr;)r*=r,r%=t;return r}function sv(n,e){const t=Me(e*e*e),r=Me(t*t*e);let s=Me(n*t*function fT(n){const{P:e}=zn,t=BigInt(5),r=BigInt(10),i=BigInt(20),s=BigInt(40),o=BigInt(80),c=n*n%e*n%e,m=ks(c,Yr)*c%e,T=ks(m,nn)*n%e,R=ks(T,t)*T%e,k=ks(R,r)*R%e,U=ks(k,i)*k%e,Q=ks(U,s)*U%e,X=ks(Q,o)*Q%e,ae=ks(X,o)*Q%e,he=ks(ae,r)*R%e;return{pow_p_5_8:ks(he,Yr)*n%e,b2:c}}(n*r).pow_p_5_8);const o=Me(e*s*s),a=s,c=Me(s*of),m=o===n,T=o===Me(-n),R=o===Me(-n*of);return m&&(s=a),(T||R)&&(s=c),fa(s)&&(s=Me(-s)),{isValid:m||T,value:s}}function dT(n){return sv(nn,n)}function Su(n){return Me(Qa(n),zn.l)}function Bs(n,e){const t=n instanceof Uint8Array?Uint8Array.from(n):rv(n);if("number"==typeof e&&t.length!==e)throw new Error(`Expected ${e} bytes`);return t}function Iu(n,e,t=!0){if(!e)throw new TypeError("Specify max value");if("number"==typeof n&&Number.isSafeInteger(n)&&(n=BigInt(n)),"bigint"==typeof n&&n{if((n=Bs(n)).length<40||n.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return Me(Qa(n),zn.l-nn)+nn},randomBytes:(n=32)=>{if(da.web)return da.web.getRandomValues(new Uint8Array(n));if(da.node){const{randomBytes:e}=da.node;return new Uint8Array(e(n).buffer)}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Ya.randomBytes(32),sha512:function(){var n=V(function*(...e){const t=uT(...e);if(da.web){const r=yield da.web.subtle.digest("SHA-512",t.buffer);return new Uint8Array(r)}if(da.node)return Uint8Array.from(da.node.createHash("sha512").update(t).digest());throw new Error("The environment doesn't have sha512 function")});return function(){return n.apply(this,arguments)}}(),precompute(n=8,e=hr.BASE){const t=e.equals(hr.BASE)?e:new hr(e.x,e.y);return t._setWindowSize(n),t.multiply(Yr),t},sha512Sync:void 0};function wV(){return hv.apply(this,arguments)}function hv(){return hv=V(function*(){const n=Ya.randomPrivateKey(),e=yield yT(n);return{privateKey:ET(n,e),publicKey:e}}),hv.apply(this,arguments)}function bV(n){return pv.apply(this,arguments)}function pv(){return pv=V(function*(n){if(32!==n.length)throw new TypeError('"seed" must be 32 bytes in length.');if(!(n instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const e=n,t=yield yT(e);return{privateKey:ET(e,t),publicKey:t}}),pv.apply(this,arguments)}function gv(){return gv=V(function*(n,e){const t=n.slice(0,32);return yield hV(e,t)}),gv.apply(this,arguments)}function yv(){return yv=V(function*(n,e,t){return yield gV(e,t,n)}),yv.apply(this,arguments)}function ET(n,e){const t=new Uint8Array(64);for(let r=0;r<32;r++)t[r]=n[r],t[32+r]=e[r];return t}Object.defineProperties(Ya,{sha512Sync:{configurable:!1,get:()=>cf,set(n){cf||(cf=n)}}});class mv{constructor(e){this._key=Cu(e,32)}verify(e,t){var r=this;return V(function*(){return yield function DV(n,e,t){return yv.apply(this,arguments)}(r._key,t,e)})()}marshal(){return this._key}get bytes(){return fu.encode({Type:dr.Ed25519,Data:this.marshal()}).subarray()}equals(e){return $r(this.bytes,e.bytes)}hash(){var e=this;return V(function*(){const{bytes:t}=yield Li.digest(e.bytes);return t})()}}class ff{constructor(e,t){this._key=Cu(e,64),this._publicKey=Cu(t,32)}sign(e){var t=this;return V(function*(){return yield function _V(n,e){return gv.apply(this,arguments)}(t._key,e)})()}get public(){return new mv(this._publicKey)}marshal(){return this._key}get bytes(){return du.encode({Type:dr.Ed25519,Data:this.marshal()}).subarray()}equals(e){return $r(this.bytes,e.bytes)}hash(){var e=this;return V(function*(){const{bytes:t}=yield Li.digest(e.bytes);return t})()}id(){var e=this;return V(function*(){const t=yield gu.digest(e.public.bytes);return Ci.encode(t.bytes).substring(1)})()}export(e,t="libp2p-key"){var r=this;return V(function*(){if("libp2p-key"===t)return yield qm(r.bytes,e);throw se(new Error(`export format '${t}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")})()}}function SV(n){if(n.length>64){const r=(n=Cu(n,96)).slice(0,64),i=n.slice(64,n.length);return new ff(r,i)}const e=(n=Cu(n,64)).slice(0,64),t=n.slice(32);return new ff(e,t)}function IV(n){return n=Cu(n,32),new mv(n)}function CV(){return vv.apply(this,arguments)}function vv(){return vv=V(function*(){const{privateKey:n,publicKey:e}=yield wV();return new ff(n,e)}),vv.apply(this,arguments)}function TV(n){return Ev.apply(this,arguments)}function Ev(){return Ev=V(function*(n){const{privateKey:e,publicKey:t}=yield bV(n);return new ff(e,t)}),Ev.apply(this,arguments)}function Cu(n,e){if((n=Uint8Array.from(n??[])).length!==e)throw se(new Error(`Key must be a Uint8Array of length ${e}, got ${n.length}`),"ERR_INVALID_KEY_TYPE");return n}function AV(){return er.randomPrivateKey()}function wv(){return wv=V(function*(n,e){const{digest:t}=yield Li.digest(e);try{return yield z2(t,n)}catch(r){throw se(r,"ERR_INVALID_INPUT")}}),wv.apply(this,arguments)}function bv(){return bv=V(function*(n,e,t){try{const{digest:r}=yield Li.digest(t);return kU(e,r,n)}catch(r){throw se(r,"ERR_INVALID_INPUT")}}),bv.apply(this,arguments)}function wT(n){try{dn.fromHex(n)}catch(e){throw se(e,"ERR_INVALID_PUBLIC_KEY")}}class _v{constructor(e){wT(e),this._key=e}verify(e,t){var r=this;return V(function*(){return yield function RV(n,e,t){return bv.apply(this,arguments)}(r._key,t,e)})()}marshal(){return function PV(n){return dn.fromHex(n).toRawBytes(!0)}(this._key)}get bytes(){return fu.encode({Type:dr.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return $r(this.bytes,e.bytes)}hash(){var e=this;return V(function*(){const{bytes:t}=yield Li.digest(e.bytes);return t})()}}class Dv{constructor(e,t){this._key=e,this._publicKey=t??function MV(n){try{return rf(n,!0)}catch(e){throw se(e,"ERR_INVALID_PRIVATE_KEY")}}(e),function NV(n){try{rf(n,!0)}catch(e){throw se(e,"ERR_INVALID_PRIVATE_KEY")}}(this._key),wT(this._publicKey)}sign(e){var t=this;return V(function*(){return yield function xV(n,e){return wv.apply(this,arguments)}(t._key,e)})()}get public(){return new _v(this._publicKey)}marshal(){return this._key}get bytes(){return du.encode({Type:dr.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return $r(this.bytes,e.bytes)}hash(){var e=this;return V(function*(){const{bytes:t}=yield Li.digest(e.bytes);return t})()}id(){var e=this;return V(function*(){return Mt(yield e.public.hash(),"base58btc")})()}export(e,t="libp2p-key"){var r=this;return V(function*(){if("libp2p-key"===t)return yield qm(r.bytes,e);throw se(new Error(`export format '${t}' is not supported`),"ERR_INVALID_EXPORT_FORMAT")})()}}function OV(n){return new Dv(n)}function LV(n){return new _v(n)}function kV(){return Sv.apply(this,arguments)}function Sv(){return Sv=V(function*(){const n=yield AV();return new Dv(n)}),Sv.apply(this,arguments)}const Oo={rsa:C,ed25519:A,secp256k1:P};function Iv(n){const e=Object.keys(Oo).join(" / ");return se(new Error(`invalid or unsupported key type ${n}. Must be ${e}`),"ERR_UNSUPPORTED_KEY_TYPE")}function Cv(n){if("rsa"===(n=n.toLowerCase())||"ed25519"===n||"secp256k1"===n)return Oo[n];throw Iv(n)}function bT(n,e){return Tv.apply(this,arguments)}function Tv(){return Tv=V(function*(n,e){return yield Cv(n).generateKeyPair(e??2048)}),Tv.apply(this,arguments)}function Tu(n){const e=fu.decode(n),t=e.Data;switch(e.Type){case dr.RSA:return Oo.rsa.unmarshalRsaPublicKey(t);case dr.Ed25519:return Oo.ed25519.unmarshalEd25519PublicKey(t);case dr.Secp256k1:return Oo.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Iv(e.Type)}}function BV(n,e){return Cv(e=(e??"rsa").toLowerCase()),n.bytes}function Au(n){return xv.apply(this,arguments)}function xv(){return xv=V(function*(n){const e=du.decode(n),t=e.Data;switch(e.Type){case dr.RSA:return yield Oo.rsa.unmarshalRsaPrivateKey(t);case dr.Ed25519:return Oo.ed25519.unmarshalEd25519PrivateKey(t);case dr.Secp256k1:return Oo.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Iv(e.Type)}}),xv.apply(this,arguments)}function FV(n,e){return Cv(e=(e??"rsa").toLowerCase()),n.bytes}function Rv(n,e){return Pv.apply(this,arguments)}function Pv(){return Pv=V(function*(n,e){try{const i=yield SU(n,e);return yield Au(i)}catch{}const t=Gn.pki.decryptRsaPrivateKey(n,e);if(null===t)throw se(new Error("Cannot read the key, most likely the password is wrong or not a RSA key"),"ERR_CANNOT_DECRYPT_PEM");let r=Gn.asn1.toDer(Gn.pki.privateKeyToAsn1(t));return r=_t(r.getBytes(),"ascii"),yield Oo.rsa.unmarshalRsaPrivateKey(r)}),Pv.apply(this,arguments)}const _T=Symbol.for("@libp2p/peer-id");function DT(n){return null!=n&&Boolean(n[_T])}const ST=Object.values(Jl).map(n=>n.decoder).reduce((n,e)=>n.or(e),Jl.identity.decoder);class Jh{constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}get[_T](){return!0}toString(){return null==this.string&&(this.string=Ci.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Rr.createV1(114,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return $r(this.multihash.bytes,e);if("string"==typeof e)return _r(e).equals(this);if(null!=e?.multihash?.bytes)return $r(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}}class df extends Jh{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}}class hf extends Jh{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}}class pf extends Jh{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}}function Zr(n){if("RSA"===n.type)return new df(n);if("Ed25519"===n.type)return new hf(n);if("secp256k1"===n.type)return new pf(n);throw se(new Error("Not a PeerId"),"ERR_INVALID_PARAMETERS")}function _r(n,e){if(e=e??ST,"1"===n.charAt(0)||"Q"===n.charAt(0)){const t=Uh(Ci.decode(`z${n}`));return n.startsWith("12D")?new hf({multihash:t}):n.startsWith("16U")?new pf({multihash:t}):new df({multihash:t})}return pa(ST.decode(n))}function pa(n){try{const e=Uh(n);if(e.code===gu.code){if(36===e.digest.length)return new hf({multihash:e});if(37===e.digest.length)return new pf({multihash:e})}if(e.code===Li.code)return new df({multihash:e})}catch{return function UV(n){if(null==n||null==n.multihash||null==n.version||1===n.version&&114!==n.code)throw new Error("Supplied PeerID CID is invalid");const e=n.multihash;if(e.code===Li.code)return new df({multihash:n.multihash});if(e.code===gu.code){if(36===e.digest.length)return new hf({multihash:n.multihash});if(37===e.digest.length)return new pf({multihash:n.multihash})}throw new Error("Supplied PeerID CID is invalid")}(Rr.decode(n))}throw new Error("Supplied PeerID CID is invalid")}function xu(n,e){return Ov.apply(this,arguments)}function Ov(){return Ov=V(function*(n,e){return 36===n.length?new hf({multihash:pu(gu.code,n),privateKey:e}):37===n.length?new pf({multihash:pu(gu.code,n),privateKey:e}):new df({multihash:yield Li.digest(n),publicKey:n,privateKey:e})}),Ov.apply(this,arguments)}function CT(n){return null!=globalThis?.Buffer?.allocUnsafe?globalThis.Buffer.allocUnsafe(n):new Uint8Array(n)}var tr=(()=>(function(n){n[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32"}(tr||(tr={})),tr))();function di(n,e,t,r,i){return{name:n,type:e,encode:t,decode:r,encodingLength:i}}di("bool",tr.VARINT,function(e){return Uint8Array.from([e?1:0])},function(e,t){return e.get(t)>0},function(){return 1});const Lv=di("bytes",tr.LENGTH_DELIMITED,function(e){return new $n(Qt.encode(e.byteLength),e)},function(e,t){const r=Qt.decode(e,t);return t+=Qt.encodingLength(r),e.subarray(t,t+r)},function(e){const t=e.byteLength;return Qt.encodingLength(t)+t});di("double",tr.BIT64,function(e){const t=new $n(new Uint8Array(8));return t.setFloat64(0,e,!0),t},function(e,t){return e.getFloat64(t,!0)},function(){return 8});const xT=(di("fixed32",tr.BIT32,function(e){const t=new $n(new Uint8Array(4));return t.setInt32(0,e,!0),t},function(e,t){return e.getInt32(t,!0)},function(){return 4}),function(e){return 8}),RT=(di("fixed64",tr.BIT64,function(e){const t=new $n(new Uint8Array(8));return t.setBigInt64(0,e,!0),t},function(e,t){return e.getBigInt64(t,!0)},xT),function(){return 4}),PT=(di("float",tr.BIT32,function(e){const t=new $n(new Uint8Array(4));return t.setFloat32(0,e,!0),t},function(e,t){return e.getFloat32(t,!0)},RT),function(e){return e<0?10:Th.encodingLength(e)}),NT=(di("int32",tr.VARINT,function(e){const t=new Uint8Array(PT(e));return Th.encode(e,t)},function(e,t){return 0|Th.decode(e,t)},PT),0x7fn),Za={encodingLength(n){let e=0;for(;n>=0x80n;e++)n>>=7n;return e+1},encode(n,e,t=0){null==e&&(e=xo(Za.encodingLength(n)));const r=gm(e);for(;NT>=7n;return r.set(t,Number(n)),e},decode:(n,e=0)=>qr.fromBytes(n,e).toBigInt(!0)},ep={encodingLength:n=>n<0n?10:Za.encodingLength(n),encode:(n,e,t)=>(null==e&&(e=xo(ep.encodingLength(n))),n<0n?(qr.fromBigInt(n).toBytes(e,t),e):Za.encode(n,e,t)),decode:(n,e=0)=>qr.fromBytes(n,e).toBigInt(!1)},tp={encodingLength:n=>Za.encodingLength(n>=0?2n*n:-2n*n-1n),encode:(n,e,t)=>(null==e&&(e=xo(tp.encodingLength(n))),qr.fromBigInt(n).zzEncode().toBytes(e,t),e),decode:(n,e=0)=>qr.fromBytes(n,e).zzDecode().toBigInt(!1)},MT=function(e){return e<0n?10:ep.encodingLength(e)};di("int64",tr.VARINT,function(e){const t=new Uint8Array(MT(e));return ep.encode(e,t)},function(e,t){return 0n|ep.decode(e,t)},MT);const LT=(di("sfixed32",tr.BIT32,function(e){const t=new $n(new Uint8Array(4));return t.setInt32(0,e,!0),t},function(e,t){return e.getInt32(t,!0)},function(){return 4}),function(){return 8});var kv;di("sfixed64",tr.BIT64,function(e){const t=new $n(new Uint8Array(8));return t.setBigInt64(0,e,!0),t},function(e,t){return e.getBigInt64(t,!0)},LT),di("sint32",tr.VARINT,function(e){return ym.encode(e)},function(e,t){return ym.decode(e,t)},function(e){return ym.encodingLength(e)}),di("sint64",tr.VARINT,function(e){return tp.encode(e)},function(e,t){return tp.decode(e,t)},function(e){return tp.encodingLength(e)}),di("string",tr.LENGTH_DELIMITED,function(e){const t=_t(e);return new $n(Qt.encode(t.byteLength),t)},function(e,t){const r=Qt.decode(e,t);return t+=Qt.encodingLength(r),Mt(e.subarray(t,t+r))},function(e){const t=_t(e).byteLength;return Qt.encodingLength(t)+t}),di("uint32",tr.VARINT,function(e){return Qt.encode(e)},function(e,t){return Qt.decode(e,t)},function(e){return Qt.encodingLength(e)}),di("uint64",tr.VARINT,function(e){return Za.encode(e)},function(e,t){return Za.decode(e,t)},function(e){return Za.encodingLength(e)}),function(n){let e;var t;(t=e=n.NoiseHandshakePayload||(n.NoiseHandshakePayload={})).codec=()=>function o7(n){return di("message",tr.LENGTH_DELIMITED,function(s){const o=new $n;function a(m,T,R){if(null==m){if(!0===R.optional)return;throw new Error(`Non optional field "${R.name}" was ${null===m?"null":"undefined"}`)}const k=T<<3|R.codec.type,U=CT(Qt.encodingLength(k));Qt.encode(k,U);const Q=R.codec.encode(m);o.append(U),o.append(Q)}for(const[m,T]of Object.entries(n)){const R=parseInt(m);if(!0===T.repeats){if(!Array.isArray(s[T.name]))throw new Error(`Repeating field "${T.name}" was not an array`);for(const k of s[T.name])a(k,R,T)}else a(s[T.name],R,T)}const c=Qt.encode(o.length);return new $n(c,o)},function(s,o){const a=Qt.decode(s,o),c=(o+=Qt.encodingLength(a))+a,m={};for(;o>3];let Q=0;if(R===tr.VARINT)if(null!=U){const X=U.codec.decode(s,o);Q=U.codec.encodingLength(X)}else{const X=Qt.decode(s,o);Q=Qt.encodingLength(X)}else if(R===tr.BIT64)Q=8;else if(R===tr.LENGTH_DELIMITED){const X=Qt.decode(s,o);Q=X+Qt.encodingLength(X)}else if(R===tr.BIT32)Q=4;else{if(R===tr.START_GROUP)throw new Error("Unsupported wire type START_GROUP");if(R===tr.END_GROUP)throw new Error("Unsupported wire type END_GROUP")}if(null!=U){const X=U.codec.decode(s,o);!0===U.repeats?(null==m[U.name]&&(m[U.name]=[]),m[U.name].push(X)):m[U.name]=X}o+=Q}for(const T of Object.values(n))!0===T.repeats&&null==m[T.name]&&(m[T.name]=[]);return m},function(s){let o=0;for(const a of Object.values(n))o+=a.codec.encodingLength(s[a.name]);return Qt.encodingLength(o)+o})}({1:{name:"identityKey",codec:Lv},2:{name:"identitySig",codec:Lv},3:{name:"data",codec:Lv}}),t.encode=r=>function HV(n,e){const t=e.encode(n),r=Qt.encodingLength(Qt.decode(t));return t instanceof Uint8Array?new $n(t.subarray(r)):t.sublist(r)}(r,t.codec()),t.decode=r=>function VV(n,e){const t=CT(Qt.encodingLength(n.byteLength));return Qt.encode(n.byteLength,t),e.decode(new $n(t,n),0)}(r,t.codec())}(kv||(kv={}));const kT=kv.NoiseHandshakePayload;function Bv(){return Bv=V(function*(n,e,t){const r=yield A7(n,BT(e)),i=t??new Uint8Array(0);if(null==n.publicKey)throw new Error("PublicKey was missing from local PeerId");return T7(n.publicKey,r,i)}),Bv.apply(this,arguments)}function T7(n,e,t){return kT.encode({identityKey:n,identitySig:e,data:t??new Uint8Array(0)}).subarray()}function A7(n,e){return Fv.apply(this,arguments)}function Fv(){return Fv=V(function*(n,e){if(null==n.privateKey)throw new Error("PrivateKey was missing from PeerId");return yield(yield Au(n.privateKey)).sign(e)}),Fv.apply(this,arguments)}function gf(n){return Uv.apply(this,arguments)}function Uv(){return Uv=V(function*(n){return yield xu(n.identityKey)}),Uv.apply(this,arguments)}function yf(n){return kT.decode(n)}function BT(n){const e=_t("noise-libp2p-static-key:");return or([e,n],e.length+n.length)}function mf(n,e,t){return Vv.apply(this,arguments)}function Vv(){return Vv=V(function*(n,e,t){const r=yield xu(e.identityKey);if(!r.equals(t))throw new Error("Peer ID doesn't match libp2p public key.");const i=BT(n);if(null==r.publicKey)throw new Error("PublicKey was missing from PeerId");if(null==e.identitySig)throw new Error("Signature was missing from message");if(!(yield Tu(r.publicKey).verify(i,e.identitySig)))throw new Error("Static key doesn't match to peer that signed payload!");return r}),Vv.apply(this,arguments)}function Xa(n){return!(!(n instanceof Uint8Array)||32!==n.length)}var Ur=N(1455);function Gt(n){return Object.assign(Ur(n),{error:Ur(`${n}:error`),trace:Ur(`${n}:trace`)})}Ur.formatters.b=n=>null==n?"undefined":Ci.baseEncode(n),Ur.formatters.t=n=>null==n?"undefined":Ro.baseEncode(n),Ur.formatters.m=n=>null==n?"undefined":Lh.baseEncode(n),Ur.formatters.p=n=>null==n?"undefined":n.toString(),Ur.formatters.c=n=>null==n?"undefined":n.toString(),Ur.formatters.k=n=>null==n?"undefined":n.toString();const ln=Gt("libp2p:noise");let hs;function FT(n){hs(`LOCAL_STATIC_PUBLIC_KEY ${Mt(n.publicKey,"hex")}`),hs(`LOCAL_STATIC_PRIVATE_KEY ${Mt(n.privateKey,"hex")}`)}function vf(n){n?(hs(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Mt(n.publicKey,"hex")}`),hs(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Mt(n.privateKey,"hex")}`)):hs("Missing local ephemeral keys.")}function Hv(n){hs(`REMOTE_STATIC_PUBLIC_KEY ${Mt(n,"hex")}`)}function Ru(n){hs(`REMOTE_EPHEMERAL_PUBLIC_KEY ${Mt(n,"hex")}`)}function UT(n){n.cs1&&n.cs2?(hs(`CIPHER_STATE_1 ${n.cs1.n.getUint64()} ${Mt(n.cs1.k,"hex")}`),hs(`CIPHER_STATE_2 ${n.cs2.n.getUint64()} ${Mt(n.cs2.k,"hex")}`)):hs("Missing cipher state.")}hs=V5?ln:Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});class N7{constructor(e=0){this.n=e,this.bytes=new Uint8Array(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}class VT{constructor(e){this.crypto=e}encryptWithAd(e,t,r){const i=this.encrypt(e.k,e.n,t,r);return e.n.increment(),i}decryptWithAd(e,t,r){const{plaintext:i,valid:s}=this.decrypt(e.k,e.n,t,r);return e.n.increment(),{plaintext:i,valid:s}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){return $r(this.createEmptyKey(),e)}encrypt(e,t,r,i){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,t.getBytes(),r,e)}encryptAndHash(e,t){let r;return r=this.hasKey(e.cs)?this.encryptWithAd(e.cs,e.h,t):t,this.mixHash(e,r),r}decrypt(e,t,r,i){t.assertValue();const s=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),r,e);return s?{plaintext:s,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,t){let r,i=!0;return this.hasKey(e.cs)?({plaintext:r,valid:i}=this.decryptWithAd(e.cs,e.h,t)):r=t,this.mixHash(e,t),{plaintext:r,valid:i}}dh(e,t){try{const r=this.crypto.generateX25519SharedKey(e,t);return 32===r.length?r:r.subarray(0,32)}catch(r){return ln(r.message),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(or([e,t],e.length+t.length))}mixKey(e,t){const[r,i]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(i),e.ck=r}initializeKey(e){return{k:e,n:new N7}}initializeSymmetric(e){const t=_t(e,"utf-8"),r=this.hashProtocolName(t),i=r,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:i,h:r}}hashProtocolName(e){if(e.length<=32){const t=new Uint8Array(32);return t.set(e),t}return this.getHash(e,new Uint8Array(0))}split(e){const[t,r]=this.crypto.getHKDF(e.ck,new Uint8Array(0));return{cs1:this.initializeKey(t),cs2:this.initializeKey(r)}}writeMessageRegular(e,t){const r=this.encryptWithAd(e,new Uint8Array(0),t);return{ne:this.createEmptyKey(),ns:new Uint8Array(0),ciphertext:r}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}}class M7 extends VT{initSession(e,t,r,i){const s=this.createEmptyKey();let o;return o=e?this.initializeInitiator(t,r,i,s):this.initializeResponder(t,r,i,s),{hs:o,i:e,mc:0}}sendMessage(e,t){let r;if(0===e.mc)r=this.writeMessageA(e.hs,t);else if(1===e.mc){const{messageBuffer:i,h:s,cs1:o,cs2:a}=this.writeMessageB(e.hs,t);r=i,e.h=s,e.cs1=o,e.cs2=a}else{if(!(e.mc>1))throw new Error("Session invalid.");if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");r=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");r=this.writeMessageRegular(e.cs2,t)}}return e.mc++,r}recvMessage(e,t){let r=new Uint8Array(0),i=!1;if(0===e.mc&&({plaintext:r,valid:i}=this.readMessageA(e.hs,t)),1===e.mc){const{plaintext:s,valid:o,h:a,cs1:c,cs2:m}=this.readMessageB(e.hs,t);r=s,i=o,e.h=a,e.cs1=c,e.cs2=m}return e.mc++,{plaintext:r,valid:i}}writeMessageA(e,t){e.e=this.crypto.generateX25519KeyPair();const r=e.e.publicKey;this.mixHash(e.ss,r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const s=this.encryptAndHash(e.ss,e.s.publicKey);return this.mixKey(e.ss,this.dh(e.s.privateKey,e.rs)),{ne:r,ns:s,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();const r=e.e.publicKey;this.mixHash(e.ss,r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re)),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const i=this.encryptAndHash(e.ss,t),o={ne:r,ns:this.createEmptyKey(),ciphertext:i},{cs1:a,cs2:c}=this.split(e.ss);return{messageBuffer:o,cs1:a,cs2:c,h:e.ss.h}}readMessageA(e,t){Xa(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));const{plaintext:r,valid:i}=this.decryptAndHash(e.ss,t.ns);i&&Xa(r)&&(e.rs=r),this.mixKey(e.ss,this.dh(e.s.privateKey,e.rs));const{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:i&&o}}readMessageB(e,t){if(Xa(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state should contain ephemeral key by now.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re)),this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));const{plaintext:r,valid:i}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:s,cs2:o}=this.split(e.ss);return{h:e.ss.h,valid:i,plaintext:r,cs1:s,cs2:o}}initializeInitiator(e,t,r,i){const o=this.initializeSymmetric("Noise_IK_25519_ChaChaPoly_SHA256");return this.mixHash(o,e),this.mixHash(o,r),{ss:o,s:t,rs:r,re:new Uint8Array(32),psk:i}}initializeResponder(e,t,r,i){const o=this.initializeSymmetric("Noise_IK_25519_ChaChaPoly_SHA256");return this.mixHash(o,e),this.mixHash(o,t.publicKey),{ss:o,s:t,rs:r,re:new Uint8Array(32),psk:i}}}class HT extends Error{constructor(e,t){super(t),this.initialMsg=e,this.name="FailedIKhandshake"}}class O7{constructor(e,t,r,i,s,o,a,c,m){this.isInitiator=e,this.payload=t,this.prologue=r,this.staticKeypair=s,this.connection=o,c&&(this.remotePeer=c),this.ik=m??new M7(i),this.session=this.ik.initSession(this.isInitiator,this.prologue,this.staticKeypair,a),this.remoteEarlyData=new Uint8Array}stage0(){var e=this;return V(function*(){if(FT(e.session.hs.s),Hv(e.session.hs.rs),e.isInitiator){ln("IK Stage 0 - Initiator sending message...");const t=e.ik.sendMessage(e.session,e.payload);e.connection.writeLP(l2(t)),ln("IK Stage 0 - Initiator sent message."),vf(e.session.hs.e)}else{ln("IK Stage 0 - Responder receiving message...");const t=yield e.connection.readLP();try{const r=bm(t.slice()),{plaintext:i,valid:s}=e.ik.recvMessage(e.session,r);if(!s)throw new Error("ik handshake stage 0 decryption validation fail");ln("IK Stage 0 - Responder got message, going to verify payload.");const o=yf(i);e.remotePeer=e.remotePeer||(yield gf(o)),yield mf(e.session.hs.rs,o,e.remotePeer),e.setRemoteEarlyData(o.data),ln("IK Stage 0 - Responder successfully verified payload!"),Ru(e.session.hs.re)}catch(r){const i=r;throw ln("Responder breaking up with IK handshake in stage 0."),new HT(t.slice(),`Error occurred while verifying initiator's signed payload: ${i.message}`)}}})()}stage1(){var e=this;return V(function*(){if(e.isInitiator){ln("IK Stage 1 - Initiator receiving message...");const t=(yield e.connection.readLP()).slice(),r=wm(t),{plaintext:i,valid:s}=e.ik.recvMessage(e.session,r);ln("IK Stage 1 - Initiator got message, going to verify payload.");try{if(!s)throw new Error("ik stage 1 decryption validation fail");const o=yf(i);e.remotePeer=e.remotePeer||(yield gf(o)),yield mf(r.ns.slice(0,32),o,e.remotePeer),e.setRemoteEarlyData(o.data),ln("IK Stage 1 - Initiator successfully verified payload!"),Ru(e.session.hs.re)}catch(o){const a=o;throw ln("Initiator breaking up with IK handshake in stage 1."),new HT(t,`Error occurred while verifying responder's signed payload: ${a.message}`)}}else{ln("IK Stage 1 - Responder sending message...");const t=e.ik.sendMessage(e.session,e.payload);e.connection.writeLP(u2(t)),ln("IK Stage 1 - Responder sent message..."),vf(e.session.hs.e)}UT(e.session)})()}decrypt(e,t){const r=this.getCS(t,!1);return this.ik.decryptWithAd(r,new Uint8Array(0),e)}encrypt(e,t){const r=this.getCS(t);return this.ik.encryptWithAd(r,new Uint8Array(0),e)}getLocalEphemeralKeys(){if(!this.session.hs.e)throw new Error("Ephemeral keys do not exist.");return this.session.hs.e}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new Error("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteEarlyData(e){e&&(this.remoteEarlyData=e)}}class np extends Error{constructor(e="Unexpected Peer"){super(e),this.code=np.code}static get code(){return"ERR_UNEXPECTED_PEER"}}class Pu extends Error{constructor(e="Invalid crypto exchange"){super(e),this.code=Pu.code}static get code(){return"ERR_INVALID_CRYPTO_EXCHANGE"}}Error;class L7 extends VT{initializeInitiator(e,t,r,i){const o=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(o,e),{ss:o,s:t,rs:r,psk:i,re:new Uint8Array(32)}}initializeResponder(e,t,r,i){const o=this.initializeSymmetric("Noise_XX_25519_ChaChaPoly_SHA256");return this.mixHash(o,e),{ss:o,s:t,rs:r,psk:i,re:new Uint8Array(32)}}writeMessageA(e,t,r){const i=new Uint8Array(0);e.e=void 0!==r?r:this.crypto.generateX25519KeyPair();const s=e.e.publicKey;return this.mixHash(e.ss,s),{ne:s,ns:i,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();const r=e.e.publicKey;this.mixHash(e.ss,r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));const s=this.encryptAndHash(e.ss,e.s.publicKey);return this.mixKey(e.ss,this.dh(e.s.privateKey,e.re)),{ne:r,ns:s,ciphertext:this.encryptAndHash(e.ss,t)}}writeMessageC(e,t){const i=this.encryptAndHash(e.ss,e.s.publicKey);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));const s=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:m}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:m}}readMessageA(e,t){return Xa(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(Xa(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));const{plaintext:r,valid:i}=this.decryptAndHash(e.ss,t.ns);i&&Xa(r)&&(e.rs=r),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,t){const{plaintext:r,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&Xa(r)&&(e.rs=r),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));const{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,t,r){const i=this.createEmptyKey(),s=new Uint8Array(32);let o;return o=e?this.initializeInitiator(t,r,s,i):this.initializeResponder(t,r,s,i),{hs:o,i:e,mc:0}}sendMessage(e,t,r){let i;if(0===e.mc)i=this.writeMessageA(e.hs,t,r);else if(1===e.mc)i=this.writeMessageB(e.hs,t);else if(2===e.mc){const{h:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=o,e.h=s,e.cs1=a,e.cs2=c}else{if(!(e.mc>2))throw new Error("Session invalid.");if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,t)}}return e.mc++,i}recvMessage(e,t){let r=new Uint8Array(0),i=!1;if(0===e.mc)({plaintext:r,valid:i}=this.readMessageA(e.hs,t));else if(1===e.mc)({plaintext:r,valid:i}=this.readMessageB(e.hs,t));else if(2===e.mc){const{h:s,plaintext:o,valid:a,cs1:c,cs2:m}=this.readMessageC(e.hs,t);r=o,i=a,e.h=s,e.cs1=c,e.cs2=m}return e.mc++,{plaintext:r,valid:i}}}class jT{constructor(e,t,r,i,s,o,a,c){this.isInitiator=e,this.payload=t,this.prologue=r,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new L7(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair),this.remoteEarlyData=new Uint8Array(0)}propose(){var e=this;return V(function*(){if(FT(e.session.hs.s),e.isInitiator){ln("Stage 0 - Initiator starting to send first message.");const t=e.xx.sendMessage(e.session,new Uint8Array(0));e.connection.writeLP(u2(t)),ln("Stage 0 - Initiator finished sending first message."),vf(e.session.hs.e)}else{ln("Stage 0 - Responder waiting to receive first message...");const t=wm((yield e.connection.readLP()).subarray()),{valid:r}=e.xx.recvMessage(e.session,t);if(!r)throw new Pu("xx handshake stage 0 validation fail");ln("Stage 0 - Responder received first message."),Ru(e.session.hs.re)}})()}exchange(){var e=this;return V(function*(){if(e.isInitiator){ln("Stage 1 - Initiator waiting to receive first message from responder...");const t=bm((yield e.connection.readLP()).subarray()),{plaintext:r,valid:i}=e.xx.recvMessage(e.session,t);if(!i)throw new Pu("xx handshake stage 1 validation fail");ln("Stage 1 - Initiator received the message."),Ru(e.session.hs.re),Hv(e.session.hs.rs),ln("Initiator going to check remote's signature...");try{const s=yf(r);e.remotePeer=e.remotePeer||(yield gf(s)),yield mf(e.session.hs.rs,s,e.remotePeer),e.setRemoteEarlyData(s.data)}catch(s){throw new np(`Error occurred while verifying signed payload: ${s.message}`)}ln("All good with the signature!")}else{ln("Stage 1 - Responder sending out first message with signed payload and static key.");const t=e.xx.sendMessage(e.session,e.payload);e.connection.writeLP(l2(t)),ln("Stage 1 - Responder sent the second handshake message with signed payload."),vf(e.session.hs.e)}})()}finish(){var e=this;return V(function*(){if(e.isInitiator){ln("Stage 2 - Initiator sending third handshake message.");const t=e.xx.sendMessage(e.session,e.payload);e.connection.writeLP(function z5(n){return or([n.ns,n.ciphertext],n.ns.length+n.ciphertext.length)}(t)),ln("Stage 2 - Initiator sent message with signed payload.")}else{ln("Stage 2 - Responder waiting for third handshake message...");const t=function W5(n){if(n.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:n.subarray(0,48),ciphertext:n.subarray(48,n.length)}}((yield e.connection.readLP()).subarray()),{plaintext:r,valid:i}=e.xx.recvMessage(e.session,t);if(!i)throw new Pu("xx handshake stage 2 validation fail");ln("Stage 2 - Responder received the message, finished handshake.");try{const s=yf(r);e.remotePeer=e.remotePeer||(yield gf(s)),yield mf(e.session.hs.rs,s,e.remotePeer),e.setRemoteEarlyData(s.data)}catch(s){throw new np(`Error occurred while verifying signed payload: ${s.message}`)}}UT(e.session)})()}encrypt(e,t){const r=this.getCS(t);return this.xx.encryptWithAd(r,new Uint8Array(0),e)}decrypt(e,t){const r=this.getCS(t,!1);return this.xx.decryptWithAd(r,new Uint8Array(0),e)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new Pu("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteEarlyData(e){e&&(this.remoteEarlyData=e)}}class k7 extends jT{constructor(e,t,r,i,s,o,a,c,m,T){super(e,t,r,i,s,o,c,T),m&&(this.ephemeralKeys=m),this.initialMsg=a}propose(){var e=this;return V(function*(){if(e.isInitiator)e.xx.sendMessage(e.session,new Uint8Array(0),e.ephemeralKeys),ln("XX Fallback Stage 0 - Initialized state as the first message was sent by initiator."),vf(e.session.hs.e);else{ln("XX Fallback Stage 0 - Responder decoding initial msg from IK.");const t=wm(e.initialMsg),{valid:r}=e.xx.recvMessage(e.session,{ne:t.ne,ns:new Uint8Array(0),ciphertext:new Uint8Array(0)});if(!r)throw new Error("xx fallback stage 0 decryption validation fail");ln("XX Fallback Stage 0 - Responder used received message from IK."),Ru(e.session.hs.re)}})()}exchange(){var e=()=>super.exchange,t=this;return V(function*(){if(t.isInitiator){const r=bm(t.initialMsg),{plaintext:i,valid:s}=t.xx.recvMessage(t.session,r);if(!s)throw new Error("xx fallback stage 1 decryption validation fail");ln("XX Fallback Stage 1 - Initiator used received message from IK."),Ru(t.session.hs.re),Hv(t.session.hs.rs),ln("Initiator going to check remote's signature...");try{const o=yf(i);t.remotePeer=t.remotePeer||(yield gf(o)),yield mf(t.session.hs.rs,o,t.remotePeer),t.setRemoteEarlyData(o.data)}catch(o){throw new Error(`Error occurred while verifying signed payload from responder: ${o.message}`)}ln("All good with the signature!")}else ln("XX Fallback Stage 1 - Responder start"),yield e().call(t),ln("XX Fallback Stage 1 - Responder end")})()}}function rp(n,e){const t={[Symbol.iterator]:()=>t,next:()=>{const r=n.next(),i=r.value;return!0===r.done||null==i?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}class $T{constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),r)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){this.map.delete(e.toString())}entries(){return rp(this.map.entries(),e=>[_r(e[0]),e[1]])}forEach(e){this.map.forEach((t,r)=>{e(t,_r(r),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return rp(this.map.keys(),e=>_r(e))}values(){return this.map.values()}get size(){return this.map.size}}class B7{constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return rp(this.set.entries(),e=>{const t=_r(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{const r=_r(t);e(r,r,this)})}has(e){return this.set.has(e.toString())}values(){return rp(this.set.values(),e=>_r(e))}}Symbol;const jv=new class F7{constructor(){this.storage=new $T}store(e,t){this.storage.set(e,t)}load(e){return e?this.storage.get(e)??null:null}resetStorage(){this.storage.clear()}};class GT{constructor(e,t,r=K5){this.protocol="/noise",this.prologue=new Uint8Array(0),this.earlyData=t??new Uint8Array(0),this.useNoisePipes=!1,this.crypto=r,this.staticKeys=e?this.crypto.generateX25519KeyPairFromSeed(e):this.crypto.generateX25519KeyPair()}secureOutbound(e,t,r){var i=this;return V(function*(){const s=r2(t,{lengthEncoder:Rh,lengthDecoder:Ph,maxDataLength:Ql}),o=yield i.performHandshake({connection:s,isInitiator:!0,localPeer:e,remotePeer:r});return{conn:yield i.createSecureConnection(s,o),remoteEarlyData:o.remoteEarlyData,remotePeer:o.remotePeer}})()}secureInbound(e,t,r){var i=this;return V(function*(){const s=r2(t,{lengthEncoder:Rh,lengthDecoder:Ph,maxDataLength:Ql}),o=yield i.performHandshake({connection:s,isInitiator:!1,localPeer:e,remotePeer:r});return{conn:yield i.createSecureConnection(s,o),remoteEarlyData:o.remoteEarlyData,remotePeer:o.remotePeer}})()}performHandshake(e){var t=this;return V(function*(){const r=yield function C7(n,e,t){return Bv.apply(this,arguments)}(e.localPeer,t.staticKeys.publicKey,t.earlyData);let i=t.useNoisePipes;if(e.isInitiator&&null===jv.load(e.remotePeer)&&(i=!1),!i)return yield t.performXXHandshake(e,r);{const{remotePeer:s,connection:o,isInitiator:a}=e,c=new O7(a,r,t.prologue,t.crypto,t.staticKeys,o,jv.load(e.remotePeer)??new Uint8Array(32),s);try{return yield t.performIKHandshake(c)}catch(m){const T=m;let R;return e.isInitiator&&(R=c.getLocalEphemeralKeys()),yield t.performXXFallbackHandshake(e,r,T.initialMsg,R)}}})()}performXXFallbackHandshake(e,t,r,i){var s=this;return V(function*(){const{isInitiator:o,remotePeer:a,connection:c}=e,m=new k7(o,t,s.prologue,s.crypto,s.staticKeys,c,r,a,i);try{yield m.propose(),yield m.exchange(),yield m.finish()}catch(T){const R=T;throw R.message=`Error occurred during XX Fallback handshake: ${R.message}`,ln(R),R}return m})()}performXXHandshake(e,t){var r=this;return V(function*(){const{isInitiator:i,remotePeer:s,connection:o}=e,a=new jT(i,t,r.prologue,r.crypto,r.staticKeys,o,s);try{yield a.propose(),yield a.exchange(),yield a.finish(),r.useNoisePipes&&a.remotePeer&&jv.store(a.remotePeer,a.getRemoteStaticKey())}catch(c){if(c instanceof Error)throw c.message=`Error occurred during XX handshake: ${c.message}`,c}return a})()}performIKHandshake(e){return V(function*(){return yield e.stage0(),yield e.stage1(),e})()}createSecureConnection(e,t){return V(function*(){const[r,i]=function B5(){const n=i2(),e=i2();return[{source:n.source,sink:e.sink},{source:e.source,sink:n.sink}]}(),s=e.unwrap();return yield Ln(r,function j5(n){return function(){var e=un(function*(t){var s,r=!1,i=!1;try{for(var a,o=Tt(t);r=!(a=yield ct(o.next())).done;r=!1){const c=a.value;for(let m=0;mc.length&&(T=c.length),yield n.encrypt(c.subarray(m,T),n.session)}}}catch(c){i=!0,s=c}finally{try{r&&null!=o.return&&(yield ct(o.return()))}finally{if(i)throw s}}});return function(t){return e.apply(this,arguments)}}()}(t),to({lengthEncoder:Rh}),s,Ms({lengthDecoder:Ph}),function $5(n){return function(){var e=un(function*(t){var s,r=!1,i=!1;try{for(var a,o=Tt(t);r=!(a=yield ct(o.next())).done;r=!1){const c=a.value;for(let m=0;mc.length&&(T=c.length);const{plaintext:R,valid:k}=yield ct(n.decrypt(c.subarray(m,T),n.session));if(!k)throw new Error("Failed to validate decrypted chunk");yield R}}}catch(c){i=!0,s=c}finally{try{r&&null!=o.return&&(yield ct(o.return()))}finally{if(i)throw s}}});return function(t){return e.apply(this,arguments)}}()}(t),r),i})()}}function Lo(n){return null!=n&&"function"==typeof n.start&&"function"==typeof n.stop}function hi(n){return null!=n&&"function"==typeof n.init}new GT;class ko{constructor(e={}){this.started=!1,null!=e.peerId&&this.setPeerId(e.peerId),null!=e.addressManager&&this.setAddressManager(e.addressManager),null!=e.peerStore&&this.setPeerStore(e.peerStore),null!=e.upgrader&&this.setUpgrader(e.upgrader),null!=e.metrics&&this.setMetrics(e.metrics),null!=e.registrar&&this.setRegistrar(e.registrar),null!=e.connectionManager&&this.setConnectionManager(e.connectionManager),null!=e.transportManager&&this.setTransportManager(e.transportManager),null!=e.connectionGater&&this.setConnectionGater(e.connectionGater),null!=e.contentRouting&&this.setContentRouting(e.contentRouting),null!=e.peerRouting&&this.setPeerRouting(e.peerRouting),null!=e.datastore&&this.setDatastore(e.datastore),null!=e.connectionProtector&&this.setConnectionProtector(e.connectionProtector),null!=e.dht&&this.setDHT(e.dht),null!=e.pubsub&&this.setPubSub(e.pubsub)}isStarted(){return this.started}beforeStart(){var e=this;return V(function*(){yield Promise.all(Object.values(e).filter(t=>Lo(t)).map(function(){var t=V(function*(r){null!=r.beforeStart&&(yield r.beforeStart())});return function(r){return t.apply(this,arguments)}}()))})()}start(){var e=this;return V(function*(){yield Promise.all(Object.values(e).filter(t=>Lo(t)).map(function(){var t=V(function*(r){yield r.start()});return function(r){return t.apply(this,arguments)}}())),e.started=!0})()}afterStart(){var e=this;return V(function*(){yield Promise.all(Object.values(e).filter(t=>Lo(t)).map(function(){var t=V(function*(r){null!=r.afterStart&&(yield r.afterStart())});return function(r){return t.apply(this,arguments)}}()))})()}beforeStop(){var e=this;return V(function*(){yield Promise.all(Object.values(e).filter(t=>Lo(t)).map(function(){var t=V(function*(r){null!=r.beforeStop&&(yield r.beforeStop())});return function(r){return t.apply(this,arguments)}}()))})()}stop(){var e=this;return V(function*(){yield Promise.all(Object.values(e).filter(t=>Lo(t)).map(function(){var t=V(function*(r){yield r.stop()});return function(r){return t.apply(this,arguments)}}())),e.started=!1})()}afterStop(){var e=this;return V(function*(){yield Promise.all(Object.values(e).filter(t=>Lo(t)).map(function(){var t=V(function*(r){null!=r.afterStop&&(yield r.afterStop())});return function(r){return t.apply(this,arguments)}}()))})()}setPeerId(e){return this.peerId=e,e}getPeerId(){if(null==this.peerId)throw se(new Error("peerId not set"),"ERR_SERVICE_MISSING");return this.peerId}setMetrics(e){return this.metrics=e,hi(e)&&e.init(this),e}getMetrics(){return this.metrics}setAddressManager(e){return this.addressManager=e,hi(e)&&e.init(this),e}getAddressManager(){if(null==this.addressManager)throw se(new Error("addressManager not set"),"ERR_SERVICE_MISSING");return this.addressManager}setPeerStore(e){return this.peerStore=e,hi(e)&&e.init(this),e}getPeerStore(){if(null==this.peerStore)throw se(new Error("peerStore not set"),"ERR_SERVICE_MISSING");return this.peerStore}setUpgrader(e){return this.upgrader=e,hi(e)&&e.init(this),e}getUpgrader(){if(null==this.upgrader)throw se(new Error("upgrader not set"),"ERR_SERVICE_MISSING");return this.upgrader}setRegistrar(e){return this.registrar=e,hi(e)&&e.init(this),e}getRegistrar(){if(null==this.registrar)throw se(new Error("registrar not set"),"ERR_SERVICE_MISSING");return this.registrar}setConnectionManager(e){return this.connectionManager=e,hi(e)&&e.init(this),e}getConnectionManager(){if(null==this.connectionManager)throw se(new Error("connectionManager not set"),"ERR_SERVICE_MISSING");return this.connectionManager}setTransportManager(e){return this.transportManager=e,hi(e)&&e.init(this),e}getTransportManager(){if(null==this.transportManager)throw se(new Error("transportManager not set"),"ERR_SERVICE_MISSING");return this.transportManager}setConnectionGater(e){return this.connectionGater=e,hi(e)&&e.init(this),e}getConnectionGater(){if(null==this.connectionGater)throw se(new Error("connectionGater not set"),"ERR_SERVICE_MISSING");return this.connectionGater}setContentRouting(e){return this.contentRouting=e,hi(e)&&e.init(this),e}getContentRouting(){if(null==this.contentRouting)throw se(new Error("contentRouting not set"),"ERR_SERVICE_MISSING");return this.contentRouting}setPeerRouting(e){return this.peerRouting=e,hi(e)&&e.init(this),e}getPeerRouting(){if(null==this.peerRouting)throw se(new Error("peerRouting not set"),"ERR_SERVICE_MISSING");return this.peerRouting}setDatastore(e){return this.datastore=e,hi(e)&&e.init(this),e}getDatastore(){if(null==this.datastore)throw se(new Error("datastore not set"),"ERR_SERVICE_MISSING");return this.datastore}setConnectionProtector(e){return this.connectionProtector=e,hi(e)&&e.init(this),e}getConnectionProtector(){return this.connectionProtector}setDHT(e){return this.dht=e,hi(e)&&e.init(this),e}getDHT(){if(null==this.dht)throw se(new Error("dht not set"),"ERR_SERVICE_MISSING");return this.dht}setPubSub(e){return this.pubsub=e,hi(e)&&e.init(this),e}getPubSub(){if(null==this.pubsub)throw se(new Error("pubsub not set"),"ERR_SERVICE_MISSING");return this.pubsub}}class zT extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Fs(n,e,t){const r=t??{},i=function U7(n){if(null!=n){if("function"==typeof n[Symbol.iterator])return n[Symbol.iterator]();if("function"==typeof n[Symbol.asyncIterator])return n[Symbol.asyncIterator]();if("function"==typeof n.next)return n}throw new Error("argument is not an iterator or iterable")}(n);function o(){return(o=un(function*(){let a;const c=()=>{a?.()};for(e.addEventListener("abort",c);;){let m;try{if(e.aborted){const{abortMessage:R,abortCode:k}=r;throw new zT(R,k)}const T=new Promise((R,k)=>{a=()=>{const{abortMessage:U,abortCode:Q}=r;k(new zT(U,Q))}});m=yield ct(Promise.race([T,i.next()])),a=null}catch(T){e.removeEventListener("abort",c);const R="aborted"===T.type&&e.aborted;if(R&&null!=r.onAbort&&(yield ct(r.onAbort(n))),"function"==typeof i.return)try{const k=i.return();k instanceof Promise&&k.catch(U=>{null!=r.onReturnError&&r.onReturnError(U)})}catch(k){null!=r.onReturnError&&r.onReturnError(k)}if(R&&!0===r.returnOnAbort)return;throw T}if(!0===m.done)break;yield m.value}e.removeEventListener("abort",c)})).apply(this,arguments)}return function s(){return o.apply(this,arguments)}()}function V7(n,e,t){return r=>n(Fs(r,e,t))}function ga(n,e,t){return{sink:V7(n.sink,e,{...t,onAbort:void 0}),source:Fs(n.source,e,t)}}var Vn=N(1732);function WT(n){return new Uint8Array(n)}var Jt=(()=>(function(n){n[n.NEW_STREAM=0]="NEW_STREAM",n[n.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",n[n.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",n[n.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",n[n.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",n[n.RESET_RECEIVER=5]="RESET_RECEIVER",n[n.RESET_INITIATOR=6]="RESET_INITIATOR"}(Jt||(Jt={})),Jt))();const qT=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),QT=Object.freeze({NEW_STREAM:Jt.NEW_STREAM,MESSAGE:Jt.MESSAGE_INITIATOR,CLOSE:Jt.CLOSE_INITIATOR,RESET:Jt.RESET_INITIATOR}),H7=Object.freeze({MESSAGE:Jt.MESSAGE_RECEIVER,CLOSE:Jt.CLOSE_RECEIVER,RESET:Jt.RESET_RECEIVER}),YT=new class K7{constructor(){this._pool=WT(10240),this._poolOffset=0}write(e){const t=this._pool;let r=this._poolOffset;Vn.encode(e.id<<3|e.type,t,r),r+=Vn.encode.bytes,Vn.encode(e.type!==Jt.NEW_STREAM&&e.type!==Jt.MESSAGE_INITIATOR&&e.type!==Jt.MESSAGE_RECEIVER||null==e.data?0:e.data.length,t,r),r+=Vn.encode.bytes;const i=t.subarray(this._poolOffset,r);return 10240-r<100?(this._pool=WT(10240),this._poolOffset=0):this._poolOffset=r,e.type!==Jt.NEW_STREAM&&e.type!==Jt.MESSAGE_INITIATOR&&e.type!==Jt.MESSAGE_RECEIVER||null==e.data?[i]:[i,e.data instanceof Uint8Array?e.data:e.data.subarray()]}};function Wv(){return Wv=un(function*(n){var r,e=!1,t=!1;try{for(var s,i=Tt(n);e=!(s=yield ct(i.next())).done;e=!1){const o=s.value;if(Array.isArray(o))for(const a of o)yield*jr(Tt(YT.write(a)),ct);else yield*jr(Tt(YT.write(o)),ct)}}catch(o){t=!0,r=o}finally{try{e&&null!=i.return&&(yield ct(i.return()))}finally{if(t)throw r}}}),Wv.apply(this,arguments)}class $7{constructor(){this._buffer=new $n,this._headerInfo=null}write(e){if(null==e||0===e.length)return[];this._buffer.append(e);const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch{break}const{id:r,type:i,length:s,offset:o}=this._headerInfo;if(this._buffer.length-o>3,type:o,offset:r+s,length:i}}}function XT(n,e=0){let s,t=0,r=0,i=e;const o=n.length;do{if(i>=o||r>49)throw e=0,new RangeError("Could not decode varint");s=n.get(i++),t+=r<28?(127&s)<=128);return{value:t,offset:e=i-e}}function z7(n){return qv.apply(this,arguments)}function qv(){return qv=un(function*(n){const e=new $7;var i,t=!1,r=!1;try{for(var o,s=Tt(n);t=!(o=yield ct(s.next())).done;t=!1){const c=e.write(o.value);c.length>0&&(yield c)}}catch(a){r=!0,i=a}finally{try{t&&null!=s.return&&(yield ct(s.return()))}finally{if(r)throw i}}}),qv.apply(this,arguments)}const JT=1<<20;var ip=N(772);const Us=Gt("libp2p:mplex:stream"),Qv="ERR_STREAM_RESET";class X7 extends Map{constructor(e){super();const{system:t,component:r,metric:i,metrics:s}=e;this.system=t??"libp2p",this.component=r,this.metric=i,this.metrics=s,this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metrics.updateComponentMetric({system:this.system,component:this.component,metric:this.metric,value:this.size})}}function Ef(n){const{system:e,component:t,metric:r,metrics:i}=n;let s;return s=null!=i?new X7({system:e,component:t,metric:r,metrics:i}):new Map,s}const so=Gt("libp2p:mplex");function eA(n){const e={...n,type:`${qT[n.type]} (${n.type})`};return n.type===Jt.NEW_STREAM&&(e.data=Mt(n.data instanceof Uint8Array?n.data:n.data.subarray())),(n.type===Jt.MESSAGE_INITIATOR||n.type===Jt.MESSAGE_RECEIVER)&&(e.data=Mt(n.data instanceof Uint8Array?n.data:n.data.subarray(),"base16")),e}class n9{constructor(e,t){this.protocol="/mplex/6.7.0",t=t??{},this._streamId=0,this._streams={initiators:Ef({metrics:e.getMetrics(),component:"mplex",metric:"initiatorStreams"}),receivers:Ef({metrics:e.getMetrics(),component:"mplex",metric:"receiverStreams"})},this._init=t,this.sink=this._createSink();const r=this._createSource();this._source=r,this.source=r,this.closeController=new AbortController}init(e){}get streams(){const e=[];return this._streams.initiators.forEach(t=>{e.push(t)}),this._streams.receivers.forEach(t=>{e.push(t)}),e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");const t=this._streamId++;return e=null==e?t.toString():e.toString(),this._newStream({id:t,name:e,type:"initiator",registry:this._streams.initiators})}close(e){this.closeController.signal.aborted||(this.streams.forEach(null!=e?t=>t.abort(e):t=>t.close()),this.closeController.abort())}_newReceiverStream(e){const{id:t,name:r}=e;return this._newStream({id:t,name:r,type:"receiver",registry:this._streams.receivers})}_newStream(e){const{id:t,name:r,type:i,registry:s}=e;if(so("new %s stream %s %s",i,t,r),"initiator"===i&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw se(new Error("Too many outbound streams open"),"ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(t))throw new Error(`${i} stream ${t} already exists!`);const c=function Z7(n){const{id:e,name:t,send:r,onEnd:i,type:s="initiator",maxMsgSize:o=JT}=n,a=new AbortController,c=new AbortController,m=new AbortController,T="initiator"===s?QT:H7,R="initiator"===s?`i${e}`:`r${e}`,k=`${t??e}`;let ae,U=!1,Q=!1,X=!1;const he={open:Date.now()},ue=Le=>{Q||(Q=!0,Us.trace("%s stream %s sink end - err: %o",s,k,Le),null!=Le&&null==ae&&(ae=Le),U&&(he.close=Date.now(),i?.(ae)))},Re={close:()=>{Us.trace("%s stream %s close",s,k),Re.closeRead(),Re.closeWrite()},closeRead:()=>{Us.trace("%s stream %s closeRead",s,k),!U&&Re.source.end()},closeWrite:()=>{if(Us.trace("%s stream %s closeWrite",s,k),!Q){m.abort();try{r({id:e,type:T.CLOSE})}catch(Le){Us.trace("%s stream %s error sending close",s,t,Le)}ue()}},abort:Le=>{Us.trace("%s stream %s abort",s,k,Le),Re.source.end(Le),a.abort(),ue(Le)},reset:()=>{const Le=se(new Error("stream reset"),Qv);c.abort(),Re.source.end(Le),ue(Le)},sink:(Le=V(function*(Fe){if(X)throw se(new Error("sink already called on stream"),"ERR_DOUBLE_SINK");if(X=!0,Q)throw se(new Error("stream closed for writing"),"ERR_SINK_ENDED");Fe=Fs(Fe,(0,ip.anySignal)([a.signal,c.signal,m.signal]));try{"initiator"===s&&r({id:e,type:QT.NEW_STREAM,data:_t(k)});const Rn=new $n;var Zt,wt=!1,mt=!1;try{for(var zr,wn=Tt(Fe);wt=!(zr=yield wn.next()).done;wt=!1)for(Rn.append(zr.value);0!==Rn.length;){if(Rn.length<=o){r({id:e,type:T.MESSAGE,data:Rn.subarray()}),Rn.consume(Rn.length);break}const Ju=Rn.length-o;r({id:e,type:T.MESSAGE,data:Rn.subarray(0,Ju)}),Rn.consume(Ju)}}catch(Yo){mt=!0,Zt=Yo}finally{try{wt&&null!=wn.return&&(yield wn.return())}finally{if(mt)throw Zt}}}catch(Rn){if("aborted"===Rn.type&&"The operation was aborted"===Rn.message){if(m.signal.aborted)return;c.signal.aborted&&(Rn.message="stream reset",Rn.code=Qv),a.signal.aborted&&(Rn.message="stream aborted",Rn.code="ERR_STREAM_ABORT")}if(Rn.code===Qv)Us.trace("%s stream %s reset",s,t);else{Us.trace("%s stream %s error",s,t,Rn);try{r({id:e,type:T.RESET})}catch(Yo){Us.trace("%s stream %s error sending reset",s,t,Yo)}}return Re.source.end(Rn),void ue(Rn)}try{r({id:e,type:T.CLOSE})}catch(Rn){Us.trace("%s stream %s error sending close",s,t,Rn)}ue()}),function(wt){return Le.apply(this,arguments)}),source:lu({onEnd:Le=>{U||(U=!0,Us.trace("%s stream %s source end - err: %o",s,k,Le),null!=Le&&null==ae&&(ae=Le),Q&&(Re.stat.timeline.close=Date.now(),i?.(ae)))}}),stat:{direction:"initiator"===s?"outbound":"inbound",timeline:he},metadata:{},id:R};var Le;return Re}({id:t,name:r,send:m=>{so.enabled&&so.trace("%s stream %s send",i,t,eA(m)),(m.type===Jt.NEW_STREAM||m.type===Jt.MESSAGE_INITIATOR||m.type===Jt.MESSAGE_RECEIVER)&&(m.data=m.data instanceof Uint8Array?m.data:m.data.subarray()),this._source.push(m)},type:i,onEnd:()=>{so("%s stream %s ended",i,t,r),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize});return s.set(t,c),c}_createSink(){var e=this;return function(){var r=V(function*(i){const s=[e.closeController.signal];null!=e._init.signal&&s.push(e._init.signal),i=Fs(i,ip(s));try{yield Ln(i,z7,function W7(n){const e=n??JT,t=r=>{if((r.type===Jt.NEW_STREAM||r.type===Jt.MESSAGE_INITIATOR||r.type===Jt.MESSAGE_RECEIVER)&&r.data.byteLength>e)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"})};return r=>{return(i=un(function*(){var c,o=!1,a=!1;try{for(var T,m=Tt(r);o=!(T=yield ct(m.next())).done;o=!1){const R=T.value;Array.isArray(R)?(R.forEach(t),yield*jr(Tt(R),ct)):(t(R),yield R)}}catch(R){a=!0,c=R}finally{try{o&&null!=m.return&&(yield ct(m.return()))}finally{if(a)throw c}}}),function s(){return i.apply(this,arguments)})();var i}}(e._init.maxMsgSize),function(){var o=V(function*(a){var T,c=!1,m=!1;try{for(var k,R=Tt(a);c=!(k=yield R.next()).done;c=!1)e._handleIncoming(k.value)}catch(U){m=!0,T=U}finally{try{c&&null!=R.return&&(yield R.return())}finally{if(m)throw T}}});return function(a){return o.apply(this,arguments)}}()),e._source.end()}catch(o){so("error in sink",o),e._source.end(o)}});return function(s){return r.apply(this,arguments)}}()}_createSource(){const t=function S5(n={}){return t2(t=>{let r;const i=[];for(;!t.isEmpty()&&(r=t.shift(),null!=r);){if(null!=r.error)throw r.error;!1===r.done&&i.push(r.value)}return null==r?{done:!0}:{done:!0===r.done,value:i}},n)}({objectMode:!0,onEnd:r=>{this.close(r)}});return Object.assign(function j7(n){return Wv.apply(this,arguments)}(t),{push:t.push,end:t.end,return:t.return})}_handleIncoming(e){const{id:t,type:r}=e;if(so.enabled&&so.trace("incoming message",eA(e)),e.type===Jt.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024))return so.error("Too many inbound streams open"),void this._source.push({id:t,type:Jt.RESET_RECEIVER});const a=this._newReceiverStream({id:t,name:Mt(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(a))}const s=(1==(1&r)?this._streams.initiators:this._streams.receivers).get(t);if(null==s)return void so("missing stream %s",t);const o=this._init.maxStreamBufferSize??4194304;switch(r){case Jt.MESSAGE_INITIATOR:case Jt.MESSAGE_RECEIVER:if(s.source.readableLength>o){this._source.push({id:e.id,type:r===Jt.MESSAGE_INITIATOR?Jt.RESET_RECEIVER:Jt.RESET_INITIATOR});const a=se(new Error("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers"),"ERR_STREAM_INPUT_BUFFER_FULL");return void s.abort(a)}s.source.push(e.data.subarray());break;case Jt.CLOSE_INITIATOR:case Jt.CLOSE_RECEIVER:s.closeRead();break;case Jt.RESET_INITIATOR:case Jt.RESET_RECEIVER:s.reset();break;default:so("unknown message type %s",r)}}}class r9{constructor(e={}){this.protocol="/mplex/6.7.0",this.components=new ko,this._init=e}init(e){this.components=e}createStreamMuxer(e={}){return new n9(this.components,{...e,...this._init})}}const i9=WebSocket;var s9=N(3676);function tA(n){return n instanceof ArrayBuffer||"ArrayBuffer"===n?.constructor?.name&&"number"==typeof n?.byteLength}const o9=n=>{n.binaryType="arraybuffer";const e=function(){var s=V(function*(){return yield new Promise((o,a)=>{if(r)return o();if(null!=i)return a(i);const c=R=>{n.removeEventListener("open",m),n.removeEventListener("error",T),R()},m=()=>c(o),T=R=>{c(()=>a(R.error??new Error(`connect ECONNREFUSED ${n.url}`)))};n.addEventListener("open",m),n.addEventListener("error",T)})});return function(){return s.apply(this,arguments)}}(),t=un(function*(){const s=new s9.zN(({push:R,stop:k,fail:U})=>{const Q=ae=>{let he=null;"string"==typeof ae.data&&(he=_t(ae.data)),tA(ae.data)&&(he=new Uint8Array(ae.data)),ae.data instanceof Uint8Array&&(he=ae.data),null!=he&&R(he)},X=ae=>U(ae.error??new Error("Socket error"));return n.addEventListener("message",Q),n.addEventListener("error",X),n.addEventListener("close",k),()=>{n.removeEventListener("message",Q),n.removeEventListener("error",X),n.removeEventListener("close",k)}},{highWaterMark:1/0});yield ct(e());var c,o=!1,a=!1;try{for(var T,m=Tt(s);o=!(T=yield ct(m.next())).done;o=!1){const R=T.value;yield tA(R)?new Uint8Array(R):R}}catch(R){a=!0,c=R}finally{try{o&&null!=m.return&&(yield ct(m.return()))}finally{if(a)throw c}}})();let i,r=1===n.readyState;return n.addEventListener("open",()=>{r=!0,i=null}),n.addEventListener("close",()=>{r=!1,i=null}),n.addEventListener("error",s=>{r||(i=s.error??new Error(`connect ECONNREFUSED ${n.url}`))}),Object.assign(t,{connected:e})},a9=n=>{if(n.readyState>=2)throw new Error("socket closed");if(1!==n.readyState)return new Promise((e,t)=>{function r(){n.removeEventListener("open",i),n.removeEventListener("error",s)}function i(){r(),e()}function s(o){r(),t(o.error??new Error(`connect ECONNREFUSED ${n.url}`))}n.addEventListener("open",i),n.addEventListener("error",s)})},c9=(n,e)=>((e=e??{}).closeOnEnd=!1!==e.closeOnEnd,function(){var r=V(function*(i){var a,s=!1,o=!1;try{for(var m,c=Tt(i);s=!(m=yield c.next()).done;s=!1){const T=m.value;try{yield a9(n)}catch(R){if("socket closed"===R.message)break;throw R}n.send(T)}}catch(T){o=!0,a=T}finally{try{s&&null!=c.return&&(yield c.return())}finally{if(o)throw a}}if(null!=e.closeOnEnd&&n.readyState<=1)return yield new Promise((T,R)=>{n.addEventListener("close",k=>{if(k.wasClean||1006===k.code)T();else{const U=Object.assign(new Error("ws error"),{event:k});R(U)}}),setTimeout(()=>n.close())})});return function(s){return r.apply(this,arguments)}}()),u9=(n,e)=>{e=e??{};const t=o9(n);let r=e.remoteAddress,i=e.remotePort;if(null!=n.url)try{const o=new URL(n.url);r=o.hostname,i=parseInt(o.port,10)}catch{}if(null==r||null==i)throw new Error("Remote connection did not have address and/or port");return{sink:c9(n,e),source:t,connected:(o=V(function*(){return yield t.connected()}),function(){return o.apply(this,arguments)}),close:function(){var o=V(function*(){(n.readyState===n.CONNECTING||n.readyState===n.OPEN)&&(yield new Promise(a=>{n.addEventListener("close",()=>{a()}),n.close()}))});return function(){return o.apply(this,arguments)}}(),destroy:()=>{null!=n.terminate?n.terminate():n.close()},remoteAddress:r,remotePort:i,socket:n};var o};var l9=N(8596);const f9={http:"ws",https:"wss"};const nA="[a-fA-F\\d:]",ya=n=>n&&n.includeBoundaries?`(?:(?<=\\s|^)(?=${nA})|(?<=${nA})(?=\\s|$))`:"",Vs="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Pr="[a-fA-F\\d]{1,4}",sp=`\n(?:\n(?:${Pr}:){7}(?:${Pr}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${Pr}:){6}(?:${Vs}|:${Pr}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${Pr}:){5}(?::${Vs}|(?::${Pr}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${Pr}:){4}(?:(?::${Pr}){0,1}:${Vs}|(?::${Pr}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${Pr}:){3}(?:(?::${Pr}){0,2}:${Vs}|(?::${Pr}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${Pr}:){2}(?:(?::${Pr}){0,3}:${Vs}|(?::${Pr}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${Pr}:){1}(?:(?::${Pr}){0,4}:${Vs}|(?::${Pr}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${Pr}){0,5}:${Vs}|(?::${Pr}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),g9=new RegExp(`(?:^${Vs}$)|(?:^${sp}$)`),y9=new RegExp(`^${Vs}$`),m9=new RegExp(`^${sp}$`),Yv=n=>n&&n.exact?g9:new RegExp(`(?:${ya(n)}${Vs}${ya(n)})|(?:${ya(n)}${sp}${ya(n)})`,"g");Yv.v4=n=>n&&n.exact?y9:new RegExp(`${ya(n)}${Vs}${ya(n)}`,"g"),Yv.v6=n=>n&&n.exact?m9:new RegExp(`${ya(n)}${sp}${ya(n)}`,"g");const Zv=Yv,{toString:w9}=Object.prototype,rA={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Xv(n,e,{}={}){try{return function v9(n){const e=(...t)=>n(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${n.name||""})`,configurable:!0}),e}(()=>function _9(n,e={}){if(!function b9(n){return"[object RegExp]"===w9.call(n)}(n))throw new TypeError("Expected a RegExp instance");const t=Object.keys(rA).map(i=>("boolean"==typeof e[i]?e[i]:n[i])?rA[i]:"").join(""),r=new RegExp(e.source||n.source,t);return r.lastIndex="number"==typeof e.lastIndex?e.lastIndex:n.lastIndex,r}(n).test(e))()}catch(r){throw r}}const Jv={timeout:400};function eE(n){return Xv(Zv({exact:!0}),n.slice(0,45),Jv)}const aA=function S9(n){return Xv(Zv.v4({exact:!0}),n.slice(0,15),Jv)},I9=function oA(n){return Xv(Zv.v6({exact:!0}),n.slice(0,45),Jv)},cA=function(n){let t,e=0;if(aA(n))t=new Uint8Array(e+4),n.split(/\./g).forEach(r=>{t[e++]=255&parseInt(r,10)});else if(I9(n)){const r=n.split(":",8);let i;for(i=0;i0;i--)s.push("0");r.splice.apply(r,s)}for(t=new Uint8Array(e+16),i=0;i>8&255,t[e++]=255&s}}if(null==t)throw Error("Invalid ip address: "+n);return t},Hs=-1,op={},tE={};function Nr(n){if("number"==typeof n){if(null!=tE[n])return tE[n];throw new Error(`no protocol with code: ${n}`)}if("string"==typeof n){if(null!=op[n])return op[n];throw new Error(`no protocol with name: ${n}`)}throw new Error("invalid protocol id type: "+typeof n)}function uA(n,e){switch(Nr(n).code){case 4:case 41:return function x9(n){const e=function(n,e,t){e=~~e,t=t??n.length-e;const r=[];let i="";const s=new DataView(n.buffer);if(4===t){for(let o=0;o65536)throw new Error("Port number is not in range(1, 65536)");const i=rE(r);return or([t,i],t.length+i.length)}(e);case 445:return function B9(n){const e=n.split(":");if(2!==e.length)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(56!==e[0].length)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);const t=Ro.decode(`b${e[0]}`),r=parseInt(e[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const i=rE(r);return or([t,i],t.length+i.length)}(e);case 466:return function M9(n){const e=A9.decode(n),t=Uint8Array.from(Vn.encode(e.length));return or([t,e],t.length+e.length)}(e);default:return _t(e,"base16")}}[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Hs,"ip6zone"],[53,Hs,"dns",!0],[54,Hs,"dns4",!0],[55,Hs,"dns6",!0],[56,Hs,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,Hs,"unix",!1,!0],[421,Hs,"ipfs"],[421,Hs,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Hs,"garlic64"],[460,0,"quic"],[466,Hs,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,Hs,"memory"]].forEach(n=>{const e=function T9(n,e,t,r,i){return{code:n,size:e,name:t,resolvable:Boolean(r),path:Boolean(i)}}(...n);tE[e.code]=e,op[e.name]=e});const nE=Object.values(Jl).map(n=>n.decoder),A9=function(){let n=nE[0].or(nE[1]);return nE.slice(2).forEach(e=>n=n.or(e)),n}();function rE(n){const e=new ArrayBuffer(2);return new DataView(e).setUint16(0,n),new Uint8Array(e)}function dA(n){return new DataView(n.buffer).getUint16(n.byteOffset)}function pA(n){return n.map(e=>{const t=cp(e);return null!=e[1]?[t.code,uA(t.code,e[1])]:[t.code]})}function gA(n){return sE(or(n.map(e=>{const t=cp(e);let r=Uint8Array.from(Vn.encode(t.code));return e.length>1&&null!=e[1]&&(r=or([r,e[1]])),r})))}function yA(n,e){return n.size>0?n.size/8:0===n.size?0:Vn.decode(e)+Vn.decode.bytes}function ap(n){const e=[];let t=0;for(;tn.length)throw vA("Invalid address Uint8Array: "+Mt(n,"base16"));e.push([r,a])}return e}function iE(n){return function U9(n){const e=[];return n.map(t=>{const r=cp(t);return e.push(r.name),t.length>1&&null!=t[1]&&e.push(t[1]),null}),oE(e.join("/"))}(pA(ap(n)))}function sE(n){const e=function mA(n){try{ap(n)}catch(e){return e}}(n);if(null!=e)throw e;return Uint8Array.from(n)}function oE(n){return"/"+n.trim().split("/").filter(e=>e).join("/")}function vA(n){return new Error("Error parsing address: "+n)}function cp(n){return Nr(n[0])}const j9=Symbol.for("nodejs.util.inspect.custom"),EA=[Nr("dns").code,Nr("dns4").code,Nr("dns6").code,Nr("dnsaddr").code],$9=[Nr("p2p").code,Nr("ipfs").code],wA=new Map,bA=Symbol.for("@multiformats/js-multiaddr/multiaddr");let vn=(()=>{class n{constructor(t){if(null==t&&(t=""),Object.defineProperty(this,bA,{value:!0}),t instanceof Uint8Array)this.bytes=sE(t);else if("string"==typeof t){if(t.length>0&&"/"!==t.charAt(0))throw new Error(`multiaddr "${t}" must start with a "/"`);this.bytes=function K9(n){return function H9(n){const e=function F9(n){const e=[],t=n.split("/").slice(1);if(1===t.length&&""===t[0])return[];for(let r=0;r=t.length)throw vA("invalid address: "+n);if(!0===s.path){e.push([i,oE(t.slice(r).join("/"))]);break}e.push([i,t[r]])}else e.push([i])}return e}(n=oE(n)),t=function V9(n){return n.map(e=>{Array.isArray(e)||(e=[e]);const t=cp(e);return e.length>1?[t.code,lA(t.code,e[1])]:[t.code]})}(e);return gA(t)}(n)}(t)}else{if(!n.isMultiaddr(t))throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=sE(t.bytes)}}toString(){return iE(this.bytes)}toJSON(){return this.toString()}toOptions(){const t=this.protoCodes(),r=this.toString().split("/").slice(1);let i,s;if(r.length>2)EA.includes(t[0])&&$9.includes(t[1])?(i=Nr("tcp").name,s=443):(i=Nr(r[2]).name,s=parseInt(r[3]));else{if(!EA.includes(t[0]))throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');i=Nr("tcp").name,s=443}return{family:41===t[0]||55===t[0]?6:4,host:r[1],transport:i,port:s}}protos(){return this.protoCodes().map(t=>Object.assign({},Nr(t)))}protoCodes(){const t=[],r=this.bytes;let i=0;for(;it.name)}tuples(){return ap(this.bytes)}stringTuples(){return pA(ap(this.bytes))}encapsulate(t){return t=new n(t),new n(this.toString()+t.toString())}decapsulate(t){const r=t.toString(),i=this.toString(),s=i.lastIndexOf(r);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new n(i.slice(0,s))}decapsulateCode(t){const r=this.tuples();for(let i=r.length-1;i>=0;i--)if(r[i][0]===t)return new n(gA(r.slice(0,i)));return this}getPeerId(){try{const r=this.stringTuples().filter(i=>i[0]===op.ipfs.code).pop();if(null!=r?.[1]){const i=r[1];return Mt("Q"===i[0]||"1"===i[0]?Ci.decode(`z${i}`):Rr.parse(i).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){let t=null;try{t=this.stringTuples().filter(r=>!0===Nr(r[0]).path)[0][1],null==t&&(t=null)}catch{t=null}return t}equals(t){return $r(this.bytes,t.bytes)}resolve(t){var r=this;return V(function*(){const i=r.protos().find(a=>a.resolvable);if(null==i)return[r];const s=wA.get(i.name);if(null==s)throw se(new Error(`no available resolver for ${i.name}`),"ERR_NO_AVAILABLE_RESOLVER");return(yield s(r,t)).map(a=>new n(a))})()}nodeAddress(){const t=this.toOptions();if("tcp"!==t.transport&&"udp"!==t.transport)throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){const r=(t??this).protos();return!(2!==r.length||4!==r[0].code&&41!==r[0].code||6!==r[1].code&&273!==r[1].code)}static fromNodeAddress(t,r){if(null==t)throw new Error("requires node address object");if(null==r)throw new Error("requires transport protocol");let i;switch(t.family){case 4:i="ip4";break;case 6:i="ip6";break;default:throw Error("Invalid addr family, should be 4 or 6.")}return new n("/"+[i,t.address,r,t.port].join("/"))}static isName(t){return!!n.isMultiaddr(t)&&t.protos().some(r=>r.resolvable)}static isMultiaddr(t){return Boolean(t?.[bA])}[j9](){return""}inspect(){return""}}return n.resolvers=wA,n})();const up=(n,e)=>e,W9={ip4:up,ip6:(n,e,t,r)=>1===r.length&&"ip6"===r[0].protocol?e:`[${e}]`,tcp:(n,e,t,r,i)=>r.some(s=>["http","https","ws","wss"].includes(s.protocol))?`${n}:${e}`:((n,e,t,r)=>{if(null!=r&&!1===r.assumeHttp)return`tcp://${n}:${e}`;let i="tcp",s=`:${e}`;return"tcp"===t[t.length-1].protocol&&(i="443"===e?"https":"http",s="443"===e||"80"===e?"":s),`${i}://${n}${s}`})(n,e,r,i),udp:(n,e)=>`udp://${n}:${e}`,dnsaddr:up,dns4:up,dns6:up,ipfs:(n,e)=>`${n}/ipfs/${e}`,p2p:(n,e)=>`${n}/p2p/${e}`,http:n=>`http://${n}`,https:n=>`https://${n}`,ws:n=>`ws://${n}`,wss:n=>`wss://${n}`,"p2p-websocket-star":n=>`${n}/p2p-websocket-star`,"p2p-webrtc-star":n=>`${n}/p2p-webrtc-star`,"p2p-webrtc-direct":n=>`${n}/p2p-webrtc-direct`};class Nu extends Error{constructor(e="The operation was aborted"){super(e),this.code=Nu.code,this.type=Nu.type}static get code(){return"ABORT_ERR"}static get type(){return"aborted"}}var Q9=N(9456);const aE="object"==typeof window&&"object"==typeof document&&9===document.nodeType,lp=Q9(),fp=aE&&!lp,Y9=lp&&!aE,Z9=lp&&aE,X9=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&"node"===globalThis.process.release.name&&!lp,_A="function"==typeof importScripts&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,J9=(typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis,typeof navigator<"u"&&"ReactNative"===navigator.product);class iH extends Error{constructor(e){super(e),this.name="TimeoutError"}}class sH extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const IA=n=>void 0===globalThis.DOMException?new sH(n):new DOMException(n),CA=n=>{const e=void 0===n.reason?IA("This operation was aborted."):n.reason;return e instanceof Error?e:IA(e)},TA=Gt("libp2p:websockets:socket");const cH=At("dns4"),uH=At("dns6"),lH=At("dnsaddr"),Ja=pi(At("dns"),lH,cH,uH),dp=pi(At("ip4"),At("ip6")),wf=pi(en(dp,At("tcp")),en(Ja,At("tcp"))),AA=en(dp,At("udp")),fH=en(AA,At("utp")),dH=en(AA,At("quic")),Mu=pi(en(wf,At("ws")),en(Ja,At("ws"))),ec=pi(en(wf,At("wss")),en(Ja,At("wss"))),cE=pi(en(wf,At("http")),en(dp,At("http")),en(Ja,At("http"))),uE=pi(en(wf,At("https")),en(dp,At("https")),en(Ja,At("https"))),xA=pi(en(Mu,At("p2p-webrtc-star"),At("p2p")),en(ec,At("p2p-webrtc-star"),At("p2p")),en(Mu,At("p2p-webrtc-star")),en(ec,At("p2p-webrtc-star"))),RA=(pi(en(Mu,At("p2p-websocket-star"),At("p2p")),en(ec,At("p2p-websocket-star"),At("p2p")),en(Mu,At("p2p-websocket-star")),en(ec,At("p2p-websocket-star"))),pi(en(cE,At("p2p-webrtc-direct"),At("p2p")),en(uE,At("p2p-webrtc-direct"),At("p2p")),en(cE,At("p2p-webrtc-direct")),en(uE,At("p2p-webrtc-direct")))),bf=pi(Mu,ec,cE,uE,xA,RA,wf,fH,dH,Ja),ma=(pi(en(bf,At("p2p-stardust"),At("p2p")),en(bf,At("p2p-stardust"))),pi(en(bf,At("p2p")),xA,RA,At("p2p"))),PA=pi(en(ma,At("p2p-circuit"),ma),en(ma,At("p2p-circuit")),en(At("p2p-circuit"),ma),en(bf,At("p2p-circuit")),en(At("p2p-circuit"),bf),At("p2p-circuit")),NA=()=>pi(en(PA,NA),PA),Ou=NA();function MA(n){return function e(t){let r;try{r=new vn(t)}catch{return!1}const i=n(r.protoNames());return null!==i&&(!0===i||!1===i?i:0===i.length)}}function en(...n){function e(t){if(t.length(r="function"==typeof i?i().partialMatch(t):i.partialMatch(t),Array.isArray(r)&&(t=r),null===r)),r}return{toString:function(){return"{ "+n.join(" ")+" }"},input:n,matches:MA(e),partialMatch:e}}function pi(...n){function e(r){let i=null;return n.some(s=>{const o="function"==typeof s?s().partialMatch(r):s.partialMatch(r);return null!=o&&(i=o,!0)}),i}return{toString:function(){return"{ "+n.join(" ")+" }"},input:n,matches:MA(e),partialMatch:e}}function At(n){const e=n;return{toString:function(){return e},matches:function t(i){let s;try{s=new vn(i)}catch{return!1}const o=s.protoNames();return 1===o.length&&o[0]===e},partialMatch:function r(i){return 0===i.length?null:i[0]===e?i.slice(1):null}}}function OA(n){return n.filter(e=>{if(e.protoCodes().includes(290))return!1;const t=e.decapsulateCode(421);return Mu.matches(t)||ec.matches(t)})}pi(en(Ou,ma,Ou),en(ma,Ou),en(Ou,ma),Ou,ma);const lE=Symbol.for("@libp2p/transport"),va=Gt("libp2p:websockets");class pH{constructor(e){this.init=e}get[Symbol.toStringTag](){return"@libp2p/websockets"}get[lE](){return!0}dial(e,t){var r=this;return V(function*(){va("dialing %s",e),t=t??{};const s=function aH(n,e,t){const r={sink:i=>V(function*(){null!=t?.signal&&(i=Fs(i,t.signal));try{yield n.sink(i)}catch(s){"aborted"!==s.type&&TA.error(s)}})(),source:null!=(t=t??{}).signal?Fs(n.source,t.signal):n.source,remoteAddr:e,timeline:{open:Date.now()},close:()=>V(function*(){const i=Date.now();try{yield function oH(n,e){const{milliseconds:t,fallback:r,message:i,customTimers:s={setTimeout,clearTimeout}}=e;let o;const a=new Promise((c,m)=>{if("number"!=typeof t||1!==Math.sign(t))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t!==Number.POSITIVE_INFINITY){if(e.signal){const{signal:T}=e;T.aborted&&m(CA(T)),T.addEventListener("abort",()=>{m(CA(T))})}o=s.setTimeout.call(void 0,()=>{if(r){try{c(r())}catch(k){m(k)}return}const R=i instanceof Error?i:new iH("string"==typeof i?i:`Promise timed out after ${t} milliseconds`);"function"==typeof n.cancel&&n.cancel(),m(R)},t),V(function*(){try{c(yield n)}catch(T){m(T)}finally{s.clearTimeout.call(void 0,o)}})()}else c(n)});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}(n.close(),{milliseconds:2e3})}catch{const{host:o,port:a}=r.remoteAddr.toOptions();TA("timeout closing stream to %s:%s after %dms, destroying it manually",o,a,Date.now()-i),n.destroy()}finally{r.timeline.close=Date.now()}})()};return null!=n.socket.once&&n.socket.once("close",()=>{null==r.timeline.close&&(r.timeline.close=Date.now())}),r}(yield r._connect(e,t),e);va("new outbound connection %s",s.remoteAddr);const o=yield t.upgrader.upgradeOutbound(s);return va("outbound connection %s upgraded",s.remoteAddr),o})()}_connect(e,t){var r=this;return V(function*(){if(!0===t?.signal?.aborted)throw new Nu;const i=e.toOptions();va("dialing %s:%s",i.host,i.port);const s=pm(),o=T=>{va.error("connection error:",T),s.reject(T)},a=function p9(n,e){e=e??{};const r=((n,e)=>(0,l9.relative)(n,e,f9,"ws"))(n,(typeof window>"u"?"":window.location).toString()),i=new i9(r,e.websocket);return u9(i,e)}(function q9(n,e){const t=new vn(n),r=n.toString().split("/").slice(1);return t.tuples().map(i=>({protocol:r.shift()??"",content:null!=i[1]?r.shift()??"":""})).reduce((i,s,o,a)=>{const c=W9[s.protocol];if(null==c)throw new Error(`Unsupported protocol ${s.protocol}`);return c(i,s.content,o,a,e)},"")}(e),r.init);if(null!=a.socket.on?a.socket.on("error",o):a.socket.onerror=o,null==t.signal)return yield Promise.race([a.connected(),s.promise]),va("connected %s",e),a;let c;const m=new Promise((T,R)=>{if(c=()=>{R(new Nu),setTimeout(()=>{a.close().catch(k=>{va.error("error closing raw socket",k)})})},!0===t?.signal?.aborted)return c();t?.signal?.addEventListener("abort",c)});try{yield Promise.race([m,s.promise,a.connected()])}finally{null!=c&&t?.signal?.removeEventListener("abort",c)}return va("connected %s",e),a})()}createListener(e){return function eH(){throw new Error("WebSocket Servers can not be created in the browser!")}()}filter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):fp||_A?function hH(n){return n.filter(e=>{if(e.protoCodes().includes(290))return!1;const t=e.decapsulateCode(421);return ec.matches(t)&&Ja.matches(t.decapsulateCode(6).decapsulateCode(478))})}(e):OA(e)}}var Bo,tc=function(n,e,t,r){if("a"===t&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===t?r:"a"===t?r.call(n):r?r.value:e.get(n)};class ki extends EventTarget{constructor(){super(...arguments),Bo.set(this,new Map)}listenerCount(e){const t=tc(this,Bo,"f").get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let i=tc(this,Bo,"f").get(e);null==i&&(i=[],tc(this,Bo,"f").set(e,i)),i.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let i=tc(this,Bo,"f").get(e);null!=i&&(i=i.filter(({callback:s})=>s!==t),tc(this,Bo,"f").set(e,i))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=tc(this,Bo,"f").get(e.type);return null==r||(r=r.filter(({once:i})=>!i),tc(this,Bo,"f").set(e.type,r)),t}}Bo=new WeakMap;class gH extends Event{constructor(e,t){super(e,t),this.detail=t?.detail}}const rn=globalThis.CustomEvent??gH;var Ea=N(5357);const LA=(n,e)=>un(function*(){const t=yield ct(Ea(n));yield*jr(Tt(t.sort(e)),ct)})();var wa=N(7414),Ks=N(6225),kA=N(0);const Fo="/",BA=(new TextEncoder).encode(Fo),hp=BA[0];class Xr{constructor(e,t){if("string"==typeof e)this._buf=_t(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==hp)throw new Error("Invalid key")}toString(e="utf8"){return Mt(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Xr(e.join(Fo))}static random(){return new Xr(((n=21)=>crypto.getRandomValues(new Uint8Array(n)).reduce((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""))().replace(/-/g,""))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Xr(e):"function"==typeof e.uint8Array?new Xr(e.uint8Array()):null}clean(){if((null==this._buf||0===this._buf.byteLength)&&(this._buf=BA),this._buf[0]!==hp){const e=new Uint8Array(this._buf.byteLength+1);e.fill(hp,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===hp;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let i=0;io)return!1}return t.lengtht.namespaces()))])}}function _H(n){return[].concat(...n)}class SH extends class yH{open(){return Promise.reject(new Error(".open is not implemented"))}close(){return Promise.reject(new Error(".close is not implemented"))}put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}putMany(e,t={}){var r=this;return un(function*(){var o,i=!1,s=!1;try{for(var c,a=Tt(e);i=!(c=yield ct(a.next())).done;i=!1){const{key:m,value:T}=c.value;yield ct(r.put(m,T,t)),yield{key:m,value:T}}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield ct(a.return()))}finally{if(s)throw o}}})()}getMany(e,t={}){var r=this;return un(function*(){var o,i=!1,s=!1;try{for(var c,a=Tt(e);i=!(c=yield ct(a.next())).done;i=!1){const m=c.value;yield r.get(m,t)}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield ct(a.return()))}finally{if(s)throw o}}})()}deleteMany(e,t={}){var r=this;return un(function*(){var o,i=!1,s=!1;try{for(var c,a=Tt(e);i=!(c=yield ct(a.next())).done;i=!1){const m=c.value;yield ct(r.delete(m,t)),yield m}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield ct(a.return()))}finally{if(s)throw o}}})()}batch(){var e=this;let t=[],r=[];return{put(i,s){t.push({key:i,value:s})},delete(i){r.push(i)},commit:(i=V(function*(s){yield wa(e.putMany(t,s)),t=[],yield wa(e.deleteMany(r,s)),r=[]}),function(o){return i.apply(this,arguments)})};var i}_all(e,t){return un(function*(){throw new Error("._all is not implemented")})()}_allKeys(e,t){return un(function*(){throw new Error("._allKeys is not implemented")})()}query(e,t){let r=this._all(e,t);if(null!=e.prefix&&(r=Ks(r,i=>i.key.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(r=e.filters.reduce((i,s)=>Ks(i,s),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((i,s)=>LA(i,s),r)),null!=e.offset){let i=0;r=Ks(r,()=>i++>=e.offset)}return null!=e.limit&&(r=kA(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix&&(r=Ks(r,i=>i.toString().startsWith(e.prefix))),Array.isArray(e.filters)&&(r=e.filters.reduce((i,s)=>Ks(i,s),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((i,s)=>LA(i,s),r)),null!=e.offset){let i=0;r=Ks(r,()=>i++>=e.offset)}return null!=e.limit&&(r=kA(r,e.limit)),r}}{constructor(){super(),this.data={}}open(){return Promise.resolve()}close(){return Promise.resolve()}put(e,t){var r=this;return V(function*(){r.data[e.toString()]=t})()}get(e){var t=this;return V(function*(){if(!(yield t.has(e)))throw function DH(n){return n=n||new Error("Not Found"),se(n,"ERR_NOT_FOUND")}();return t.data[e.toString()]})()}has(e){var t=this;return V(function*(){return void 0!==t.data[e.toString()]})()}delete(e){var t=this;return V(function*(){delete t.data[e.toString()]})()}_all(){var e=this;return un(function*(){yield*jr(Tt(Object.entries(e.data).map(([t,r])=>({key:new Xr(t),value:r}))),ct)})()}_allKeys(){var e=this;return un(function*(){yield*jr(Tt(Object.entries(e.data).map(([t])=>new Xr(t))),ct)})()}}var Cn=(()=>(function(n){n.NOT_STARTED_YET="The libp2p node is not started yet",n.DHT_DISABLED="DHT is not available",n.PUBSUB_DISABLED="PubSub is not available",n.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",n.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",n.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",n.NOT_FOUND="Not found"}(Cn||(Cn={})),Cn))(),Ie=(()=>(function(n){n.DHT_DISABLED="ERR_DHT_DISABLED",n.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",n.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",n.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",n.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",n.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",n.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",n.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",n.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",n.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",n.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",n.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",n.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",n.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",n.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",n.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",n.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",n.ERR_DIALED_SELF="ERR_DIALED_SELF",n.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",n.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",n.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",n.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",n.ERR_INVALID_KEY="ERR_INVALID_KEY",n.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",n.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",n.ERR_INVALID_PEER="ERR_INVALID_PEER",n.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",n.ERR_NOT_FOUND="ERR_NOT_FOUND",n.ERR_TIMEOUT="ERR_TIMEOUT",n.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",n.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",n.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",n.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",n.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",n.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",n.ERR_FIND_SELF="ERR_FIND_SELF",n.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",n.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",n.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",n.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",n.ERR_INVALID_CMS="ERR_INVALID_CMS",n.ERR_MISSING_KEYS="ERR_MISSING_KEYS",n.ERR_NO_KEY="ERR_NO_KEY",n.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",n.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",n.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",n.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",n.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",n.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",n.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",n.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",n.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",n.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",n.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",n.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",n.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",n.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",n.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",n.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",n.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",n.ERR_INVALID_RECORD="ERR_INVALID_RECORD",n.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",n.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",n.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",n.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS"}(Ie||(Ie={})),Ie))(),fE=N(6930);function dE(n,e){return hE.apply(this,arguments)}function hE(){return hE=un(function*(n,e){yield*jr(Tt(fE(n,function(){var t=V(function*(r){return yield e.addressBook.add(r.id,r.multiaddrs),r});return function(r){return t.apply(this,arguments)}}())),ct)}),hE.apply(this,arguments)}function FA(n){const e=new Set;return Ks(n,t=>!e.has(t.id.toString())&&(e.add(t.id.toString()),!0))}function UA(n){return pE.apply(this,arguments)}function pE(){return pE=un(function*(n,e=1){let t=0;var s,r=!1,i=!1;try{for(var a,o=Tt(n);r=!(a=yield ct(o.next())).done;r=!1){const c=a.value;t++,yield c}}catch(c){i=!0,s=c}finally{try{r&&null!=o.return&&(yield ct(o.return()))}finally{if(i)throw s}}if(tun(function*(){try{yield yield ct(s.findPeer(e,t))}catch(o){VA.error(o)}})())),s=>Ks(s,Boolean),s=>dE(s,r.components.getPeerStore()),function(){var s=V(function*(o){return yield nc(o)});return function(o){return s.apply(this,arguments)}}());if(null!=i)return i;throw se(new Error(Cn.NOT_FOUND),Ie.ERR_NOT_FOUND)})()}getClosestPeers(e,t){var r=this;return un(function*(){if(0===r.routers.length)throw se(new Error("No peer routers available"),Ie.ERR_NO_ROUTERS_AVAILABLE);yield*jr(Tt(Ln(xh(...r.routers.map(i=>i.getClosestPeers(e,t))),i=>dE(i,r.components.getPeerStore()),i=>FA(i),i=>UA(i))),ct)})()}}class CH{constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}start(){var e=this;return V(function*(){e.started=!0})()}stop(){var e=this;return V(function*(){e.started=!1})()}findProviders(e,t={}){var r=this;return un(function*(){if(0===r.routers.length)throw se(new Error("No content this.routers available"),Ie.ERR_NO_ROUTERS_AVAILABLE);yield*jr(Tt(Ln(xh(...r.routers.map(i=>i.findProviders(e,t))),i=>dE(i,r.components.getPeerStore()),i=>FA(i),i=>UA(i))),ct)})()}provide(e,t={}){var r=this;return V(function*(){if(0===r.routers.length)throw se(new Error("No content routers available"),Ie.ERR_NO_ROUTERS_AVAILABLE);yield Promise.all(r.routers.map(function(){var i=V(function*(s){return yield s.provide(e,t)});return function(s){return i.apply(this,arguments)}}()))})()}put(e,t,r){var i=this;return V(function*(){if(!i.isStarted())throw se(new Error(Cn.NOT_STARTED_YET),Ie.DHT_NOT_STARTED);const s=i.components.getDHT();null!=s&&(yield wa(s.put(e,t,r)))})()}get(e,t){var r=this;return V(function*(){if(!r.isStarted())throw se(new Error(Cn.NOT_STARTED_YET),Ie.DHT_NOT_STARTED);const i=r.components.getDHT();if(null!=i){var a,s=!1,o=!1;try{for(var m,c=Tt(i.get(e,t));s=!(m=yield c.next()).done;s=!1){const T=m.value;if("VALUE"===T.name)return T.value}}catch(T){o=!0,a=T}finally{try{s&&null!=c.return&&(yield c.return())}finally{if(o)throw a}}}throw se(new Error(Cn.NOT_FOUND),Ie.ERR_NOT_FOUND)})()}getMany(e,t,r){var i=this;return un(function*(){if(!i.isStarted())throw se(new Error(Cn.NOT_STARTED_YET),Ie.DHT_NOT_STARTED);if(null==t||0===t)return;let s=0;const o=i.components.getDHT();if(null!=o){var m,a=!1,c=!1;try{for(var R,T=Tt(o.get(e,r));a=!(R=yield ct(T.next())).done;a=!1){const k=R.value;if("VALUE"===k.name&&(yield{from:k.from,val:k.value},s++,s===t))break}}catch(k){c=!0,m=k}finally{try{a&&null!=T.return&&(yield ct(T.return()))}finally{if(c)throw m}}}if(0===s)throw se(new Error(Cn.NOT_FOUND),Ie.ERR_NOT_FOUND)})()}}function _f(n){if(DT(n))return{id:n,multiaddrs:[],protocols:[]};let e;return"string"==typeof n&&(n=new vn(n)),vn.isMultiaddr(n)&&(e=n,n=function TH(n){const e=n.getPeerId();if(null==e)throw se(new Error(`${n.toString()} does not have a valid peer type`),Ie.ERR_INVALID_MULTIADDR);try{return _r(e)}catch{throw se(new Error(`${n.toString()} is not a valid peer type`),Ie.ERR_INVALID_MULTIADDR)}}(n)),{id:n,multiaddrs:null!=e?[e]:[],protocols:[]}}const AH=n=>n;class xH extends ki{constructor(e,t){super();const{listen:r=[],announce:i=[]}=t;this.components=e,this.listen=new Set(r.map(s=>s.toString())),this.announce=new Set(i.map(s=>s.toString())),this.observed=new Set,this.announceFilter=t.announceFilter??AH}getListenAddrs(){return Array.from(this.listen).map(e=>new vn(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>new vn(e))}getObservedAddrs(){return Array.from(this.observed).map(e=>new vn(e))}addObservedAddr(e){let t=new vn(e);const r=t.getPeerId();null!=r&&_r(r).equals(this.components.getPeerId())&&(t=t.decapsulate(new vn(`/p2p/${this.components.getPeerId().toString()}`)));const i=t.toString();this.observed.has(i)||(this.observed.add(i),this.dispatchEvent(new rn("change:addresses")))}getAddresses(){let e=this.getAnnounceAddrs().map(r=>r.toString());0===e.length&&(e=this.components.getTransportManager().getAddrs().map(r=>r.toString())),e=e.concat(this.getObservedAddrs().map(r=>r.toString()));const t=new Set(e);return this.announceFilter(Array.from(t).map(r=>new vn(r))).map(r=>r.getPeerId()===this.components.getPeerId().toString()?r:r.encapsulate(`/p2p/${this.components.getPeerId().toString()}`))}}const Df=N(7820),HA=Gt("libp2p:connection-manager:latency-monitor:visibility-change-emitter");class PH extends ki{constructor(){super(),this.hidden="hidden",this.visibilityChange="visibilityChange",null!=globalThis.document&&(this._initializeVisibilityVarNames(),this._addVisibilityChangeListener())}_initializeVisibilityVarNames(){let e="hidden",t="visibilitychange";typeof globalThis.document.hidden<"u"?(e="hidden",t="visibilitychange"):typeof globalThis.document.mozHidden<"u"?(e="mozHidden",t="mozvisibilitychange"):typeof globalThis.document.msHidden<"u"?(e="msHidden",t="msvisibilitychange"):typeof globalThis.document.webkitHidden<"u"&&(e="webkitHidden",t="webkitvisibilitychange"),this.hidden=e,this.visibilityChange=t}_addVisibilityChangeListener(){typeof globalThis.document.addEventListener>"u"||typeof document[this.hidden]>"u"?HA("Checking page visibility requires a browser that supports the Page Visibility API."):globalThis.document.addEventListener(this.visibilityChange,this._handleVisibilityChange.bind(this),!1)}isVisible(){if(void 0!==this.hidden&&void 0!==document[this.hidden])return null==document[this.hidden]}_handleVisibilityChange(){const e=!1===globalThis.document[this.hidden];HA(e?"Page Visible":"Page Hidden"),this.dispatchEvent(new rn("visibilityChange",{detail:e}))}}const Uo=Gt("libp2p:connection-manager:latency-monitor");class NH extends ki{constructor(e={}){super();const{latencyCheckIntervalMs:t,dataEmitIntervalMs:r,asyncTestFn:i,latencyRandomPercentage:s}=e;this.latencyCheckIntervalMs=t??500,this.latencyRandomPercentage=s??10,this.latencyCheckMultiply=this.latencyRandomPercentage/100*2*this.latencyCheckIntervalMs,this.latencyCheckSubtract=this.latencyCheckMultiply/2,this.dataEmitIntervalMs=null===r||0===r?void 0:r??5e3,Uo("latencyCheckIntervalMs: %s dataEmitIntervalMs: %s",this.latencyCheckIntervalMs,this.dataEmitIntervalMs),null!=this.dataEmitIntervalMs?Uo("Expecting ~%s events per summary",this.latencyCheckIntervalMs/this.dataEmitIntervalMs):Uo("Not emitting summaries"),this.asyncTestFn=i,null!=globalThis.process?.hrtime?(Uo("Using process.hrtime for timing"),this.now=globalThis.process.hrtime,this.getDeltaMS=o=>{const a=this.now(o);return 1e3*a[0]+a[1]/1e6}):typeof window<"u"&&null!=window.performance?.now?(Uo("Using performance.now for timing"),this.now=window.performance.now.bind(window.performance),this.getDeltaMS=o=>Math.round(this.now()-o)):(Uo("Using Date.now for timing"),this.now=Date.now,this.getDeltaMS=o=>this.now()-o),this.latencyData=this.initLatencyData()}start(){(function MH(){return typeof globalThis.window<"u"})()&&(this.visibilityChangeEmitter=new PH,this.visibilityChangeEmitter.addEventListener("visibilityChange",e=>{const{detail:t}=e;t?this._startTimers():(this._emitSummary(),this._stopTimers())})),!0===this.visibilityChangeEmitter?.isVisible()&&this._startTimers()}stop(){this._stopTimers()}_startTimers(){null==this.checkLatencyID&&(this.checkLatency(),null!=this.dataEmitIntervalMs&&(this.emitIntervalID=setInterval(()=>this._emitSummary(),this.dataEmitIntervalMs),"function"==typeof this.emitIntervalID.unref&&this.emitIntervalID.unref()))}_stopTimers(){null!=this.checkLatencyID&&(clearTimeout(this.checkLatencyID),this.checkLatencyID=void 0),null!=this.emitIntervalID&&(clearInterval(this.emitIntervalID),this.emitIntervalID=void 0)}_emitSummary(){const e=this.getSummary();e.events>0&&this.dispatchEvent(new rn("data",{detail:e}))}getSummary(){const e={events:this.latencyData.events,minMs:this.latencyData.minMs,maxMs:this.latencyData.maxMs,avgMs:this.latencyData.events>0?this.latencyData.totalMs/this.latencyData.events:Number.POSITIVE_INFINITY,lengthMs:this.getDeltaMS(this.latencyData.startTime)};return this.latencyData=this.initLatencyData(),Uo.trace("Summary: %O",e),e}checkLatency(){const e=Math.random()*this.latencyCheckMultiply-this.latencyCheckSubtract,t={deltaOffset:Math.ceil(this.latencyCheckIntervalMs+e),startTime:this.now()},r=()=>{if(null==this.checkLatencyID)return;const i=this.getDeltaMS(t.startTime)-t.deltaOffset;this.checkLatency(),this.latencyData.events++,this.latencyData.minMs=Math.min(this.latencyData.minMs,i),this.latencyData.maxMs=Math.max(this.latencyData.maxMs,i),this.latencyData.totalMs+=i,Uo.trace("MS: %s Data: %O",i,this.latencyData)};Uo.trace("localData: %O",t),this.checkLatencyID=setTimeout(()=>{null!=this.asyncTestFn?(t.deltaOffset=0,t.startTime=this.now(),this.asyncTestFn(r)):(t.deltaOffset-=1,r())},t.deltaOffset),"function"==typeof this.checkLatencyID.unref&&this.checkLatencyID.unref()}initLatencyData(){return{startTime:this.now(),minMs:Number.POSITIVE_INFINITY,maxMs:Number.NEGATIVE_INFINITY,events:0,totalMs:0}}}var Sf=N(2502);const jA="CLOSING",gE="CLOSED";var OH=N(8614);const $A=Gt("libp2p:dialer:dial-request");class LH{constructor(e){const{addrs:t,dialAction:r,dialer:i}=e;this.addrs=t,this.dialer=i,this.dialAction=r}run(e={}){var t=this;return V(function*(){const r=t.dialer.getTokens(t.addrs.length);if(r.length<1)throw se(new Error("No dial tokens available"),Ie.ERR_NO_DIAL_TOKENS);const i=new OH;for(const c of r)i.push(c).catch(m=>{$A.error(m)});const s=t.addrs.map(()=>{const c=new AbortController;try{(0,Jr.setMaxListeners)?.(1/0,c.signal)}catch{}return c});if(null!=e.signal)try{(0,Jr.setMaxListeners)?.(1/0,e.signal)}catch{}let o=0,a=!1;try{return yield Promise.any(t.addrs.map(function(){var c=V(function*(m,T){const R=yield i.shift();if(a)throw t.dialer.releaseToken(r.splice(r.indexOf(R),1)[0]),se(new Error("dialAction already succeeded"),Ie.ERR_ALREADY_SUCCEEDED);const k=s[T];if(null==k)throw se(new Error("dialAction did not come with an AbortController"),Ie.ERR_INVALID_PARAMETERS);let U;try{const Q=k.signal;U=yield t.dialAction(m,{...e,signal:null!=e.signal?(0,ip.anySignal)([Q,e.signal]):Q}),s[T]=void 0}finally{o++,t.addrs.length-o>=r.length?i.push(R).catch(Q=>{$A.error(Q)}):t.dialer.releaseToken(r.splice(r.indexOf(R),1)[0])}if(null==U)throw se(new Error("dialAction led to empty object"),Ie.ERR_TRANSPORT_DIAL_FAILED);return a=!0,U});return function(m,T){return c.apply(this,arguments)}}()))}finally{s.forEach(c=>{void 0!==c&&c.abort()}),r.forEach(c=>t.dialer.releaseToken(c))}})()}}var GA=N(4108);function zA(n){const{address:e}=n.nodeAddress();return Boolean(GA(e))}function yE(n,e){const t=zA(n.multiaddr),r=zA(e.multiaddr);return t&&!r?1:!t&&r||n.isCertified&&!e.isCertified?-1:!n.isCertified&&e.isCertified?1:0}var mE=N(4297);const js=Gt("libp2p:dialer"),YA="dialler";class HH{constructor(e={}){this.components=new ko,this.started=!1,this.addressSorter=e.addressSorter??yE,this.maxAddrsToDial=e.maxAddrsToDial??25,this.timeout=e.dialTimeout??3e4,this.maxDialsPerPeer=e.maxDialsPerPeer??4,this.tokens=[...new Array(e.maxParallelDials??100)].map((t,r)=>r),this.pendingDials=Ef({component:YA,metric:"pending-dials",metrics:e.metrics}),this.pendingDialTargets=Ef({component:YA,metric:"pending-dial-targets",metrics:e.metrics});for(const[t,r]of Object.entries(e.resolvers??{}))vn.resolvers.set(t,r)}init(e){this.components=e}isStarted(){return this.started}start(){var e=this;return V(function*(){e.started=!0})()}stop(){var e=this;return V(function*(){e.started=!1;for(const t of e.pendingDials.values())try{t.controller.abort()}catch(r){js.error(r)}e.pendingDials.clear();for(const t of e.pendingDialTargets.values())t.reject(new Nu("Dialer was destroyed"));e.pendingDialTargets.clear()})()}dial(e,t={}){var r=this;return V(function*(){const{id:i,multiaddrs:s}=_f(e);if(r.components.getPeerId().equals(i))throw se(new Error("Tried to dial self"),Ie.ERR_DIALED_SELF);if(js("check multiaddrs %p",i),null!=s&&s.length>0&&(js("storing multiaddrs %p",i,s),yield r.components.getPeerStore().addressBook.add(i,s)),yield r.components.getConnectionGater().denyDialPeer(i))throw se(new Error("The dial request is blocked by gater.allowDialPeer"),Ie.ERR_PEER_DIAL_INTERCEPTED);js("creating dial target for %p",i);const o=yield r._createCancellableDialTarget(i,t);if(0===o.addrs.length)throw se(new Error("The dial request has no valid addresses"),Ie.ERR_NO_VALID_ADDRESSES);const a=r.pendingDials.get(o.id)??r._createPendingDial(o,t);try{const c=yield a.promise;return js("dial succeeded to %s",o.id),c}catch(c){throw js("dial failed to %s",o.id,c),a.controller.signal.aborted&&(c.code=Ie.ERR_TIMEOUT),js.error(c),c}finally{a.destroy()}})()}_createCancellableDialTarget(e,t){var r=this;return V(function*(){const i=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,s=new Promise((o,a)=>{r.pendingDialTargets.set(i,{resolve:o,reject:a})});try{return yield Promise.race([r._createDialTarget(e,t),s])}finally{r.pendingDialTargets.delete(i)}})()}_createDialTarget(e,t){var r=this;return V(function*(){const i=yield Ln(yield r.components.getPeerStore().addressBook.get(e),a=>Ks(a,function(){var c=V(function*(m){return!(yield r.components.getConnectionGater().denyDialMultiaddr(e,m.multiaddr))});return function(m){return c.apply(this,arguments)}}()),a=>mE(a,r.addressSorter),a=>fE(a,c=>{const m=c.multiaddr;return e.toString()===m.getPeerId()?m:m.encapsulate(`/p2p/${e.toString()}`)}),function(){var a=V(function*(c){return yield Ea(c)});return function(c){return a.apply(this,arguments)}}()),s=[];for(const a of i)(yield r._resolve(a,t)).forEach(m=>s.push(m));const o=s.filter(a=>r.components.getTransportManager().transportForMultiaddr(a));if(o.length>r.maxAddrsToDial)throw yield r.components.getPeerStore().delete(e),se(new Error("dial with more addresses than allowed"),Ie.ERR_TOO_MANY_ADDRESSES);return{id:e.toString(),addrs:o}})()}_createPendingDial(e,t={}){var r=this;const i=function(){var T=V(function*(R,k={}){if(!0===k.signal?.aborted)throw se(new Error("already aborted"),Ie.ERR_ALREADY_ABORTED);return yield r.components.getTransportManager().dial(R,k).catch(U=>{throw js.error("dial to %s failed",R,U),U})});return function(k){return T.apply(this,arguments)}}(),s=new LH({addrs:e.addrs,dialAction:i,dialer:this}),o=new Bi.TimeoutController(this.timeout),a=[o.signal];null!=t.signal&&a.push(t.signal);const c=(0,ip.anySignal)(a);try{(0,Jr.setMaxListeners)?.(1/0,c)}catch{}const m={dialRequest:s,controller:o,promise:s.run({...t,signal:c}),destroy:()=>{o.clear(),this.pendingDials.delete(e.id)}};return this.pendingDials.set(e.id,m),m}getTokens(e){const t=Math.min(e,this.maxDialsPerPeer,this.tokens.length),r=this.tokens.splice(0,t);return js("%d tokens request, returning %d, %d remaining",e,t,this.tokens.length),r}releaseToken(e){this.tokens.includes(e)||(js("token %d released",e),this.tokens.push(e))}_resolve(e,t){var r=this;return V(function*(){if(!e.protoNames().includes("dnsaddr"))return[e];const s=yield r._resolveRecord(e,t);return(yield Promise.all(s.map(function(){var c=V(function*(m){return yield r._resolve(m,t)});return function(m){return c.apply(this,arguments)}}()))).flat().reduce((c,m)=>(null==c.find(T=>T.equals(m))&&c.push(m),c),[])})()}_resolveRecord(e,t){return V(function*(){try{return e=new vn(e.toString()),yield e.resolve(t)}catch(r){return js.error(`multiaddr ${e.toString()} could not be resolved`,r),[]}})()}}const gi=Gt("libp2p:connection-manager"),jH={maxConnections:1/0,minConnections:0,maxData:1/0,maxSentData:1/0,maxReceivedData:1/0,maxEventLoopDelay:1/0,pollInterval:2e3,autoDialInterval:1e4,movingAverageInterval:6e4},vE="libp2p",EE="connection-manager";class GH extends ki{constructor(e){if(super(),this.components=new ko,this.opts=Df.call({ignoreUndefined:!0},jH,e),this.opts.maxConnections{const t={inbound:0,outbound:0};for(const r of this.connections.values())for(const i of r)"inbound"===i.stat.direction?t.inbound++:t.outbound++;return t}}),this.components.getMetrics()?.updateComponentMetric({system:vE,component:EE,metric:"protocol-streams-total",label:"protocol",value:()=>{const t={};for(const r of this.connections.values())for(const i of r)for(const s of i.streams){const o=`${s.stat.direction} ${s.stat.protocol??"unnegotiated"}`;t[o]=(t[o]??0)+1}return t}}),this.components.getMetrics()?.updateComponentMetric({system:vE,component:EE,metric:"protocol-streams-per-connection-90th-percentile",label:"protocol",value:()=>{const t={};for(const i of this.connections.values())for(const s of i){const o={};for(const a of s.streams){const c=`${a.stat.direction} ${a.stat.protocol??"unnegotiated"}`;o[c]=(o[c]??0)+1}for(const[a,c]of Object.entries(o))t[a]=t[a]??[],t[a].push(c)}const r={};for(let[i,s]of Object.entries(t)){s=s.sort((a,c)=>a-c);const o=Math.floor(.9*s.length);r[i]=s[o]}return r}})}isStarted(){return this.started}start(){var e=this;return V(function*(){null!=e.components.getMetrics()&&(e.timer=e.timer??Sf(e._checkMetrics,e.opts.pollInterval)),e.latencyMonitor.start(),e._onLatencyMeasure=e._onLatencyMeasure.bind(e),e.latencyMonitor.addEventListener("data",e._onLatencyMeasure),yield e.dialer.start(),e.started=!0,gi("started")})()}afterStart(){var e=this;return V(function*(){e.components.getUpgrader().addEventListener("connection",e.onConnect),e.components.getUpgrader().addEventListener("connectionEnd",e.onDisconnect),Promise.resolve().then(V(function*(){const t=[];for(const r of yield e.components.getPeerStore().all())(yield e.components.getPeerStore().getTags(r.id)).filter(o=>"keep-alive"===o.name).length>0&&t.push(r.id);e.connectOnStartupController?.clear(),e.connectOnStartupController=new Bi.TimeoutController(e.startupReconnectTimeout);try{(0,Jr.setMaxListeners)?.(1/0,e.connectOnStartupController.signal)}catch{}yield Promise.all(t.map(function(){var r=V(function*(i){yield e.openConnection(i,{signal:e.connectOnStartupController?.signal}).catch(s=>{gi.error(s)})});return function(i){return r.apply(this,arguments)}}()))})).catch(t=>{gi.error(t)}).finally(()=>{e.connectOnStartupController?.clear()})})()}beforeStop(){var e=this;return V(function*(){e.connectOnStartupController?.abort(),e.components.getUpgrader().removeEventListener("connection",e.onConnect),e.components.getUpgrader().removeEventListener("connectionEnd",e.onDisconnect)})()}stop(){var e=this;return V(function*(){e.timer?.clear(),e.latencyMonitor.removeEventListener("data",e._onLatencyMeasure),e.latencyMonitor.stop(),yield e.dialer.stop(),e.started=!1,yield e._close(),gi("stopped")})()}_close(){var e=this;return V(function*(){const t=[];for(const r of e.connections.values())for(const i of r)t.push(V(function*(){try{yield i.close()}catch(s){gi.error(s)}})());gi("closing %d connections",t.length),yield Promise.all(t),e.connections.clear()})()}_checkMetrics(){var e=this;return V(function*(){const t=e.components.getMetrics();if(null!=t)try{const r=t.getGlobal().getMovingAverages(),i=r.dataReceived[e.opts.movingAverageInterval].movingAverage;yield e._checkMaxLimit("maxReceivedData",i);const s=r.dataSent[e.opts.movingAverageInterval].movingAverage;yield e._checkMaxLimit("maxSentData",s);const o=i+s;yield e._checkMaxLimit("maxData",o),gi.trace("metrics update",o)}finally{e.timer=Sf(e._checkMetrics,e.opts.pollInterval)}})()}onConnect(e){this._onConnect(e).catch(t=>{gi.error(t)})}_onConnect(e){var t=this;return V(function*(){const{detail:r}=e;if(!t.started)return void(yield r.close());const i=r.remotePeer,s=i.toString(),o=t.connections.get(s);null!=o?o.push(r):t.connections.set(s,[r]),null!=i.publicKey&&(yield t.components.getPeerStore().keyBook.set(i,i.publicKey));const a=t.getConnections().length,c=a-t.opts.maxConnections;yield t._checkMaxLimit("maxConnections",a,c),t.dispatchEvent(new rn("peer:connect",{detail:r}))})()}onDisconnect(e){const{detail:t}=e;if(!this.started)return;const r=t.remotePeer.toString();let i=this.connections.get(r);null!=i&&i.length>1?(i=i.filter(s=>s.id!==t.id),this.connections.set(r,i)):null!=i&&(this.connections.delete(r),this.dispatchEvent(new rn("peer:disconnect",{detail:t})),this.components.getMetrics()?.onPeerDisconnected(t.remotePeer))}getConnections(e){if(null!=e)return this.connections.get(e.toString())??[];let t=[];for(const r of this.connections.values())t=t.concat(r);return t}openConnection(e,t={}){var r=this;return V(function*(){gi("dial to %p",e);const i=r.getConnections(e);if(i.length>0)return gi("had an existing connection to %p",e),i[0];let s;if(null==t?.signal){s=new Bi.TimeoutController(r.dialTimeout),t.signal=s.signal;try{(0,Jr.setMaxListeners)?.(1/0,s.signal)}catch{}}try{const o=yield r.dialer.dial(e,t);let a=r.connections.get(e.toString());null==a&&(a=[],r.connections.set(e.toString(),a));let c=!1;for(const m of a)m.id===o.id&&(c=!0);return c||a.push(o),o}finally{s?.clear()}})()}closeConnections(e){var t=this;return V(function*(){const r=t.connections.get(e.toString())??[];yield Promise.all(r.map(function(){var i=V(function*(s){return yield s.close()});return function(s){return i.apply(this,arguments)}}()))})()}getAll(e){if(!DT(e))throw se(new Error("peerId must be an instance of peer-id"),Ie.ERR_INVALID_PARAMETERS);const t=e.toString(),r=this.connections.get(t);return null!=r?r.filter(i=>"OPEN"===i.stat.status):[]}_onLatencyMeasure(e){const{detail:t}=e;this._checkMaxLimit("maxEventLoopDelay",t.avgMs,1).catch(r=>{gi.error(r)})}_checkMaxLimit(e,t,r=1){var i=this;return V(function*(){const s=i.opts[e];gi.trace("checking limit of %s. current value: %d of %d",e,t,s),t>s&&(gi("%s: limit exceeded: %p, %d/%d, pruning %d connection(s)",i.components.getPeerId(),e,t,s,r),yield i._maybePruneConnections(r))})()}_maybePruneConnections(e){var t=this;return V(function*(){const r=t.getConnections();if(r.length<=t.opts.minConnections||e<1)return;const i=new $T;for(const a of r){const c=a.remotePeer;if(i.has(c))continue;const m=yield t.components.getPeerStore().getTags(c);i.set(c,m.reduce((T,R)=>T+R.value,0))}const s=r.sort((a,c)=>{const m=i.get(a.remotePeer)??0,T=i.get(c.remotePeer)??0;return m>T?1:m{ba.error("could start autodial",t)}),ba("started")):ba("not enabled")})()}stop(){var e=this;return V(function*(){e.options.enabled?(e.running=!1,null!=e.autoDialTimeout&&e.autoDialTimeout.clear(),ba("stopped")):ba("not enabled")})()}_autoDial(){var e=this;return V(function*(){null!=e.autoDialTimeout&&e.autoDialTimeout.clear();const t=e.options.minConnections;if(e.components.getConnectionManager().getConnections().length>=t)return void(e.autoDialTimeout=Sf(e._autoDial,e.options.autoDialInterval));const r=yield e.components.getPeerStore().all(),i=yield Ln(r.sort(()=>Math.random()>.5?1:-1),s=>Ks(s,o=>!o.id.equals(e.components.getPeerId())),s=>mE(s,(o,a)=>a.protocols.length>o.protocols.length||null!=a.id.publicKey&&null==o.id.publicKey?1:-1),function(){var s=V(function*(o){return yield Ea(o)});return function(o){return s.apply(this,arguments)}}());for(let s=0;e.running&&sNh(t)}(e=n.Status||(n.Status={})),function(a){a.HOP="HOP",a.STOP="STOP",a.STATUS="STATUS",a.CAN_HOP="CAN_HOP"}(r=n.Type||(n.Type={})),function(a){a[a.HOP=1]="HOP",a[a.STOP=2]="STOP",a[a.STATUS=3]="STATUS",a[a.CAN_HOP=4]="CAN_HOP"}(i||(i={})),function(a){a.codec=()=>Nh(i)}(r=n.Type||(n.Type={})),function(a){let c;a.codec=()=>(null==c&&(c=fi((m,T,R={})=>{if(!1!==R.lengthDelimited&&T.fork(),null==m.id)throw new Error('Protocol error: required field "id" was not found in object');if(T.uint32(10),T.bytes(m.id),null==m.addrs)throw new Error('Protocol error: required field "addrs" was not found in object');for(const k of m.addrs)T.uint32(18),T.bytes(k);!1!==R.lengthDelimited&&T.ldelim()},(m,T)=>{const R={},k=null==T?m.len:m.pos+T;for(;m.pos>>3){case 1:R.id=m.bytes();break;case 2:R.addrs=R.addrs??[],R.addrs.push(m.bytes());break;default:m.skipType(7&U)}}if(R.addrs=R.addrs??[],null==R.id)throw new Error('Protocol error: value for required field "id" was not found in protobuf');if(null==R.addrs)throw new Error('Protocol error: value for required field "addrs" was not found in protobuf');return R})),c),a.encode=m=>li(m,a.codec()),a.decode=m=>ui(m,a.codec())}(s=n.Peer||(n.Peer={})),n.codec=()=>(null==o&&(o=fi((a,c,m={})=>{!1!==m.lengthDelimited&&c.fork(),null!=a.type&&(c.uint32(8),n.Type.codec().encode(a.type,c)),null!=a.srcPeer&&(c.uint32(18),n.Peer.codec().encode(a.srcPeer,c)),null!=a.dstPeer&&(c.uint32(26),n.Peer.codec().encode(a.dstPeer,c)),null!=a.code&&(c.uint32(32),n.Status.codec().encode(a.code,c)),!1!==m.lengthDelimited&&c.ldelim()},(a,c)=>{const m={},T=null==c?a.len:a.pos+c;for(;a.pos>>3){case 1:m.type=n.Type.codec().decode(a);break;case 2:m.srcPeer=n.Peer.codec().decode(a,a.uint32());break;case 3:m.dstPeer=n.Peer.codec().decode(a,a.uint32());break;case 4:m.code=n.Status.codec().decode(a);break;default:a.skipType(7&R)}}return m})),o),n.encode=a=>li(a,n.codec()),n.decode=a=>ui(a,n.codec())}(sn||(sn={}));const qH=Gt("libp2p:stream:converter");function ZA(n,e={}){const{stream:t,remoteAddr:r}=n,{sink:i,source:s}=t,o=un(function*(){var k,T=!1,R=!1;try{for(var Q,U=Tt(s);T=!(Q=yield ct(U.next())).done;T=!1){const X=Q.value;yield*jr(Tt(X),ct)}}catch(X){R=!0,k=X}finally{try{T&&null!=U.return&&(yield ct(U.return()))}finally{if(R)throw k}}})(),a={sink:T=>V(function*(){null!=e.signal&&(T=Fs(T,e.signal));try{yield i(T),yield c()}catch(R){"aborted"!==R.type&&qH(R)}})(),source:null!=e.signal?Fs(o,e.signal):o,remoteAddr:r,timeline:{open:Date.now(),close:void 0},close:()=>V(function*(){yield i(un(function*(){yield new Uint8Array(0)})()),yield c()})()};function c(){return m.apply(this,arguments)}function m(){return(m=V(function*(){return null==a.timeline.close&&(a.timeline.close=Date.now()),yield Promise.resolve()})).apply(this,arguments)}return a}const If="/libp2p/circuit/relay/0.1.0";function XA(n,e){n.write({type:sn.Type.STATUS,code:e})}function JA(n,e){try{null!=n.dstPeer?.addrs&&n.dstPeer.addrs.forEach(t=>new vn(t))}catch(t){throw XA(e,n.type===sn.Type.HOP?sn.Status.HOP_DST_MULTIADDR_INVALID:sn.Status.STOP_DST_MULTIADDR_INVALID),t}try{null!=n.srcPeer?.addrs&&n.srcPeer.addrs.forEach(t=>new vn(t))}catch(t){throw XA(e,n.type===sn.Type.HOP?sn.Status.HOP_SRC_MULTIADDR_INVALID:sn.Status.STOP_SRC_MULTIADDR_INVALID),t}}const Cf=Gt("libp2p:circuit:stream-handler");class gp{constructor(e){const{stream:t,maxLength:r=4096}=e;this.stream=t,this.shake=Ch(this.stream),this.decoder=Ms.fromReader(this.shake.reader,{maxDataLength:r})}read(){var e=this;return V(function*(){const t=yield e.decoder.next();if(null!=t.value){const r=sn.decode(t.value);return Cf("read message type",r.type),r}Cf("read received no value, closing stream"),e.close()})()}write(e){Cf("write message type %s",e.type),this.shake.write(to.single(sn.encode(e)))}rest(){return this.shake.rest(),this.shake.stream}end(e){this.write(e),this.close()}close(){Cf("closing the stream"),this.rest().sink([]).catch(e=>{Cf.error(e)})}}const Tf=Gt("libp2p:circuit:stop");function ZH(n){return wE.apply(this,arguments)}function wE(){return wE=V(function*(n){const{connection:e,request:t,signal:r}=n,i=yield e.newStream(If,{signal:r});Tf("starting stop request to %p",e.remotePeer);const s=new gp({stream:i});s.write(t);const o=yield s.read();if(null!=o)return o.code===sn.Status.SUCCESS?(Tf("stop request to %p was successful",e.remotePeer),s.rest()):(Tf("stop request failed with code %d",o.code),void s.close());s.close()}),wE.apply(this,arguments)}const ps=Gt("libp2p:circuit:hop");function bE(){return bE=V(function*(n){const{connection:e,request:t,streamHandler:r,circuit:i,connectionManager:s}=n;if(!i.hopEnabled())return ps("HOP request received but we are not acting as a relay"),r.end({type:sn.Type.STATUS,code:sn.Status.HOP_CANT_SPEAK_RELAY});try{JA(t,r)}catch(R){return void ps.error("invalid hop request via peer %p %o",e.remotePeer,R)}if(null==t.dstPeer)return void ps("HOP request received but we do not receive a dstPeer");const o=pa(t.dstPeer.id),a=s.getConnections(o);if(0===a.length&&!i.hopActive())return ps("HOP request received but we are not connected to the destination peer"),r.end({type:sn.Type.STATUS,code:sn.Status.HOP_NO_CONN_TO_DST});if(0===a.length)return ps("did not have connection to remote peer"),r.end({type:sn.Type.STATUS,code:sn.Status.HOP_NO_CONN_TO_DST});const c={type:sn.Type.STOP,dstPeer:t.dstPeer,srcPeer:t.srcPeer};let m;try{ps("performing STOP request");const R=yield ZH({connection:a[0],request:c});if(null==R)throw new Error("Could not stop");m=R}catch(R){return void ps.error(R)}ps("hop request from %p is valid",e.remotePeer),r.write({type:sn.Type.STATUS,code:sn.Status.SUCCESS});const T=r.rest();return ps("creating related connections"),yield Ln(T,m,T)}),bE.apply(this,arguments)}function _E(){return _E=V(function*(n){const{connection:e,request:t,signal:r}=n,i=yield e.newStream(If,{signal:r}),s=new gp({stream:i});s.write(t);const o=yield s.read();if(null==o)throw se(new Error("HOP request had no response"),Ie.ERR_HOP_REQUEST_FAILED);if(o.code===sn.Status.SUCCESS)return ps("hop request was successful"),s.rest();throw ps("hop request failed with code %d, closing stream",o.code),s.close(),se(new Error(`HOP request failed with code "${o.code??"unknown"}"`),Ie.ERR_HOP_REQUEST_FAILED)}),_E.apply(this,arguments)}function DE(){return DE=V(function*(n){const{connection:e,signal:t}=n,r=yield e.newStream(If,{signal:t}),i=new gp({stream:r});i.write({type:sn.Type.CAN_HOP});const s=yield i.read();return yield i.close(),!(null==s||s.code!==sn.Status.SUCCESS)}),DE.apply(this,arguments)}const gs=Gt("libp2p:circuit");class nK{constructor(e){this.components=new ko,this._init=e}init(e){this.components=e,this.components.getRegistrar().handle(If,t=>{this._onProtocol(t).catch(r=>{gs.error(r)})}).catch(t=>{gs.error(t)})}hopEnabled(){return!0}hopActive(){return!0}get[lE](){return!0}get[Symbol.toStringTag](){return"libp2p/circuit-relay-v1"}_onProtocol(e){var t=this;return V(function*(){const{connection:r,stream:i}=e,s=new Bi.TimeoutController(t._init.hop.timeout);try{(0,Jr.setMaxListeners)?.(1/0,s.signal)}catch{}try{const o=ga(i,s.signal),a=new gp({stream:{...i,...o}}),c=yield a.read();if(null==c)return gs("request was invalid, could not read from stream"),a.write({type:sn.Type.STATUS,code:sn.Status.MALFORMED_MESSAGE}),void a.close();let m;switch(c.type){case sn.Type.CAN_HOP:gs("received CAN_HOP request from %p",r.remotePeer),yield function tK(n){const{connection:e,streamHandler:t,circuit:r}=n,i=r.hopEnabled();ps("can hop (%s) request from %p",i,e.remotePeer),t.end({type:sn.Type.STATUS,code:i?sn.Status.SUCCESS:sn.Status.HOP_CANT_SPEAK_RELAY})}({circuit:t,connection:r,streamHandler:a});break;case sn.Type.HOP:gs("received HOP request from %p",r.remotePeer),yield function XH(n){return bE.apply(this,arguments)}({connection:r,request:c,streamHandler:a,circuit:t,connectionManager:t.components.getConnectionManager()});break;case sn.Type.STOP:gs("received STOP request from %p",r.remotePeer),m=yield function YH(n){const{connection:e,request:t,streamHandler:r}=n;try{JA(t,r)}catch(i){return void Tf.error("invalid stop request via peer %p %o",e.remotePeer,i)}return Tf("stop request is valid"),r.write({type:sn.Type.STATUS,code:sn.Status.SUCCESS}),r.rest()}({connection:r,request:c,streamHandler:a});break;default:return gs("Request of type %s not supported",c.type),a.write({type:sn.Type.STATUS,code:sn.Status.MALFORMED_MESSAGE}),void a.close()}if(null!=m){const k=ZA({stream:m,remoteAddr:r.remoteAddr.encapsulate("/p2p-circuit").encapsulate(new vn(c.dstPeer?.addrs[0])),localAddr:new vn(c.srcPeer?.addrs[0])}),U=c.type===sn.Type.HOP?"relay":"inbound";gs("new %s connection %s",U,k.remoteAddr);const Q=yield t.components.getUpgrader().upgradeInbound(k);gs("%s connection %s upgraded",U,k.remoteAddr),null!=t.handler&&t.handler(Q)}}finally{s.clear()}})()}dial(e,t={}){var r=this;return V(function*(){const i=e.toString().split("/p2p-circuit"),s=new vn(i[0]),o=new vn(i[i.length-1]),a=s.getPeerId(),c=o.getPeerId();if(null==a||null==c){const Q="Circuit relay dial failed as addresses did not have peer id";throw gs.error(Q),se(new Error(Q),Ie.ERR_RELAYED_DIAL)}const m=_r(a),T=_r(c);let R=!1,U=r.components.getConnectionManager().getConnections(m)[0];null==U&&(yield r.components.getPeerStore().addressBook.add(m,[s]),U=yield r.components.getConnectionManager().openConnection(m,t),R=!0);try{const Q=yield function JH(n){return _E.apply(this,arguments)}({...t,connection:U,request:{type:sn.Type.HOP,srcPeer:{id:r.components.getPeerId().toBytes(),addrs:r.components.getAddressManager().getAddresses().map(he=>he.bytes)},dstPeer:{id:T.toBytes(),addrs:[new vn(o).bytes]}}}),X=s.encapsulate(`/p2p-circuit/p2p/${r.components.getPeerId().toString()}`),ae=ZA({stream:Q,remoteAddr:e,localAddr:X});return gs("new outbound connection %s",ae.remoteAddr),yield r.components.getUpgrader().upgradeOutbound(ae)}catch(Q){throw gs.error("Circuit relay dial failed",Q),R&&(yield U.close()),Q}})()}createListener(e){return this.handler=e.handler,function QH(n){const e=new Map;function r(){return(r=V(function*(o){const a=o.toString().split("/p2p-circuit").find(U=>""!==U),c=new vn(a),m=c.getPeerId();if(null==m)throw new Error("Could not determine relay peer from multiaddr");const T=_r(m);yield n.peerStore.addressBook.add(T,[c]);const R=yield n.connectionManager.openConnection(T),k=R.remoteAddr.encapsulate("/p2p-circuit");e.set(R.remotePeer.toString(),k),s.dispatchEvent(new rn("listening"))})).apply(this,arguments)}const s=Object.assign(new ki,{close:(o=V(function*(){return yield Promise.resolve()}),function(){return o.apply(this,arguments)}),listen:function t(o){return r.apply(this,arguments)},getAddrs:function i(){const o=[];for(const a of e.values())o.push(a);return o}});var o;return n.connectionManager.addEventListener("peer:disconnect",o=>{const{detail:a}=o;e.delete(a.remotePeer.toString())&&s.dispatchEvent(new rn("close"))}),s}({connectionManager:this.components.getConnectionManager(),peerStore:this.components.getPeerStore()})}filter(e){return(e=Array.isArray(e)?e:[e]).filter(t=>Ou.matches(t))}}function ex(n){return SE.apply(this,arguments)}function SE(){return SE=V(function*(n){const e=(new TextEncoder).encode(n),t=yield Li.digest(e);return Rr.createV0(t)}),SE.apply(this,arguments)}const nx="hop_relay",ix="/libp2p/relay",Af=Gt("libp2p:auto-relay"),oK=()=>{};class aK{constructor(e,t){this.components=e,this.addressSorter=t.addressSorter??yE,this.maxListeners=t.maxListeners??1,this.listenRelays=new Set,this.onError=t.onError??oK,this._onProtocolChange=this._onProtocolChange.bind(this),this._onPeerDisconnected=this._onPeerDisconnected.bind(this),this.components.getPeerStore().addEventListener("change:protocols",r=>{this._onProtocolChange(r).catch(i=>{Af.error(i)})}),this.components.getConnectionManager().addEventListener("peer:disconnect",this._onPeerDisconnected)}_onProtocolChange(e){var t=this;return V(function*(){const{peerId:r,protocols:i}=e.detail,s=r.toString();if(null!=i.find(a=>a===If)){if(!t.listenRelays.has(s))try{const a=t.components.getConnectionManager().getConnections(r);if(0===a.length)return;const c=a[0];if(c.remoteAddr.protoCodes().includes(290))return void Af(`relayed connection to ${s} will not be used to hop on`);(yield function eK(n){return DE.apply(this,arguments)}({connection:c}))&&(yield t.components.getPeerStore().metadataBook.setValue(r,nx,_t("true")),yield t._addListenRelay(c,s))}catch(a){t.onError(a)}}else t.listenRelays.has(s)&&(yield t._removeListenRelay(s))})()}_onPeerDisconnected(e){const i=e.detail.remotePeer.toString();!this.listenRelays.has(i)||this._removeListenRelay(i).catch(s=>{Af.error(s)})}_addListenRelay(e,t){var r=this;return V(function*(){try{if(r.listenRelays.size>=r.maxListeners)return;const i=yield Ln(yield r.components.getPeerStore().addressBook.get(e.remotePeer),o=>mE(o,r.addressSorter),function(){var o=V(function*(a){return yield Ea(a)});return function(a){return o.apply(this,arguments)}}());(yield Promise.all(i.map(function(){var o=V(function*(a){try{let c=a.multiaddr;return null==c.getPeerId()&&(c=c.encapsulate(`/p2p/${e.remotePeer.toString()}`)),c=c.encapsulate("/p2p-circuit"),yield r.components.getTransportManager().listen([c]),!0}catch(c){Af.error("error listening on circuit address",c),r.onError(c)}return!1});return function(a){return o.apply(this,arguments)}}()))).includes(!0)&&r.listenRelays.add(t)}catch(i){r.onError(i),r.listenRelays.delete(t)}})()}_removeListenRelay(e){var t=this;return V(function*(){t.listenRelays.delete(e)&&(yield t._listenOnAvailableHopRelays([e]))})()}_listenOnAvailableHopRelays(e=[]){var t=this;return V(function*(){if(t.listenRelays.size>=t.maxListeners)return;const r=[],i=yield t.components.getPeerStore().all();for(const{id:T,metadata:R}of i){const k=T.toString();if(t.listenRelays.has(k)||e.includes(k))continue;const U=R.get(nx);if(null==U||"true"!==Mt(U))continue;const Q=t.components.getConnectionManager().getConnections(T);if(0!==Q.length){if(yield t._addListenRelay(Q[0],k),t.listenRelays.size>=t.maxListeners)return}else r.push(T)}for(const T of r)if(yield t._tryToListenOnRelay(T),t.listenRelays.size>=t.maxListeners)return;try{const T=yield ex(ix);var a,s=!1,o=!1;try{for(var m,c=Tt(t.components.getContentRouting().findProviders(T));s=!(m=yield c.next()).done;s=!1){const R=m.value;if(0===R.multiaddrs.length)continue;const k=R.id;if(!k.equals(t.components.getPeerId())&&(yield t.components.getPeerStore().addressBook.add(k,R.multiaddrs),yield t._tryToListenOnRelay(k),t.listenRelays.size>=t.maxListeners))return}}catch(R){o=!0,a=R}finally{try{s&&null!=c.return&&(yield c.return())}finally{if(o)throw a}}}catch(T){t.onError(T)}})()}_tryToListenOnRelay(e){var t=this;return V(function*(){try{const r=yield t.components.getConnectionManager().openConnection(e);yield t._addListenRelay(r,e.toString())}catch(r){Af.error("Could not use %p as relay",e,r),t.onError(r,`could not connect and listen on known hop relay ${e.toString()}`)}})()}}const sx=Gt("libp2p:relay");class cK{constructor(e,t){this.components=e,this.autoRelay=!1!==t.autoRelay?.enabled?new aK(e,{addressSorter:t.addressSorter,...t.autoRelay}):void 0,this.started=!1,this.init=t,this._advertiseService=this._advertiseService.bind(this)}isStarted(){return this.started}start(){var e=this;return V(function*(){!1!==e.init.hop.enabled&&!1!==e.init.advertise.enabled&&(e.timeout=(0,pp.setDelayedInterval)(e._advertiseService,e.init.advertise.ttl,e.init.advertise.bootDelay)),e.started=!0})()}stop(){var e=this;return V(function*(){null!=e.timeout&&(0,pp.clearDelayedInterval)(e.timeout),e.started=!1})()}_advertiseService(){var e=this;return V(function*(){try{const t=yield ex(ix);yield e.components.getContentRouting().provide(t)}catch(t){t.code===Ie.ERR_NO_ROUTERS_AVAILABLE?(sx.error("a content router, such as a DHT, must be provided in order to advertise the relay service",t),yield e.stop()):sx.error(t)}})()}}var uK=N(9014);N(422),N(5911);const ox=Gn.pki;function IE(){return IE=V(function*(n,e){const t=n.map(e);return n[(yield Promise.all(t)).findIndex(s=>s)]}),IE.apply(this,arguments)}const dK=Gt("libp2p:keychain:cms"),CE=new WeakMap;class hK{constructor(e,t){if(null==e)throw se(new Error("keychain is required"),Ie.ERR_KEYCHAIN_REQUIRED);this.keychain=e,CE.set(this,{dek:t})}encrypt(e,t){var r=this;return V(function*(){if(!(t instanceof Uint8Array))throw se(new Error("Plain data must be a Uint8Array"),Ie.ERR_INVALID_PARAMETERS);const i=yield r.keychain.findKeyByName(e),s=yield r.keychain.getPrivateKey(e),o=CE.get(r);if(null==o)throw se(new Error("dek missing"),Ie.ERR_INVALID_PARAMETERS);const c=Gn.pki.decryptRsaPrivateKey(s,o.dek),m=yield((n,e)=>{const t=ox.rsa.setPublicKey(e.n,e.e),r=ox.createCertificate();r.publicKey=t,r.serialNumber="01",r.validity.notBefore=new Date,r.validity.notAfter=new Date,r.validity.notAfter.setFullYear(r.validity.notBefore.getFullYear()+10);const i=[{name:"organizationName",value:"ipfs"},{shortName:"OU",value:"keystore"},{name:"commonName",value:n.id}];return r.setSubject(i),r.setIssuer(i),r.setExtensions([{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0,codeSigning:!0,emailProtection:!0,timeStamping:!0},{name:"nsCertType",client:!0,server:!0,email:!0,objsign:!0,sslCA:!0,emailCA:!0,objCA:!0}]),r.sign(e),r})(i,c),T=Gn.pkcs7.createEnvelopedData();return T.addRecipient(m),T.content=Gn.util.createBuffer(t),T.encrypt(),_t(Gn.asn1.toDer(T.toAsn1()).getBytes(),"ascii")})()}decrypt(e){var t=this;return V(function*(){if(!(e instanceof Uint8Array))throw se(new Error("CMS data is required"),Ie.ERR_INVALID_PARAMETERS);let r;try{const R=Gn.util.createBuffer(Mt(e,"ascii")),k=Gn.asn1.fromDer(R);r=Gn.pkcs7.messageFromAsn1(k)}catch(R){throw dK.error(R),se(new Error("Invalid CMS"),Ie.ERR_INVALID_CMS)}const i=r.recipients.filter(R=>R.issuer.find(k=>"O"===k.shortName&&"ipfs"===k.value)).filter(R=>R.issuer.find(k=>"CN"===k.shortName)).map(R=>({recipient:R,keyId:R.issuer.find(k=>"CN"===k.shortName).value})),s=yield function fK(n,e){return IE.apply(this,arguments)}(i,function(){var R=V(function*(k){try{if(null!=(yield t.keychain.findKeyById(k.keyId)))return!0}catch{return!1}return!1});return function(k){return R.apply(this,arguments)}}());if(null==s){const R=i.map(k=>k.keyId);throw se(new Error(`Decryption needs one of the key(s): ${R.join(", ")}`),Ie.ERR_MISSING_KEYS,{missingKeys:R})}const o=yield t.keychain.findKeyById(s.keyId);if(null==o)throw se(new Error("No key available to decrypto"),Ie.ERR_NO_KEY);const a=yield t.keychain.getPrivateKey(o.name),c=CE.get(t);if(null==c)throw se(new Error("dek missing"),Ie.ERR_INVALID_PARAMETERS);const T=Gn.pki.decryptRsaPrivateKey(a,c.dek);return r.decrypt(s.recipient,T),_t(r.content.getBytes(),"ascii")})()}}N(1298);var pK=N(7949);const cx={sha1:"sha1","sha2-256":"sha256","sha2-512":"sha512"};function ux(n,e,t,r,i){if("sha1"!==i&&"sha2-256"!==i&&"sha2-512"!==i){const a=Object.keys(cx).join(" / ");throw se(new Error(`Hash '${i}' is unknown or not supported. Must be ${a}`),"ERR_UNSUPPORTED_HASH_TYPE")}const o=pK(n,e,t,r,cx[i]);return wU.encode64(o,null)}const yp=Gt("libp2p:keychain"),_a=new WeakMap,AE={dek:{keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function Vo(n){return null!=n&&"string"==typeof n&&n===uK(n.trim())&&n.length>0}function Hn(){return xE.apply(this,arguments)}function xE(){return(xE=V(function*(){const t=800*Math.random()+200;yield new Promise(r=>setTimeout(r,t))})).apply(this,arguments)}function oo(n){return new Xr("/pkcs8/"+n)}function Ho(n){return new Xr("/info/"+n)}class fx{constructor(e,t){if(this.components=e,this.init=Df(AE,t),null!=this.init.pass&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(null!=this.init.dek?.keyLength&&this.init.dek.keyLength<14)throw new Error("dek.keyLength must be least 14 bytes");if(null!=this.init.dek?.salt?.length&&this.init.dek.salt.length<16)throw new Error("dek.saltLength must be least 16 bytes");if(null!=this.init.dek?.iterationCount&&this.init.dek.iterationCount<1e3)throw new Error("dek.iterationCount must be least 1000");const r=null!=this.init.pass&&null!=this.init.dek?.salt?ux(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";_a.set(this,{dek:r}),this.started=!1}isStarted(){return this.started}start(){var e=this;return V(function*(){const t=Ho("self");(yield e.components.getDatastore().has(t))||(yield e.importPeer("self",e.components.getPeerId())),e.started=!0})()}stop(){this.started=!1}get cms(){const e=_a.get(this);if(null==e)throw se(new Error("dek missing"),Ie.ERR_INVALID_PARAMETERS);return new hK(this,e.dek)}static generateOptions(){const e=Object.assign({},AE),t=3*Math.ceil(16/3);return e.dek.salt=Mt(sf(t),"base64"),e}static get options(){return AE}createKey(e,t,r=2048){var i=this;return V(function*(){if(!Vo(e)||"self"===e)throw yield Hn(),se(new Error("Invalid key name"),Ie.ERR_INVALID_KEY_NAME);if("string"!=typeof t)throw yield Hn(),se(new Error("Invalid key type"),Ie.ERR_INVALID_KEY_TYPE);const s=oo(e);if(yield i.components.getDatastore().has(s))throw yield Hn(),se(new Error("Key name already exists"),Ie.ERR_KEY_ALREADY_EXISTS);if("rsa"===t.toLowerCase()&&(!Number.isSafeInteger(r)||r<2048))throw yield Hn(),se(new Error("Invalid RSA key size"),Ie.ERR_INVALID_KEY_SIZE);let a;try{const c=yield bT(t,r),m=yield c.id(),T=_a.get(i);if(null==T)throw se(new Error("dek missing"),Ie.ERR_INVALID_PARAMETERS);const R=T.dek,k=yield c.export(R);a={name:e,id:m};const U=i.components.getDatastore().batch();U.put(s,_t(k)),U.put(Ho(e),_t(JSON.stringify(a))),yield U.commit()}catch(c){throw yield Hn(),c}return a})()}listKeys(){var e=this;return V(function*(){const t={prefix:"/info/"},r=[];var o,i=!1,s=!1;try{for(var c,a=Tt(e.components.getDatastore().query(t));i=!(c=yield a.next()).done;i=!1)r.push(JSON.parse(Mt(c.value.value)))}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield a.return())}finally{if(s)throw o}}return r})()}findKeyById(e){var t=this;return V(function*(){try{return(yield t.listKeys()).find(i=>i.id===e)}catch(r){throw yield Hn(),r}})()}findKeyByName(e){var t=this;return V(function*(){if(!Vo(e))throw yield Hn(),se(new Error(`Invalid key name '${e}'`),Ie.ERR_INVALID_KEY_NAME);const r=Ho(e);try{const i=yield t.components.getDatastore().get(r);return JSON.parse(Mt(i))}catch(i){throw yield Hn(),yp.error(i),se(new Error(`Key '${e}' does not exist.`),Ie.ERR_KEY_NOT_FOUND)}})()}removeKey(e){var t=this;return V(function*(){if(!Vo(e)||"self"===e)throw yield Hn(),se(new Error(`Invalid key name '${e}'`),Ie.ERR_INVALID_KEY_NAME);const r=oo(e),i=yield t.findKeyByName(e),s=t.components.getDatastore().batch();return s.delete(r),s.delete(Ho(e)),yield s.commit(),i})()}renameKey(e,t){var r=this;return V(function*(){if(!Vo(e)||"self"===e)throw yield Hn(),se(new Error(`Invalid old key name '${e}'`),Ie.ERR_OLD_KEY_NAME_INVALID);if(!Vo(t)||"self"===t)throw yield Hn(),se(new Error(`Invalid new key name '${t}'`),Ie.ERR_NEW_KEY_NAME_INVALID);const i=oo(e),s=oo(t),o=Ho(e),a=Ho(t);if(yield r.components.getDatastore().has(s))throw yield Hn(),se(new Error(`Key '${t}' already exists`),Ie.ERR_KEY_ALREADY_EXISTS);try{const m=yield r.components.getDatastore().get(i),T=yield r.components.getDatastore().get(o),R=JSON.parse(Mt(T));R.name=t;const k=r.components.getDatastore().batch();return k.put(s,m),k.put(a,_t(JSON.stringify(R))),k.delete(i),k.delete(o),yield k.commit(),R}catch(m){throw yield Hn(),m}})()}exportKey(e,t){var r=this;return V(function*(){if(!Vo(e))throw yield Hn(),se(new Error(`Invalid key name '${e}'`),Ie.ERR_INVALID_KEY_NAME);if(null==t)throw yield Hn(),se(new Error("Password is required"),Ie.ERR_PASSWORD_REQUIRED);const i=oo(e);try{const o=Mt(yield r.components.getDatastore().get(i)),a=_a.get(r);if(null==a)throw se(new Error("dek missing"),Ie.ERR_INVALID_PARAMETERS);const c=a.dek;return yield(yield Rv(o,c)).export(t)}catch(s){throw yield Hn(),s}})()}importKey(e,t,r){var i=this;return V(function*(){if(!Vo(e)||"self"===e)throw yield Hn(),se(new Error(`Invalid key name '${e}'`),Ie.ERR_INVALID_KEY_NAME);if(null==t)throw yield Hn(),se(new Error("PEM encoded key is required"),Ie.ERR_PEM_REQUIRED);const s=oo(e);if(yield i.components.getDatastore().has(s))throw yield Hn(),se(new Error(`Key '${e}' already exists`),Ie.ERR_KEY_ALREADY_EXISTS);let a,c;try{a=yield Rv(t,r)}catch{throw yield Hn(),se(new Error("Cannot read the key, most likely the password is wrong"),Ie.ERR_CANNOT_READ_KEY)}try{c=yield a.id();const R=_a.get(i);if(null==R)throw se(new Error("dek missing"),Ie.ERR_INVALID_PARAMETERS);const k=R.dek;t=yield a.export(k)}catch(R){throw yield Hn(),R}const m={name:e,id:c},T=i.components.getDatastore().batch();return T.put(s,_t(t)),T.put(Ho(e),_t(JSON.stringify(m))),yield T.commit(),m})()}importPeer(e,t){var r=this;return V(function*(){try{if(!Vo(e))throw se(new Error(`Invalid key name '${e}'`),Ie.ERR_INVALID_KEY_NAME);if(null==t)throw se(new Error("PeerId is required"),Ie.ERR_MISSING_PRIVATE_KEY);if(null==t.privateKey)throw se(new Error("PeerId.privKey is required"),Ie.ERR_MISSING_PRIVATE_KEY);const i=yield Au(t.privateKey),s=oo(e);if(yield r.components.getDatastore().has(s))throw yield Hn(),se(new Error(`Key '${e}' already exists`),Ie.ERR_KEY_ALREADY_EXISTS);const a=_a.get(r);if(null==a)throw se(new Error("dek missing"),Ie.ERR_INVALID_PARAMETERS);const c=a.dek,m=yield i.export(c),T={name:e,id:t.toString()},R=r.components.getDatastore().batch();return R.put(s,_t(m)),R.put(Ho(e),_t(JSON.stringify(T))),yield R.commit(),T}catch(i){throw yield Hn(),i}})()}getPrivateKey(e){var t=this;return V(function*(){if(!Vo(e))throw yield Hn(),se(new Error(`Invalid key name '${e}'`),Ie.ERR_INVALID_KEY_NAME);try{const r=oo(e);return Mt(yield t.components.getDatastore().get(r))}catch(r){throw yield Hn(),yp.error(r),se(new Error(`Key '${e}' does not exist.`),Ie.ERR_KEY_NOT_FOUND)}})()}rotateKeychainPass(e,t){var r=this;return V(function*(){if("string"!=typeof e)throw yield Hn(),se(new Error(`Invalid old pass type '${typeof e}'`),Ie.ERR_INVALID_OLD_PASS_TYPE);if("string"!=typeof t)throw yield Hn(),se(new Error(`Invalid new pass type '${typeof t}'`),Ie.ERR_INVALID_NEW_PASS_TYPE);if(t.length<20)throw yield Hn(),se(new Error(`Invalid pass length ${t.length}`),Ie.ERR_INVALID_PASS_LENGTH);yp("recreating keychain");const i=_a.get(r);if(null==i)throw se(new Error("dek missing"),Ie.ERR_INVALID_PARAMETERS);const s=i.dek;r.init.pass=t;const o=null!=t&&null!=r.init.dek?.salt?ux(t,r.init.dek.salt,r.init.dek?.iterationCount,r.init.dek?.keyLength,r.init.dek?.hash):"";_a.set(r,{dek:o});const a=yield r.listKeys();for(const c of a){const T=Mt(yield r.components.getDatastore().get(oo(c.name))),R=yield Rv(T,s),k=o.toString(),U=yield R.export(k),Q=r.components.getDatastore().batch(),X={name:c.name,id:c.id};Q.put(oo(c.name),_t(U)),Q.put(Ho(c.name),_t(JSON.stringify(X))),yield Q.commit()}yp("keychain reconstructed")})()}}var RE=N(1349),yK=N(5550);class mK{constructor(e){if("number"!=typeof e)throw new Error("must provide a timespan to the moving average constructor");if(e<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t){if(null!=this.previousTime){const r=this.alpha(e,this.previousTime),i=t-this.movingAverage,s=r*i;this.movingAverage=r*t+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+i*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*i}else this.movingAverage=t;this.previousTime=e}}function dx(n){return new mK(n)}class PE extends ki{constructor(e){super(),this.enabled=e.enabled,this.queue=[],this.stats={dataReceived:0n,dataSent:0n},this.frequencyLastTime=Date.now(),this.frequencyAccumulators={},this.movingAverages={dataReceived:[],dataSent:[]},this.computeThrottleMaxQueueSize=e.computeThrottleMaxQueueSize,this.computeThrottleTimeout=e.computeThrottleTimeout,this._update=this._update.bind(this),this.movingAverageIntervals=e.movingAverageIntervals;for(let t=0;t0&&this._resetComputeTimeout()}stop(){null!=this.timeout&&(this.timeout.clear(),this.timeout=null)}getSnapshot(){return Object.assign({},this.stats)}getMovingAverages(){return Object.assign({},this.movingAverages)}push(e,t){this.queue.push([e,t,Date.now()]),this._resetComputeTimeout()}_resetComputeTimeout(){this.timeout=Sf(this._update,this._nextTimeout())}_nextTimeout(){return Math.max(this.computeThrottleTimeout*(1-this.queue.length/this.computeThrottleMaxQueueSize),0)}_update(){if(this.timeout=null,this.queue.length>0){let e=["",0,0];for(e of this.queue)this._applyOp(e);this.queue=[],e.length>2&&""!==e[0]&&this._updateFrequency(e[2]),this.dispatchEvent(new rn("update",{detail:this.stats}))}}_updateFrequency(e){const t=e-this.frequencyLastTime;this._updateFrequencyFor("dataReceived",t,e),this._updateFrequencyFor("dataSent",t,e),this.frequencyLastTime=e}_updateFrequencyFor(e,t,r){const i=this.frequencyAccumulators[e]??0;this.frequencyAccumulators[e]=0;const o=i/(t??1)*1e3;let a=this.movingAverages[e];null==a&&(a=this.movingAverages[e]=[]);const c=this.movingAverageIntervals;for(let m=0;ms:s})}forPeer(e){const t=e.toString();return this.peerStats.get(t)??this.oldPeers.get(t)}getProtocols(){return Array.from(this.protocolStats.keys())}forProtocol(e){return this.protocolStats.get(e)}onPeerDisconnected(e){const t=e.toString(),r=this.peerStats.get(t);null!=r&&(r.stop(),this.peerStats.delete(t),this.oldPeers.set(t,r))}_onMessage(e){if(!this.running)return;const{remotePeer:t,protocol:r,direction:i,dataLength:s}=e,o=EK[i];let a=this.forPeer(t);if(null==a){const c=new PE(this.statsInit);this.peerStats.set(t.toString(),c),a=c}if(a.push(o,s),this.globalStats.push(o,s),null!=r){let c=this.forProtocol(r);if(null==c){const m=new PE(this.statsInit);this.protocolStats.set(r,m),c=m}c.push(o,s)}}updatePlaceholder(e,t){if(!this.running)return;const r=e.toString(),i=this.peerStats.get(r)??this.oldPeers.get(r),s=t.toString(),o=this.peerStats.get(s)??this.oldPeers.get(s);let a=i;null!=o&&(a=function bK(n,e){return n.stop(),e.stop(),n.queue=[...n.queue,...e.queue],n}(o,a),this.oldPeers.remove(s)),this.peerStats.delete(e.toString()),this.peerStats.set(s,a),a.start()}trackStream(e){var t=this;const{stream:r,remotePeer:i,protocol:s}=e;if(!this.running)return;r.source=RE(r.source,c=>this._onMessage({remotePeer:i,protocol:s,direction:"in",dataLength:c.byteLength}));const a=r.sink;r.sink=function(){var c=V(function*(m){return yield Ln(m,T=>RE(T,R=>{t._onMessage({remotePeer:i,protocol:s,direction:"out",dataLength:R.byteLength})}),a)});return function(m){return c.apply(this,arguments)}}()}}function NE(n){return ME.apply(this,arguments)}function ME(){return ME=V(function*(n){try{return{status:"fulfilled",value:yield n,isFulfilled:!0,isRejected:!1}}catch(e){return{status:"rejected",reason:e,isFulfilled:!1,isRejected:!0}}}),ME.apply(this,arguments)}function OE(n,e,t){(function _K(n,e){if(e.has(n))throw new TypeError("Cannot initialize the same private elements twice on an object")})(n,e),e.set(n,t)}function hx(n,e,t){if(!e.has(n))throw new TypeError("attempted to "+t+" private field on non-instance");return e.get(n)}function Ko(n,e,t){return function DK(n,e,t){if(e.set)e.set.call(n,t);else{if(!e.writable)throw new TypeError("attempted to set read only private field");e.value=t}}(n,hx(n,e,"set"),t),t}function Da(n,e){return function SK(n,e){return e.get?e.get.call(n):e.value}(n,hx(n,e,"get"))}function px(n,e,t){return e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}let gx;class IK{constructor(e){px(this,"value",void 0),px(this,"next",void 0),this.value=e}}var Sa=new WeakMap,xf=new WeakMap,ic=new WeakMap;gx=Symbol.iterator;class CK{constructor(){OE(this,Sa,{writable:!0,value:void 0}),OE(this,xf,{writable:!0,value:void 0}),OE(this,ic,{writable:!0,value:void 0}),this.clear()}enqueue(e){var t;const i=new IK(e);Da(this,Sa)?(Da(this,xf).next=i,Ko(this,xf,i)):(Ko(this,Sa,i),Ko(this,xf,i)),Ko(this,ic,(t=Da(this,ic),++t))}dequeue(){var e;const r=Da(this,Sa);if(r)return Ko(this,Sa,Da(this,Sa).next),Ko(this,ic,(e=Da(this,ic),--e)),r.value}clear(){Ko(this,Sa,void 0),Ko(this,xf,void 0),Ko(this,ic,0)}get size(){return Da(this,ic)}*[gx](){let e=Da(this,Sa);for(;e;)yield e.value,e=e.next}}function TK(n){if(!Number.isInteger(n)&&n!==Number.POSITIVE_INFINITY||!(n>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");const e=new CK;let t=0;const i=function(){var a=V(function*(c,m,T){t++;const R=V(function*(){return c(...T)})();m(R);try{yield R}catch{}t--,e.size>0&&e.dequeue()()});return function(m,T,R){return a.apply(this,arguments)}}(),o=(a,...c)=>new Promise(m=>{((a,c,m)=>{e.enqueue(i.bind(void 0,a,c,m)),V(function*(){yield Promise.resolve(),t0&&e.dequeue()()})()})(a,m,c)});return Object.defineProperties(o,{activeCount:{get:()=>t},pendingCount:{get:()=>e.size},clearQueue:{value:()=>{e.clear()}}}),o}function AK(n){return LE.apply(this,arguments)}function LE(){return LE=V(function*(n,e={}){const{concurrency:t=Number.POSITIVE_INFINITY}=e,r=TK(t);return Promise.all(n.map(i=>NE(i&&"function"==typeof i.then?i:"function"==typeof i?r(()=>i()):Promise.resolve(i))))}),LE.apply(this,arguments)}const sc=Gt("libp2p:transports");class xK extends ki{constructor(e,t={}){super(),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Ef({component:"transport-manager",metric:"listeners",metrics:this.components.getMetrics()}),this.faultTolerance=t.faultTolerance??oc.FATAL_ALL}add(e){const t=e[Symbol.toStringTag];if(null==t)throw se(new Error("Transport must have a valid tag"),Ie.ERR_INVALID_KEY);if(this.transports.has(t))throw se(new Error("There is already a transport with this tag"),Ie.ERR_DUPLICATE_TRANSPORT);sc("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){var e=this;return V(function*(){const t=e.components.getAddressManager().getListenAddrs();yield e.listen(t),e.started=!0})()}stop(){var e=this;return V(function*(){const t=[];for(const[r,i]of e.listeners)for(sc("closing listeners for %s",r);i.length>0;){const s=i.pop();null!=s&&t.push(s.close())}yield Promise.all(t),sc("all listeners closed");for(const r of e.listeners.keys())e.listeners.set(r,[]);e.started=!1})()}dial(e,t){var r=this;return V(function*(){const i=r.transportForMultiaddr(e);if(null==i)throw se(new Error(`No transport available for address ${String(e)}`),Ie.ERR_TRANSPORT_UNAVAILABLE);try{return yield i.dial(e,{...t,upgrader:r.components.getUpgrader()})}catch(s){throw null==s.code&&(s.code=Ie.ERR_TRANSPORT_DIAL_FAILED),s}})()}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}transportForMultiaddr(e){for(const t of this.transports.values())if(t.filter([e]).length>0)return t}listen(e){var t=this;return V(function*(){if(null==e||0===e.length)return void sc("no addresses were provided for listening, this node is dial only");const r=[];for(const[i,s]of t.transports.entries()){const o=s.filter(e),a=[];for(const T of o){sc("creating listener for %s on %s",i,T);const R=s.createListener({upgrader:t.components.getUpgrader()});let k=t.listeners.get(i);null==k&&(k=[],t.listeners.set(i,k)),k.push(R),R.addEventListener("listening",()=>{t.dispatchEvent(new rn("listener:listening",{detail:R}))}),R.addEventListener("close",()=>{t.dispatchEvent(new rn("listener:close",{detail:R}))}),a.push(R.listen(T))}if(0!==a.length){if(null==(yield AK(a)).find(T=>T.isFulfilled)&&t.faultTolerance!==oc.NO_FATAL)throw se(new Error(`Transport (${i}) could not listen on any available address`),Ie.ERR_NO_VALID_ADDRESSES)}else r.push(i)}if(r.length===t.transports.size){const i=`no valid addresses were provided for transports [${r.join(", ")}]`;if(t.faultTolerance===oc.FATAL_ALL)throw se(new Error(i),Ie.ERR_NO_VALID_ADDRESSES);sc(`libp2p in dial mode only: ${i}`)}})()}remove(e){var t=this;return V(function*(){sc("removing %s",e);for(const r of t.listeners.get(e)??[])yield r.close();t.transports.delete(e),t.listeners.delete(e)})()}removeAll(){var e=this;return V(function*(){const t=[];for(const r of e.transports.keys())t.push(e.remove(r));yield Promise.all(t)})()}}var oc=(()=>(function(n){n[n.FATAL_ALL=0]="FATAL_ALL",n[n.NO_FATAL=1]="NO_FATAL"}(oc||(oc={})),oc))();const Lu="/multistream/1.0.0",yx=_t("\n");function kE(n){const e=new $n(n,yx);return to.single(e)}function Rf(n,e,t={}){const r=kE(e);n.push(!0===t.writeBytes?r.subarray():r)}function RK(n,e,t={}){const r=new $n;for(const i of e)r.append(kE(i));n.push(!0===t.writeBytes?r.subarray():r)}function PK(n,e){return BE.apply(this,arguments)}function BE(){return BE=V(function*(n,e){let t=1;const r={[Symbol.asyncIterator]:()=>r,next:(a=V(function*(){return yield n.next(t)}),function(){return a.apply(this,arguments)})};var a;let i=r;null!=e?.signal&&(i=Fs(r,e.signal));const o=yield Ln(i,Ms({onLength:a=>{t=a}}),function(){var a=V(function*(c){return yield nc(c)});return function(c){return a.apply(this,arguments)}}());if(null==o)throw se(new Error("no buffer returned"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==yx[0])throw se(new Error("missing newline"),"ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}),BE.apply(this,arguments)}function mp(n,e){return FE.apply(this,arguments)}function FE(){return FE=V(function*(n,e){return Mt((yield PK(n,e)).subarray())}),FE.apply(this,arguments)}const Pf=Gt("libp2p:mss:select");function UE(n,e){return VE.apply(this,arguments)}function VE(){return VE=V(function*(n,e,t={}){e=Array.isArray(e)?[...e]:[e];const{reader:r,writer:i,rest:s,stream:o}=Ch(n),a=e.shift();if(null==a)throw new Error("At least one protocol must be specified");Pf('select: write ["%s", "%s"]',Lu,a),RK(i,[_t(Lu),_t(a)],t);let T=yield mp(r,t);if(Pf('select: read "%s"',T),T===Lu&&(T=yield mp(r,t),Pf('select: read "%s"',T)),T===a)return s(),{stream:o,protocol:a};for(const R of e){Pf('select: write "%s"',R),Rf(i,_t(R),t);const k=yield mp(r,t);if(Pf('select: read "%s" for "%s"',k,R),k===R)return s(),{stream:o,protocol:R}}throw s(),se(new Error("protocol selection failed"),"ERR_UNSUPPORTED_PROTOCOL")}),VE.apply(this,arguments)}const Nf=Gt("libp2p:mss:handle");function HE(n,e,t){return KE.apply(this,arguments)}function KE(){return KE=V(function*(n,e,t){e=Array.isArray(e)?e:[e];const{writer:r,reader:i,rest:s,stream:o}=Ch(n);for(;;){const a=yield mp(i,t);if(Nf('read "%s"',a),a!==Lu){if(e.includes(a))return Rf(r,_t(a),t),Nf('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};"ls"!==a?(Rf(r,_t("na"),t),Nf('respond with "na" for "%s"',a)):(Rf(r,new $n(...e.map(c=>kE(_t(c)))),t),Nf('respond with "%s" for %s',e,a))}else Nf('respond with "%s" for "%s"',Lu,a),Rf(r,_t(Lu),t)}}),KE.apply(this,arguments)}var mx=N(344);const vx=Symbol.for("@libp2p/connection"),NK=Gt("libp2p:connection");class MK{constructor(e){const{remoteAddr:t,remotePeer:r,newStream:i,close:s,getStreams:o,stat:a}=e;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.stat={...a,status:"OPEN"},this._newStream=i,this._close=s,this._getStreams=o,this.tags=[],this._closing=!1}get[Symbol.toStringTag](){return"Connection"}get[vx](){return!0}get streams(){return this._getStreams()}newStream(e,t){var r=this;return V(function*(){if(r.stat.status===jA)throw se(new Error("the connection is being closed"),"ERR_CONNECTION_BEING_CLOSED");if(r.stat.status===gE)throw se(new Error("the connection is closed"),"ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);const i=yield r._newStream(e,t);return i.stat.direction="outbound",i})()}addStream(e){e.stat.direction="inbound"}removeStream(e){}close(){var e=this;return V(function*(){if(e.stat.status!==gE&&!e._closing){e.stat.status=jA;try{e.streams.forEach(t=>t.close())}catch(t){NK.error(t)}e._closing=!0,yield e._close(),e._closing=!1,e.stat.timeline.close=Date.now(),e.stat.status=gE}})()}}const jE=Symbol.for("@libp2p/topology"),Ex=Gt("libp2p:registrar");class kK{constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onProtocolChange=this._onProtocolChange.bind(this),this.components.getConnectionManager().addEventListener("peer:disconnect",this._onDisconnect),this.components.getPeerStore().addEventListener("change:protocols",this._onProtocolChange)}getProtocols(){return Array.from(new Set([...this.topologies.keys(),...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw se(new Error(`No handler registered for protocol ${e}`),Ie.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}handle(e,t,r){var i=this;return V(function*(){if(i.handlers.has(e))throw se(new Error(`Handler already registered for protocol ${e}`),Ie.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);const s=Df.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);i.handlers.set(e,{handler:t,options:s}),yield i.components.getPeerStore().protoBook.add(i.components.getPeerId(),[e])})()}unhandle(e){var t=this;return V(function*(){const r=Array.isArray(e)?e:[e];r.forEach(i=>{t.handlers.delete(i)}),yield t.components.getPeerStore().protoBook.remove(t.components.getPeerId(),r)})()}register(e,t){var r=this;return V(function*(){if(!function LK(n){return null!=n&&Boolean(n[jE])}(t))throw Ex.error("topology must be an instance of interfaces/topology"),se(new Error("topology must be an instance of interfaces/topology"),Ie.ERR_INVALID_PARAMETERS);const i=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let s=r.topologies.get(e);return null==s&&(s=new Map,r.topologies.set(e,s)),s.set(i,t),yield t.setRegistrar(r),i})()}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail;this.components.getPeerStore().protoBook.get(t.remotePeer).then(r=>{for(const i of r){const s=this.topologies.get(i);if(null!=s)for(const o of s.values())o.onDisconnect(t.remotePeer)}}).catch(r=>{Ex.error(r)})}_onProtocolChange(e){const{peerId:t,protocols:r,oldProtocols:i}=e.detail,s=i.filter(a=>!r.includes(a)),o=r.filter(a=>!i.includes(a));for(const a of s){const c=this.topologies.get(a);if(null!=c)for(const m of c.values())m.onDisconnect(t)}for(const a of o){const c=this.topologies.get(a);if(null!=c)for(const m of c.values()){const T=this.components.getConnectionManager().getConnections(t)[0];null!=T&&m.onConnect(t,T)}}}}const Zn=Gt("libp2p:upgrader");function _x(n,e,t){let r=0;return t.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===n&&r++}),r}class UK extends ki{constructor(e,t){super(),this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(r=>{this.connectionEncryption.set(r.protocol,r)}),this.muxers=new Map,t.muxers.forEach(r=>{this.muxers.set(r.protocol,r)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout}upgradeInbound(e){var t=this;return V(function*(){let r,i,s,o,a,c,m;const T=t.components.getMetrics(),R=new Bi.TimeoutController(t.inboundUpgradeTimeout);try{(0,Jr.setMaxListeners)?.(1/0,R.signal)}catch{}try{const k=ga(e,R.signal);if(e.source=k.source,e.sink=k.sink,yield t.components.getConnectionGater().denyInboundConnection(e))throw se(new Error("The multiaddr connection is blocked by gater.acceptConnection"),Ie.ERR_CONNECTION_INTERCEPTED);if(null!=T){({setTarget:c,proxy:m}=mx());const X=`${(1e9*Math.random()).toString(36)}${Date.now()}`;c({toString:()=>X}),T.trackStream({stream:e,remotePeer:m})}Zn("starting the inbound connection upgrade");let U=e;const Q=t.components.getConnectionProtector();null!=Q&&(Zn("protecting the inbound connection"),U=yield Q.protect(e));try{if(({conn:r,remotePeer:i,protocol:a}=yield t._encryptInbound(U)),yield t.components.getConnectionGater().denyInboundEncryptedConnection(i,{...U,...r}))throw se(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),Ie.ERR_CONNECTION_INTERCEPTED);if(t.muxers.size>0){const X=yield t._multiplexInbound({...U,...r},t.muxers);o=X.muxerFactory,s=X.stream}else s=r}catch(X){throw Zn.error("Failed to upgrade inbound connection",X),yield e.close(X),X}if(yield t.components.getConnectionGater().denyInboundUpgradedConnection(i,{...U,...r}))throw se(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),Ie.ERR_CONNECTION_INTERCEPTED);return null!=T&&(T.updatePlaceholder(m,i),c(i)),Zn("Successfully upgraded inbound connection"),t._createConnection({cryptoProtocol:a,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:o,remotePeer:i})}finally{R.clear()}})()}upgradeOutbound(e){var t=this;return V(function*(){const r=e.remoteAddr.getPeerId();if(null==r)throw se(new Error("outbound connection must have a peer id"),Ie.ERR_INVALID_MULTIADDR);const i=_r(r);if(yield t.components.getConnectionGater().denyOutboundConnection(i,e))throw se(new Error("The multiaddr connection is blocked by connectionGater.denyOutboundConnection"),Ie.ERR_CONNECTION_INTERCEPTED);let s,o,a,c,m,T,R;const k=t.components.getMetrics();if(null!=k){({setTarget:T,proxy:R}=mx());const X=`${(1e9*Math.random()).toString(36)}${Date.now()}`;T({toB58String:()=>X}),k.trackStream({stream:e,remotePeer:R})}Zn("Starting the outbound connection upgrade");let U=e;const Q=t.components.getConnectionProtector();null!=Q&&(U=yield Q.protect(e));try{if(({conn:s,remotePeer:o,protocol:c}=yield t._encryptOutbound(U,i)),yield t.components.getConnectionGater().denyOutboundEncryptedConnection(o,{...U,...s}))throw se(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),Ie.ERR_CONNECTION_INTERCEPTED);if(t.muxers.size>0){const X=yield t._multiplexOutbound({...U,...s},t.muxers);m=X.muxerFactory,a=X.stream}else a=s}catch(X){throw Zn.error("Failed to upgrade outbound connection",X),yield e.close(X),X}if(yield t.components.getConnectionGater().denyOutboundUpgradedConnection(o,{...U,...s}))throw se(new Error("The multiaddr connection is blocked by gater.acceptEncryptedConnection"),Ie.ERR_CONNECTION_INTERCEPTED);return null!=k&&(k.updatePlaceholder(R,o),T(o)),Zn("Successfully upgraded outbound connection"),t._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:m,remotePeer:o})})()}_createConnection(e){var t=this;const{cryptoProtocol:r,direction:i,maConn:s,upgradedConn:o,remotePeer:a,muxerFactory:c}=e;let m,T,R;null!=c&&(m=c.createStreamMuxer({direction:i,onIncomingStream:Q=>{null!=R&&Promise.resolve().then(V(function*(){const X=t.components.getRegistrar().getProtocols(),{stream:ae,protocol:he}=yield HE(Q,X);if(Zn("%s: incoming stream opened on %s",i,he),t.components.getMetrics()?.trackStream({stream:ae,remotePeer:a,protocol:he}),null==R)return;const ue=function BK(n,e){try{const{options:t}=e.getHandler(n);return t.maxInboundStreams}catch(t){if(t.code!==Ie.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return 32}(he,t.components.getRegistrar());_x(he,"inbound",R)!==ue?(Q.stat.protocol=he,t.components.getPeerStore().protoBook.add(a,[he]).catch(Le=>Zn.error(Le)),R.addStream(Q),t._onStream({connection:R,stream:{...Q,...ae},protocol:he})):Q.abort(se(new Error(`Too many inbound protocol streams for protocol "${he}" - limit ${ue}`),Ie.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS))})).catch(X=>{Zn.error(X),null==Q.stat.timeline.close&&Q.close()})},onStreamEnd:Q=>{R?.removeStream(Q.id)}}),hi(m)&&m.init(this.components),T=function(){var Q=V(function*(X,ae={}){if(null==m)throw se(new Error("Stream is not multiplexed"),Ie.ERR_MUXER_UNAVAILABLE);Zn("%s: starting new stream on %s",i,X);const he=m.newStream(),Ae=t.components.getMetrics();let ue;try{if(null==ae.signal){Zn("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",X),ue=new Bi.TimeoutController(3e4),ae.signal=ue.signal;try{(0,Jr.setMaxListeners)?.(1/0,ue.signal)}catch{}}const{stream:Re,protocol:Le}=yield UE(he,X,ae);Ae?.trackStream({stream:Re,remotePeer:a,protocol:Le});const Fe=function FK(n,e){try{const{options:t}=e.getHandler(n);return t.maxOutboundStreams}catch(t){if(t.code!==Ie.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return 64}(Le,t.components.getRegistrar());if(_x(Le,"outbound",R)===Fe){const mt=se(new Error(`Too many outbound protocol streams for protocol "${Le}" - limit ${Fe}`),Ie.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw he.abort(mt),mt}return he.stat.protocol=Le,t.components.getPeerStore().protoBook.add(a,[Le]).catch(mt=>Zn.error(mt)),{...he,...Re,stat:{...he.stat,protocol:Le}}}catch(Re){throw Zn.error("could not create new stream",Re),null==he.stat.timeline.close&&he.close(),null!=Re.code?Re:se(Re,Ie.ERR_UNSUPPORTED_PROTOCOL)}finally{ue?.clear()}});return function(ae){return Q.apply(this,arguments)}}(),Ln(o,m,o).catch(Zn.error));const k=s.timeline;s.timeline=new Proxy(k,{set:(...Q)=>(null!=R&&"close"===Q[1]&&null!=Q[2]&&null==k.close&&V(function*(){try{"OPEN"===R.stat.status&&(yield R.close())}catch(X){Zn.error(X)}finally{t.dispatchEvent(new rn("connectionEnd",{detail:R}))}})().catch(X=>{Zn.error(X)}),Reflect.set(...Q))}),s.timeline.upgraded=Date.now();const U=()=>{throw se(new Error("connection is not multiplexed"),Ie.ERR_CONNECTION_NOT_MULTIPLEXED)};return R=function OK(n){return new MK(n)}({remoteAddr:s.remoteAddr,remotePeer:a,stat:{status:"OPEN",direction:i,timeline:s.timeline,multiplexer:m?.protocol,encryption:r},newStream:T??U,getStreams:()=>null!=m?m.streams:U(),close:(Q=V(function*(){yield s.close(),m?.close()}),function(){return Q.apply(this,arguments)})}),this.dispatchEvent(new rn("connection",{detail:R})),R;var Q}_onStream(e){const{connection:t,stream:r,protocol:i}=e,{handler:s}=this.components.getRegistrar().getHandler(i);s({connection:t,stream:r})}_encryptInbound(e){var t=this;return V(function*(){const r=Array.from(t.connectionEncryption.keys());Zn("handling inbound crypto protocol selection",r);try{const{stream:i,protocol:s}=yield HE(e,r,{writeBytes:!0}),o=t.connectionEncryption.get(s);if(null==o)throw new Error(`no crypto module found for ${s}`);return Zn("encrypting inbound connection..."),{...yield o.secureInbound(t.components.getPeerId(),i),protocol:s}}catch(i){throw se(i,Ie.ERR_ENCRYPTION_FAILED)}})()}_encryptOutbound(e,t){var r=this;return V(function*(){const i=Array.from(r.connectionEncryption.keys());Zn("selecting outbound crypto protocol",i);try{const{stream:s,protocol:o}=yield UE(e,i,{writeBytes:!0}),a=r.connectionEncryption.get(o);if(null==a)throw new Error(`no crypto module found for ${o}`);return Zn("encrypting outbound connection to %p",t),{...yield a.secureOutbound(r.components.getPeerId(),s,t),protocol:o}}catch(s){throw se(s,Ie.ERR_ENCRYPTION_FAILED)}})()}_multiplexOutbound(e,t){return V(function*(){const r=Array.from(t.keys());Zn("outbound selecting muxer %s",r);try{const{stream:i,protocol:s}=yield UE(e,r,{writeBytes:!0});return Zn("%s selected as muxer protocol",s),{stream:i,muxerFactory:t.get(s)}}catch(i){throw Zn.error("error multiplexing outbound stream",i),se(i,Ie.ERR_MUXER_UNAVAILABLE)}})()}_multiplexInbound(e,t){return V(function*(){const r=Array.from(t.keys());Zn("inbound handling muxers %s",r);try{const{stream:i,protocol:s}=yield HE(e,r,{writeBytes:!0});return{stream:i,muxerFactory:t.get(s)}}catch(i){throw Zn.error("error multiplexing inbound stream",i),se(i,Ie.ERR_MUXER_UNAVAILABLE)}})()}}var ac;!function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null!=t.protocolVersion&&(r.uint32(42),r.string(t.protocolVersion)),null!=t.agentVersion&&(r.uint32(50),r.string(t.agentVersion)),null!=t.publicKey&&(r.uint32(10),r.bytes(t.publicKey)),null==t.listenAddrs)throw new Error('Protocol error: required field "listenAddrs" was not found in object');for(const s of t.listenAddrs)r.uint32(18),r.bytes(s);if(null!=t.observedAddr&&(r.uint32(34),r.bytes(t.observedAddr)),null==t.protocols)throw new Error('Protocol error: required field "protocols" was not found in object');for(const s of t.protocols)r.uint32(26),r.string(s);null!=t.signedPeerRecord&&(r.uint32(66),r.bytes(t.signedPeerRecord)),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs=i.listenAddrs??[],i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols=i.protocols??[],i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(7&o)}}if(i.listenAddrs=i.listenAddrs??[],i.protocols=i.protocols??[],null==i.listenAddrs)throw new Error('Protocol error: value for required field "listenAddrs" was not found in protobuf');if(null==i.protocols)throw new Error('Protocol error: value for required field "protocols" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(ac||(ac={}));var vp;!function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.publicKey)throw new Error('Protocol error: required field "publicKey" was not found in object');if(r.uint32(10),r.bytes(t.publicKey),null==t.payloadType)throw new Error('Protocol error: required field "payloadType" was not found in object');if(r.uint32(18),r.bytes(t.payloadType),null==t.payload)throw new Error('Protocol error: required field "payload" was not found in object');if(r.uint32(26),r.bytes(t.payload),null==t.signature)throw new Error('Protocol error: required field "signature" was not found in object');r.uint32(42),r.bytes(t.signature),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(7&o)}}if(null==i.publicKey)throw new Error('Protocol error: value for required field "publicKey" was not found in protobuf');if(null==i.payloadType)throw new Error('Protocol error: value for required field "payloadType" was not found in protobuf');if(null==i.payload)throw new Error('Protocol error: value for required field "payload" was not found in protobuf');if(null==i.signature)throw new Error('Protocol error: value for required field "signature" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(vp||(vp={}));class Yi{constructor(e){const{peerId:t,payloadType:r,payload:i,signature:s}=e;this.peerId=t,this.payloadType=r,this.payload=i,this.signature=s}marshal(){if(null==this.peerId.publicKey)throw new Error("Missing public key");return null==this.marshaled&&(this.marshaled=vp.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return $r(this.marshal(),e.marshal())}validate(e){var t=this;return V(function*(){const r=Dx(e,t.payloadType,t.payload);if(null==t.peerId.publicKey)throw new Error("Missing public key");return yield Tu(t.peerId.publicKey).verify(r.subarray(),t.signature)})()}}Yi.createFromProtobuf=function(){var n=V(function*(e){const t=vp.decode(e),r=yield xu(t.publicKey);return new Yi({peerId:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})});return function(e){return n.apply(this,arguments)}}(),Yi.seal=function(){var n=V(function*(e,t){if(null==t.privateKey)throw new Error("Missing private key");const r=e.domain,i=e.codec,s=e.marshal(),o=Dx(r,i,s),c=yield(yield Au(t.privateKey)).sign(o.subarray());return new Yi({peerId:t,payloadType:i,payload:s,signature:c})});return function(e,t){return n.apply(this,arguments)}}(),Yi.openAndCertify=function(){var n=V(function*(e,t){const r=yield Yi.createFromProtobuf(e);if(!(yield r.validate(t)))throw se(new Error("envelope signature is not valid for the given domain"),"ERR_SIGNATURE_NOT_VALID");return r});return function(e,t){return n.apply(this,arguments)}}();const Dx=(n,e,t)=>{const r=_t(n),i=Qt.encode(r.byteLength),s=Qt.encode(e.length),o=Qt.encode(t.length);return new $n(i,r,s,e,o,t)};var Ep;!function(n){let e,t;!function(r){let i;r.codec=()=>(null==i&&(i=fi((s,o,a={})=>{if(!1!==a.lengthDelimited&&o.fork(),null==s.multiaddr)throw new Error('Protocol error: required field "multiaddr" was not found in object');o.uint32(10),o.bytes(s.multiaddr),!1!==a.lengthDelimited&&o.ldelim()},(s,o)=>{const a={multiaddr:new Uint8Array(0)},c=null==o?s.len:s.pos+o;for(;s.pos>>3==1?a.multiaddr=s.bytes():s.skipType(7&m)}if(null==a.multiaddr)throw new Error('Protocol error: value for required field "multiaddr" was not found in protobuf');return a})),i),r.encode=s=>li(s,r.codec()),r.decode=s=>ui(s,r.codec())}(e=n.AddressInfo||(n.AddressInfo={})),n.codec=()=>(null==t&&(t=fi((r,i,s={})=>{if(!1!==s.lengthDelimited&&i.fork(),null==r.peerId)throw new Error('Protocol error: required field "peerId" was not found in object');if(i.uint32(10),i.bytes(r.peerId),null==r.seq)throw new Error('Protocol error: required field "seq" was not found in object');if(i.uint32(16),i.uint64(r.seq),null==r.addresses)throw new Error('Protocol error: required field "addresses" was not found in object');for(const o of r.addresses)i.uint32(26),n.AddressInfo.codec().encode(o,i);!1!==s.lengthDelimited&&i.ldelim()},(r,i)=>{const s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=null==i?r.len:r.pos+i;for(;r.pos>>3){case 1:s.peerId=r.bytes();break;case 2:s.seq=r.uint64();break;case 3:s.addresses.push(n.AddressInfo.codec().decode(r,r.uint32()));break;default:r.skipType(7&a)}}if(null==s.peerId)throw new Error('Protocol error: value for required field "peerId" was not found in protobuf');if(null==s.seq)throw new Error('Protocol error: value for required field "seq" was not found in protobuf');return s})),t),n.encode=r=>li(r,n.codec()),n.decode=r=>ui(r,n.codec())}(Ep||(Ep={}));const $K=Uint8Array.from([3,1]);let ku=(()=>{class n{constructor(t){this.domain=n.DOMAIN,this.codec=n.CODEC;const{peerId:r,multiaddrs:i,seqNumber:s}=t;this.peerId=r,this.multiaddrs=i??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=Ep.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!!(t instanceof n&&this.peerId.equals(t.peerId)&&this.seqNumber===t.seqNumber&&function KK(n,e){const t=(r,i)=>r.toString().localeCompare(i.toString());return n.length===e.length&&e.sort(t)&&n.sort(t).every((r,i)=>e[i].equals(r))}(this.multiaddrs,t.multiaddrs))}}return n.createFromProtobuf=e=>{const t=Ep.decode(e),r=pa(t.peerId),i=(t.addresses??[]).map(o=>new vn(o.multiaddr));return new n({peerId:r,multiaddrs:i,seqNumber:t.seq})},n.DOMAIN="libp2p-peer-record",n.CODEC=$K,n})();const Ix="js-libp2p/0.0.0",Wn=Gt("libp2p:identify");class $E{constructor(e,t){this.components=e,this.started=!1,this.init=t,this.identifyProtocolStr=`/${t.protocolPrefix}/id/1.0.0`,this.identifyPushProtocolStr=`/${t.protocolPrefix}/id/push/1.0.0`,this.host={protocolVersion:`${t.protocolPrefix}/0.1.0`,...t.host},this.components.getConnectionManager().addEventListener("peer:connect",r=>{this.identify(r.detail).catch(Wn.error)}),this.components.getPeerStore().addEventListener("change:multiaddrs",r=>{const{peerId:i}=r.detail;this.components.getPeerId().equals(i)&&this.pushToPeerStore().catch(s=>Wn.error(s))}),this.components.getPeerStore().addEventListener("change:protocols",r=>{const{peerId:i}=r.detail;this.components.getPeerId().equals(i)&&this.pushToPeerStore().catch(s=>Wn.error(s))})}isStarted(){return this.started}start(){var e=this;return V(function*(){e.started||(yield e.components.getPeerStore().metadataBook.setValue(e.components.getPeerId(),"AgentVersion",_t(e.host.agentVersion)),yield e.components.getPeerStore().metadataBook.setValue(e.components.getPeerId(),"ProtocolVersion",_t(e.host.protocolVersion)),yield e.components.getRegistrar().handle(e.identifyProtocolStr,t=>{e._handleIdentify(t).catch(r=>{Wn.error(r)})},{maxInboundStreams:e.init.maxInboundStreams,maxOutboundStreams:e.init.maxOutboundStreams}),yield e.components.getRegistrar().handle(e.identifyPushProtocolStr,t=>{e._handlePush(t).catch(r=>{Wn.error(r)})},{maxInboundStreams:e.init.maxPushIncomingStreams,maxOutboundStreams:e.init.maxPushOutgoingStreams}),e.started=!0)})()}stop(){var e=this;return V(function*(){yield e.components.getRegistrar().unhandle(e.identifyProtocolStr),yield e.components.getRegistrar().unhandle(e.identifyPushProtocolStr),e.started=!1})()}push(e){var t=this;return V(function*(){const r=yield t.components.getPeerStore().addressBook.getRawEnvelope(t.components.getPeerId()),i=t.components.getAddressManager().getAddresses().map(a=>a.bytes),s=yield t.components.getPeerStore().protoBook.get(t.components.getPeerId()),o=e.map(function(){var a=V(function*(c){let m;const T=new Bi.TimeoutController(t.init.timeout);try{(0,Jr.setMaxListeners)?.(1/0,T.signal)}catch{}try{m=yield c.newStream([t.identifyPushProtocolStr],{signal:T.signal});const R=ga(m,T.signal);yield Ln([ac.encode({listenAddrs:i,signedPeerRecord:r,protocols:s})],to(),R,wa)}catch(R){Wn.error("could not push identify update to peer",R)}finally{m?.close(),T.clear()}});return function(c){return a.apply(this,arguments)}}());yield Promise.all(o)})()}pushToPeerStore(){var e=this;return V(function*(){if(!e.isStarted())return;const t=[];for(const r of e.components.getConnectionManager().getConnections()){const i=r.remotePeer;!(yield e.components.getPeerStore().get(i)).protocols.includes(e.identifyPushProtocolStr)||t.push(r)}yield e.push(t)})()}_identify(e,t={}){var r=this;return V(function*(){let i,o,s=t.signal;if(null==s){i=new Bi.TimeoutController(r.init.timeout),s=i.signal;try{(0,Jr.setMaxListeners)?.(1/0,i.signal)}catch{}}try{o=yield e.newStream([r.identifyProtocolStr],{signal:s});const a=ga(o,s),c=yield Ln([],a,Ms({maxDataLength:r.init.maxIdentifyMessageSize??8192}),function(){var m=V(function*(T){return yield nc(T)});return function(T){return m.apply(this,arguments)}}());if(null==c)throw se(new Error("No data could be retrieved"),Ie.ERR_CONNECTION_ENDED);try{return ac.decode(c)}catch(m){throw se(m,Ie.ERR_INVALID_MESSAGE)}}finally{i?.clear(),o?.close()}})()}identify(e,t={}){var r=this;return V(function*(){const i=yield r._identify(e,t),{publicKey:s,listenAddrs:o,protocols:a,observedAddr:c,signedPeerRecord:m,agentVersion:T,protocolVersion:R}=i;if(null==s)throw se(new Error("public key was missing from identify message"),Ie.ERR_MISSING_PUBLIC_KEY);const k=yield xu(s);if(!e.remotePeer.equals(k))throw se(new Error("identified peer does not match the expected peer"),Ie.ERR_INVALID_PEER);if(r.components.getPeerId().equals(k))throw se(new Error("identified peer is our own peer id?"),Ie.ERR_INVALID_PEER);const U=$E.getCleanMultiaddr(c);if(null!=m){Wn("received signed peer record from %p",k);try{const Q=yield Yi.openAndCertify(m,ku.DOMAIN);if(!Q.peerId.equals(k))throw se(new Error("identified peer does not match the expected peer"),Ie.ERR_INVALID_PEER);if(yield r.components.getPeerStore().addressBook.consumePeerRecord(Q))return yield r.components.getPeerStore().protoBook.set(k,a),null!=T&&(yield r.components.getPeerStore().metadataBook.setValue(k,"AgentVersion",_t(T))),null!=R&&(yield r.components.getPeerStore().metadataBook.setValue(k,"ProtocolVersion",_t(R))),void Wn("identify completed for peer %p and protocols %o",k,a)}catch(Q){Wn("received invalid envelope, discard it and fallback to listenAddrs is available",Q)}}else Wn("no signed peer record received from %p",k);Wn("falling back to legacy addresses from %p",k);try{yield r.components.getPeerStore().addressBook.set(k,o.map(Q=>new vn(Q)))}catch(Q){Wn.error("received invalid addrs",Q)}yield r.components.getPeerStore().protoBook.set(k,a),null!=T&&(yield r.components.getPeerStore().metadataBook.setValue(k,"AgentVersion",_t(T))),null!=R&&(yield r.components.getPeerStore().metadataBook.setValue(k,"ProtocolVersion",_t(R))),Wn("identify completed for peer %p and protocols %o",k,a),Wn("received observed address of %s",U?.toString())})()}_handleIdentify(e){var t=this;return V(function*(){const{connection:r,stream:i}=e,s=new Bi.TimeoutController(t.init.timeout);try{(0,Jr.setMaxListeners)?.(1/0,s.signal)}catch{}try{const o=t.components.getPeerId().publicKey??new Uint8Array(0),a=yield t.components.getPeerStore().get(t.components.getPeerId()),c=t.components.getAddressManager().getAddresses().map(k=>k.decapsulateCode(Nr("p2p").code));let m=a.peerRecordEnvelope;if(c.length>0&&null==m){const k=new ku({peerId:t.components.getPeerId(),multiaddrs:c}),U=yield Yi.seal(k,t.components.getPeerId());yield t.components.getPeerStore().addressBook.consumePeerRecord(U),m=U.marshal().subarray()}const T=ac.encode({protocolVersion:t.host.protocolVersion,agentVersion:t.host.agentVersion,publicKey:o,listenAddrs:c.map(k=>k.bytes),signedPeerRecord:m,observedAddr:r.remoteAddr.bytes,protocols:a.protocols}),R=ga(i,s.signal);yield Ln([T],to(),R,wa)}catch(o){Wn.error("could not respond to identify request",o)}finally{i.close(),s.clear()}})()}_handlePush(e){var t=this;return V(function*(){const{connection:r,stream:i}=e,s=new Bi.TimeoutController(t.init.timeout);try{(0,Jr.setMaxListeners)?.(1/0,s.signal)}catch{}let o;try{const c=ga(i,s.signal),m=yield Ln([],c,Ms({maxDataLength:t.init.maxIdentifyMessageSize??8192}),function(){var T=V(function*(R){return yield nc(R)});return function(R){return T.apply(this,arguments)}}());null!=m&&(o=ac.decode(m))}catch(c){return Wn.error("received invalid message",c)}finally{i.close(),s.clear()}if(null==o)return Wn.error("received invalid message");const a=r.remotePeer;if(t.components.getPeerId().equals(a))Wn("received push from ourselves?");else{if(Wn("received push from %p",a),null!=o.signedPeerRecord){Wn("received signedPeerRecord in push");try{const c=yield Yi.openAndCertify(o.signedPeerRecord,ku.DOMAIN);if(yield t.components.getPeerStore().addressBook.consumePeerRecord(c))return Wn("consumed signedPeerRecord sent in push"),void(yield t.components.getPeerStore().protoBook.set(a,o.protocols));Wn("failed to consume signedPeerRecord sent in push")}catch(c){Wn("received invalid envelope, discard it and fallback to listenAddrs is available",c)}}else Wn("did not receive signedPeerRecord in push");try{yield t.components.getPeerStore().addressBook.set(a,o.listenAddrs.map(c=>new vn(c)))}catch(c){Wn.error("received invalid addrs",c)}try{yield t.components.getPeerStore().protoBook.set(a,o.protocols)}catch(c){Wn.error("received invalid protocols",c)}Wn("handled push from %p",a)}})()}static getCleanMultiaddr(e){if(null!=e&&e.length>0)try{return new vn(e)}catch{}}}var wp,ao;!function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.identifier)throw new Error('Protocol error: required field "identifier" was not found in object');r.uint32(10),r.string(t.identifier),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={},s=null==r?t.len:t.pos+r;for(;t.pos>>3==1?i.identifier=t.string():t.skipType(7&o)}if(null==i.identifier)throw new Error('Protocol error: value for required field "identifier" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(wp||(wp={})),function(n){let e;var i;let t,r;(i=e=n.StatusCode||(n.StatusCode={})).OK="OK",i.NOT_FOUND="NOT_FOUND",i.ERROR="ERROR",function(i){i[i.OK=0]="OK",i[i.NOT_FOUND=1]="NOT_FOUND",i[i.ERROR=2]="ERROR"}(t||(t={})),function(i){i.codec=()=>Nh(t)}(e=n.StatusCode||(n.StatusCode={})),n.codec=()=>(null==r&&(r=fi((i,s,o={})=>{if(!1!==o.lengthDelimited&&s.fork(),null==i.status)throw new Error('Protocol error: required field "status" was not found in object');if(s.uint32(8),n.StatusCode.codec().encode(i.status,s),null==i.data)throw new Error('Protocol error: required field "data" was not found in object');s.uint32(18),s.bytes(i.data),!1!==o.lengthDelimited&&s.ldelim()},(i,s)=>{const o={},a=null==s?i.len:i.pos+s;for(;i.pos>>3){case 1:o.status=n.StatusCode.codec().decode(i);break;case 2:o.data=i.bytes();break;default:i.skipType(7&c)}}if(null==o.status)throw new Error('Protocol error: value for required field "status" was not found in protobuf');if(null==o.data)throw new Error('Protocol error: value for required field "data" was not found in protobuf');return o})),r),n.encode=i=>li(i,n.codec()),n.decode=i=>ui(i,n.codec())}(ao||(ao={}));const Tx=Gt("libp2p:fetch");class tj{constructor(e,t){this.started=!1,this.components=e,this.protocol=`/${t.protocolPrefix??"libp2p"}/fetch/0.0.1`,this.lookupFunctions=new Map,this.handleMessage=this.handleMessage.bind(this),this.init=t}start(){var e=this;return V(function*(){yield e.components.getRegistrar().handle(e.protocol,t=>{e.handleMessage(t).catch(r=>{Tx.error(r)}).finally(()=>{t.stream.close()})},{maxInboundStreams:e.init.maxInboundStreams,maxOutboundStreams:e.init.maxOutboundStreams}),e.started=!0})()}stop(){var e=this;return V(function*(){yield e.components.getRegistrar().unhandle(e.protocol),e.started=!1})()}isStarted(){return this.started}fetch(e,t,r={}){var i=this;return V(function*(){Tx("dialing %s to %p",i.protocol,e);const s=yield i.components.getConnectionManager().openConnection(e,r);let o,c,a=r.signal;if(null==a){o=new Bi.TimeoutController(i.init.timeout),a=o.signal;try{(0,Jr.setMaxListeners)?.(1/0,o.signal)}catch{}}try{c=yield s.newStream([i.protocol],{signal:a});const m=ga(c,a);return(yield Ln([wp.encode({identifier:t})],to(),m,Ms(),function(){var R=V(function*(k){const U=yield nc(k);if(null==U)throw se(new Error("No data received"),Ie.ERR_INVALID_MESSAGE);const Q=ao.decode(U);switch(Q.status){case ao.StatusCode.OK:return Q.data;case ao.StatusCode.NOT_FOUND:return null;case ao.StatusCode.ERROR:{const X=(new TextDecoder).decode(Q.data);throw se(new Error("Error in fetch protocol response: "+X),Ie.ERR_INVALID_PARAMETERS)}default:throw se(new Error("Unknown response status"),Ie.ERR_INVALID_MESSAGE)}});return function(k){return R.apply(this,arguments)}}()))??null}finally{o?.clear(),c?.close()}})()}handleMessage(e){var t=this;return V(function*(){const{stream:r}=e,i=t;yield Ln(r,Ms(),function(){var s=un(function*(o){const a=yield ct(nc(o));if(null==a)throw se(new Error("No data received"),Ie.ERR_INVALID_MESSAGE);const c=wp.decode(a);let m;const T=i._getLookupFunction(c.identifier);if(null!=T){const R=yield ct(T(c.identifier));m=null!=R?{status:ao.StatusCode.OK,data:R}:{status:ao.StatusCode.NOT_FOUND,data:new Uint8Array(0)}}else{const R=(new TextEncoder).encode("No lookup function registered for key: "+c.identifier);m={status:ao.StatusCode.ERROR,data:R}}yield ao.encode(m)});return function(o){return s.apply(this,arguments)}}(),to(),r)})()}_getLookupFunction(e){for(const t of this.lookupFunctions.keys())if(e.startsWith(t))return this.lookupFunctions.get(t)}registerLookupFunction(e,t){if(this.lookupFunctions.has(e))throw se(new Error("Fetch protocol handler for key prefix '"+e+"' already registered"),Ie.ERR_KEY_ALREADY_EXISTS);this.lookupFunctions.set(e,t)}unregisterLookupFunction(e,t){null!=t&&this.lookupFunctions.get(e)!==t||this.lookupFunctions.delete(e)}}const Ax=Gt("libp2p:ping");class sj{constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix}/ping/1.0.0`,this.init=t}start(){var e=this;return V(function*(){yield e.components.getRegistrar().handle(e.protocol,e.handleMessage,{maxInboundStreams:e.init.maxInboundStreams,maxOutboundStreams:e.init.maxOutboundStreams}),e.started=!0})()}stop(){var e=this;return V(function*(){yield e.components.getRegistrar().unhandle(e.protocol),e.started=!1})()}isStarted(){return this.started}handleMessage(e){const{stream:t}=e;Ln(t,t).catch(r=>{Ax.error(r)})}ping(e,t={}){var r=this;return V(function*(){Ax("dialing %s to %p",r.protocol,e);const i=Date.now(),s=sf(32),o=yield r.components.getConnectionManager().openConnection(e,t);let a,m,c=t.signal;if(null==c){a=new Bi.TimeoutController(r.init.timeout),c=a.signal;try{(0,Jr.setMaxListeners)?.(1/0,a.signal)}catch{}}try{m=yield o.newStream([r.protocol],{signal:c});const T=ga(m,c),R=yield Ln([s],T,function(){var U=V(function*(Q){return yield nc(Q)});return function(Q){return U.apply(this,arguments)}}()),k=Date.now();if(null==R||!$r(s,R.subarray()))throw se(new Error("Received wrong ping ack"),Ie.ERR_WRONG_PING_ACK);return k-i}finally{a?.clear(),m?.close()}})()}}function GE(){return(GE=V(function*(){throw new Error("Not supported in browsers")})).apply(this,arguments)}function cj(n){const{address:e}=n.nodeAddress();return function aj(n){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(n)||/^::1$/.test(n)}(e)}const WE=Gt("libp2p:nat");function uj(n=1024,e=65535){return Math.floor(Math.random()*(e-n+1)+n)}class lj{constructor(e,t){if(this.components=e,this.started=!1,this.enabled=t.enabled,this.externalAddress=t.externalAddress,this.localAddress=t.localAddress,this.description=t.description??`libp2p@0.0.0 ${this.components.getPeerId().toString()}`,this.ttl=t.ttl??7200,this.keepAlive=t.keepAlive??!0,this.gateway=t.gateway,this.ttl<7200)throw se(new Error("NatManager ttl should be at least 7200 seconds"),Ie.ERR_INVALID_PARAMETERS)}isStarted(){return this.started}start(){}afterStart(){fp||!this.enabled||this.started||(this.started=!0,this._start().catch(e=>{WE.error(e)}))}_start(){var e=this;return V(function*(){const t=e.components.getTransportManager().getAddrs();for(const r of t){const{family:i,host:s,port:o,transport:a}=r.toOptions();if(!r.isThinWaistAddress()||"tcp"!==a||cj(r)||4!==i)continue;const c=yield e._getClient(),m=e.externalAddress??(yield c.externalIp());if(GA(m))throw new Error(`${m} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`);const T=uj();WE(`opening uPnP connection from ${m}:${T} to ${s}:${o}`),yield c.map({publicPort:T,localPort:o,localAddress:e.localAddress,protocol:"TCP"===a.toUpperCase()?"TCP":"UDP"}),e.components.getAddressManager().addObservedAddr(vn.fromNodeAddress({family:4,address:m,port:T},a))}})()}_getClient(){var e=this;return V(function*(){return null!=e.client||(e.client=yield function oj(){return GE.apply(this,arguments)}({description:e.description,ttl:e.ttl,keepAlive:e.keepAlive,gateway:e.gateway})),e.client})()}stop(){var e=this;return V(function*(){if(!fp&&null!=e.client)try{yield e.client.close(),e.client=void 0}catch(t){WE.error(t)}})()}}const fj=Gt("libp2p:peer-record-updater");class dj{constructor(e){this.components=e,this.started=!1,this.update=this.update.bind(this)}isStarted(){return this.started}start(){var e=this;return V(function*(){e.started=!0,e.components.getTransportManager().addEventListener("listener:listening",e.update),e.components.getTransportManager().addEventListener("listener:close",e.update),e.components.getAddressManager().addEventListener("change:addresses",e.update)})()}stop(){var e=this;return V(function*(){e.started=!1,e.components.getTransportManager().removeEventListener("listener:listening",e.update),e.components.getTransportManager().removeEventListener("listener:close",e.update),e.components.getAddressManager().removeEventListener("change:addresses",e.update)})()}update(){var e=this;Promise.resolve().then(V(function*(){const t=new ku({peerId:e.components.getPeerId(),multiaddrs:e.components.getAddressManager().getAddresses().map(i=>i.decapsulateCode(Nr("p2p").code))}),r=yield Yi.seal(t,e.components.getPeerId());yield e.components.getPeerStore().addressBook.consumePeerRecord(r)})).catch(t=>{fj.error("Could not update self peer record: %o",t)})}}class hj{constructor(e){this.dht=e}findPeer(e,t={}){var r=this;return V(function*(){var o,i=!1,s=!1;try{for(var c,a=Tt(r.dht.findPeer(e,t));i=!(c=yield a.next()).done;i=!1){const m=c.value;if("FINAL_PEER"===m.name)return m.peer}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield a.return())}finally{if(s)throw o}}throw se(new Error(Cn.NOT_FOUND),Ie.ERR_NOT_FOUND)})()}getClosestPeers(e,t={}){var r=this;return un(function*(){var o,i=!1,s=!1;try{for(var c,a=Tt(r.dht.getClosestPeers(e,t));i=!(c=yield ct(a.next())).done;i=!1){const m=c.value;"PEER_RESPONSE"===m.name&&(yield*jr(Tt(m.closer),ct))}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield ct(a.return()))}finally{if(s)throw o}}})()}}const Kn=Gt("libp2p:peer-store:address-book"),bp="change:multiaddrs";function pj(){return QE.apply(this,arguments)}function QE(){return(QE=V(function*(){return!0})).apply(this,arguments)}class gj{constructor(e,t,r){this.dispatchEvent=e,this.store=t,this.addressFilter=r??pj}consumePeerRecord(e){var t=this;return V(function*(){Kn.trace("consumePeerRecord await write lock");const r=yield t.store.lock.writeLock();let i,s,o;Kn.trace("consumePeerRecord got write lock");try{let a;try{a=ku.createFromProtobuf(e.payload)}catch{return Kn.error("invalid peer record received"),!1}i=a.peerId;const c=a.multiaddrs;if(!i.equals(e.peerId))return Kn("signing key does not match PeerId in the PeerRecord"),!1;if(null==c||0===c.length)return!1;if((yield t.store.has(i))&&(s=yield t.store.load(i),null!=s.peerRecordEnvelope)){const T=yield Yi.createFromProtobuf(s.peerRecordEnvelope),R=ku.createFromProtobuf(T.payload);if(R.seqNumber>=a.seqNumber)return Kn("sequence number was lower or equal to existing sequence number - stored: %d received: %d",R.seqNumber,a.seqNumber),!1}const m=yield YE(i,c,t.addressFilter,!0);o=yield t.store.patchOrCreate(i,{addresses:m,peerRecordEnvelope:e.marshal().subarray()}),Kn("stored provided peer record for %p",a.peerId)}finally{Kn.trace("consumePeerRecord release write lock"),r()}return t.dispatchEvent(new rn(bp,{detail:{peerId:i,multiaddrs:o.addresses.map(({multiaddr:a})=>a),oldMultiaddrs:null==s?[]:s.addresses.map(({multiaddr:a})=>a)}})),!0})()}getRawEnvelope(e){var t=this;return V(function*(){Kn.trace("getRawEnvelope await read lock");const r=yield t.store.lock.readLock();Kn.trace("getRawEnvelope got read lock");try{return(yield t.store.load(e)).peerRecordEnvelope}catch(i){if("ERR_NOT_FOUND"!==i.code)throw i}finally{Kn.trace("getRawEnvelope release read lock"),r()}})()}getPeerRecord(e){var t=this;return V(function*(){const r=yield t.getRawEnvelope(e);if(null!=r)return yield Yi.createFromProtobuf(r)})()}get(e){var t=this;return V(function*(){e=Zr(e),Kn.trace("get wait for read lock");const r=yield t.store.lock.readLock();Kn.trace("get got read lock");try{return(yield t.store.load(e)).addresses}catch(i){if("ERR_NOT_FOUND"!==i.code)throw i}finally{Kn.trace("get release read lock"),r()}return[]})()}set(e,t){var r=this;return V(function*(){if(e=Zr(e),!Array.isArray(t))throw Kn.error("multiaddrs must be an array of Multiaddrs"),se(new Error("multiaddrs must be an array of Multiaddrs"),"ERR_INVALID_PARAMETERS");Kn.trace("set await write lock");const i=yield r.store.lock.writeLock();Kn.trace("set got write lock");let o,a,s=!1;try{const c=yield YE(e,t,r.addressFilter);if(0===c.length)return;try{if(o=yield r.store.load(e),s=!0,new Set([...c.map(({multiaddr:m})=>m.toString()),...o.addresses.map(({multiaddr:m})=>m.toString())]).size===o.addresses.length&&c.length===o.addresses.length)return}catch(m){if("ERR_NOT_FOUND"!==m.code)throw m}a=yield r.store.patchOrCreate(e,{addresses:c}),Kn("set multiaddrs for %p",e)}finally{Kn.trace("set multiaddrs for %p",e),Kn("set release write lock"),i()}r.dispatchEvent(new rn(bp,{detail:{peerId:e,multiaddrs:a.addresses.map(c=>c.multiaddr),oldMultiaddrs:null==o?[]:o.addresses.map(({multiaddr:c})=>c)}})),s||r.dispatchEvent(new rn("peer",{detail:{id:e,multiaddrs:a.addresses.map(c=>c.multiaddr),protocols:a.protocols}}))})()}add(e,t){var r=this;return V(function*(){if(e=Zr(e),!Array.isArray(t))throw Kn.error("multiaddrs must be an array of Multiaddrs"),se(new Error("multiaddrs must be an array of Multiaddrs"),"ERR_INVALID_PARAMETERS");Kn.trace("add await write lock");const i=yield r.store.lock.writeLock();let s,o,a;Kn.trace("add got write lock");try{const c=yield YE(e,t,r.addressFilter);if(0===c.length)return;try{if(o=yield r.store.load(e),s=!0,new Set([...c.map(({multiaddr:m})=>m.toString()),...o.addresses.map(({multiaddr:m})=>m.toString())]).size===o.addresses.length)return}catch(m){if("ERR_NOT_FOUND"!==m.code)throw m}a=yield r.store.mergeOrCreate(e,{addresses:c}),Kn("added multiaddrs for %p",e)}finally{Kn.trace("set release write lock"),i()}r.dispatchEvent(new rn(bp,{detail:{peerId:e,multiaddrs:a.addresses.map(c=>c.multiaddr),oldMultiaddrs:null==o?[]:o.addresses.map(({multiaddr:c})=>c)}})),!0===s&&r.dispatchEvent(new rn("peer",{detail:{id:e,multiaddrs:a.addresses.map(c=>c.multiaddr),protocols:a.protocols}}))})()}delete(e){var t=this;return V(function*(){e=Zr(e),Kn.trace("delete await write lock");const r=yield t.store.lock.writeLock();let i;Kn.trace("delete got write lock");try{try{i=yield t.store.load(e)}catch(s){if("ERR_NOT_FOUND"!==s.code)throw s}yield t.store.patchOrCreate(e,{addresses:[]})}finally{Kn.trace("delete release write lock"),r()}null!=i&&t.dispatchEvent(new rn(bp,{detail:{peerId:e,multiaddrs:[],oldMultiaddrs:null==i?[]:i.addresses.map(({multiaddr:s})=>s)}}))})()}}function YE(n,e,t){return ZE.apply(this,arguments)}function ZE(){return ZE=V(function*(n,e,t,r=!1){return yield Ln(e,i=>RE(i,s=>{if(!vn.isMultiaddr(s))throw Kn.error("multiaddr must be an instance of Multiaddr"),se(new Error("multiaddr must be an instance of Multiaddr"),"ERR_INVALID_PARAMETERS")}),i=>Ks(i,function(){var s=V(function*(o){return yield t(n,o)});return function(o){return s.apply(this,arguments)}}()),i=>fE(i,s=>({multiaddr:new vn(s.toString()),isCertified:r})),function(){var i=V(function*(s){return yield Ea(s)});return function(s){return i.apply(this,arguments)}}())}),ZE.apply(this,arguments)}const co=Gt("libp2p:peer-store:key-book"),xx="change:pubkey";class yj{constructor(e,t){this.dispatchEvent=e,this.store=t}set(e,t){var r=this;return V(function*(){if(e=Zr(e),!(t instanceof Uint8Array))throw co.error("publicKey must be an instance of Uint8Array to store data"),se(new Error("publicKey must be an instance of PublicKey"),"ERR_INVALID_PARAMETERS");co.trace("set await write lock");const i=yield r.store.lock.writeLock();co.trace("set got write lock");let o,s=!1;try{try{if(o=yield r.store.load(e),null!=o.pubKey&&$r(o.pubKey,t))return}catch(a){if("ERR_NOT_FOUND"!==a.code)throw a}yield r.store.patchOrCreate(e,{pubKey:t}),s=!0}finally{co.trace("set release write lock"),i()}s&&r.dispatchEvent(new rn(xx,{detail:{peerId:e,publicKey:t,oldPublicKey:o?.pubKey}}))})()}get(e){var t=this;return V(function*(){e=Zr(e),co.trace("get await write lock");const r=yield t.store.lock.readLock();co.trace("get got write lock");try{return(yield t.store.load(e)).pubKey}catch(i){if("ERR_NOT_FOUND"!==i.code)throw i}finally{co("get release write lock"),r()}})()}delete(e){var t=this;return V(function*(){e=Zr(e),co.trace("delete await write lock");const r=yield t.store.lock.writeLock();let i;co.trace("delete got write lock");try{try{i=yield t.store.load(e)}catch(s){if("ERR_NOT_FOUND"!==s.code)throw s}yield t.store.patchOrCreate(e,{pubKey:void 0})}catch(s){if("ERR_NOT_FOUND"!==s.code)throw s}finally{co.trace("delete release write lock"),r()}t.dispatchEvent(new rn(xx,{detail:{peerId:e,publicKey:void 0,oldPublicKey:i?.pubKey}}))})()}}const Mr=Gt("libp2p:peer-store:metadata-book"),_p="change:metadata";class mj{constructor(e,t){this.dispatchEvent=e,this.store=t}get(e){var t=this;return V(function*(){e=Zr(e),Mr.trace("get await read lock");const r=yield t.store.lock.readLock();Mr.trace("get got read lock");try{return(yield t.store.load(e)).metadata}catch(i){if("ERR_NOT_FOUND"!==i.code)throw i}finally{Mr.trace("get release read lock"),r()}return new Map})()}getValue(e,t){var r=this;return V(function*(){e=Zr(e),Mr.trace("getValue await read lock");const i=yield r.store.lock.readLock();Mr.trace("getValue got read lock");try{return(yield r.store.load(e)).metadata.get(t)}catch(s){if("ERR_NOT_FOUND"!==s.code)throw s}finally{Mr.trace("getValue release write lock"),i()}})()}set(e,t){var r=this;return V(function*(){if(e=Zr(e),!(t instanceof Map))throw Mr.error("valid metadata must be provided to store data"),se(new Error("valid metadata must be provided"),"ERR_INVALID_PARAMETERS");Mr.trace("set await write lock");const i=yield r.store.lock.writeLock();let s;Mr.trace("set got write lock");try{try{s=yield r.store.load(e)}catch(o){if("ERR_NOT_FOUND"!==o.code)throw o}yield r.store.mergeOrCreate(e,{metadata:t})}finally{Mr.trace("set release write lock"),i()}r.dispatchEvent(new rn(_p,{detail:{peerId:e,metadata:t,oldMetadata:null==s?new Map:s.metadata}}))})()}setValue(e,t,r){var i=this;return V(function*(){if(e=Zr(e),"string"!=typeof t||!(r instanceof Uint8Array))throw Mr.error("valid key and value must be provided to store data"),se(new Error("valid key and value must be provided"),"ERR_INVALID_PARAMETERS");Mr.trace("setValue await write lock");const s=yield i.store.lock.writeLock();let o,a;Mr.trace("setValue got write lock");try{try{o=yield i.store.load(e);const c=o.metadata.get(t);if(null!=c&&$r(r,c))return}catch(c){if("ERR_NOT_FOUND"!==c.code)throw c}a=yield i.store.mergeOrCreate(e,{metadata:new Map([[t,r]])})}finally{Mr.trace("setValue release write lock"),s()}i.dispatchEvent(new rn(_p,{detail:{peerId:e,metadata:a.metadata,oldMetadata:null==o?new Map:o.metadata}}))})()}delete(e){var t=this;return V(function*(){e=Zr(e),Mr.trace("delete await write lock");const r=yield t.store.lock.writeLock();let i;Mr.trace("delete got write lock");try{try{i=yield t.store.load(e)}catch(s){if("ERR_NOT_FOUND"!==s.code)throw s}null!=i&&(yield t.store.patch(e,{metadata:new Map}))}finally{Mr.trace("delete release write lock"),r()}null!=i&&t.dispatchEvent(new rn(_p,{detail:{peerId:e,metadata:new Map,oldMetadata:i.metadata}}))})()}deleteValue(e,t){var r=this;return V(function*(){e=Zr(e),Mr.trace("deleteValue await write lock");const i=yield r.store.lock.writeLock();let s,o;Mr.trace("deleteValue got write lock");try{o=yield r.store.load(e),s=o.metadata,s.delete(t),yield r.store.patch(e,{metadata:s})}catch(a){if("ERR_NOT_FOUND"!==a.code)throw a}finally{Mr.trace("deleteValue release write lock"),i()}null!=s&&r.dispatchEvent(new rn(_p,{detail:{peerId:e,metadata:s,oldMetadata:null==o?new Map:o.metadata}}))})()}}const Or=Gt("libp2p:peer-store:proto-book"),Dp="change:protocols";class vj{constructor(e,t){this.dispatchEvent=e,this.store=t}get(e){var t=this;return V(function*(){Or.trace("get wait for read lock");const r=yield t.store.lock.readLock();Or.trace("get got read lock");try{return(yield t.store.load(e)).protocols}catch(i){if("ERR_NOT_FOUND"!==i.code)throw i}finally{Or.trace("get release read lock"),r()}return[]})()}set(e,t){var r=this;return V(function*(){if(e=Zr(e),!Array.isArray(t))throw Or.error("protocols must be provided to store data"),se(new Error("protocols must be provided"),"ERR_INVALID_PARAMETERS");Or.trace("set await write lock");const i=yield r.store.lock.writeLock();let s,o;Or.trace("set got write lock");try{try{if(s=yield r.store.load(e),new Set([...t]).size===s.protocols.length)return}catch(a){if("ERR_NOT_FOUND"!==a.code)throw a}o=yield r.store.patchOrCreate(e,{protocols:t}),Or("stored provided protocols for %p",e)}finally{Or.trace("set release write lock"),i()}r.dispatchEvent(new rn(Dp,{detail:{peerId:e,protocols:o.protocols,oldProtocols:null==s?[]:s.protocols}}))})()}add(e,t){var r=this;return V(function*(){if(e=Zr(e),!Array.isArray(t))throw Or.error("protocols must be provided to store data"),se(new Error("protocols must be provided"),"ERR_INVALID_PARAMETERS");Or.trace("add await write lock");const i=yield r.store.lock.writeLock();let s,o;Or.trace("add got write lock");try{try{if(s=yield r.store.load(e),new Set([...s.protocols,...t]).size===s.protocols.length)return}catch(a){if("ERR_NOT_FOUND"!==a.code)throw a}o=yield r.store.mergeOrCreate(e,{protocols:t}),Or("added provided protocols for %p",e)}finally{Or.trace("add release write lock"),i()}r.dispatchEvent(new rn(Dp,{detail:{peerId:e,protocols:o.protocols,oldProtocols:null==s?[]:s.protocols}}))})()}remove(e,t){var r=this;return V(function*(){if(e=Zr(e),!Array.isArray(t))throw Or.error("protocols must be provided to store data"),se(new Error("protocols must be provided"),"ERR_INVALID_PARAMETERS");Or.trace("remove await write lock");const i=yield r.store.lock.writeLock();let s,o;Or.trace("remove got write lock");try{try{s=yield r.store.load(e);const a=new Set(s.protocols);for(const c of t)a.delete(c);if(s.protocols.length===a.size)return;t=Array.from(a)}catch(a){if("ERR_NOT_FOUND"!==a.code)throw a}o=yield r.store.patchOrCreate(e,{protocols:t})}finally{Or.trace("remove release write lock"),i()}r.dispatchEvent(new rn(Dp,{detail:{peerId:e,protocols:o.protocols,oldProtocols:null==s?[]:s.protocols}}))})()}delete(e){var t=this;return V(function*(){e=Zr(e),Or.trace("delete await write lock");const r=yield t.store.lock.writeLock();let i;Or.trace("delete got write lock");try{try{i=yield t.store.load(e)}catch(s){if("ERR_NOT_FOUND"!==s.code)throw s}yield t.store.patchOrCreate(e,{protocols:[]})}finally{Or.trace("delete release write lock"),r()}null!=i&&t.dispatchEvent(new rn(Dp,{detail:{peerId:e,protocols:[],oldProtocols:i.protocols}}))})()}}var Sp,Ip,Cp;!function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.addresses)throw new Error('Protocol error: required field "addresses" was not found in object');for(const s of t.addresses)r.uint32(10),Ip.codec().encode(s,r);if(null==t.protocols)throw new Error('Protocol error: required field "protocols" was not found in object');for(const s of t.protocols)r.uint32(18),r.string(s);if(null==t.metadata)throw new Error('Protocol error: required field "metadata" was not found in object');for(const s of t.metadata)r.uint32(26),Cp.codec().encode(s,r);null!=t.pubKey&&(r.uint32(34),r.bytes(t.pubKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={addresses:[],protocols:[],metadata:[]},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:i.addresses.push(Ip.codec().decode(t,t.uint32()));break;case 2:i.protocols.push(t.string());break;case 3:i.metadata.push(Cp.codec().decode(t,t.uint32()));break;case 4:i.pubKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;default:t.skipType(7&o)}}return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(Sp||(Sp={})),function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.multiaddr)throw new Error('Protocol error: required field "multiaddr" was not found in object');r.uint32(10),r.bytes(t.multiaddr),null!=t.isCertified&&(r.uint32(16),r.bool(t.isCertified)),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={multiaddr:new Uint8Array(0)},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:i.multiaddr=t.bytes();break;case 2:i.isCertified=t.bool();break;default:t.skipType(7&o)}}if(null==i.multiaddr)throw new Error('Protocol error: value for required field "multiaddr" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(Ip||(Ip={})),function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.key)throw new Error('Protocol error: required field "key" was not found in object');if(r.uint32(10),r.string(t.key),null==t.value)throw new Error('Protocol error: required field "value" was not found in object');r.uint32(18),r.bytes(t.value),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={key:"",value:new Uint8Array(0)},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:i.key=t.string();break;case 2:i.value=t.bytes();break;default:t.skipType(7&o)}}if(null==i.key)throw new Error('Protocol error: value for required field "key" was not found in protobuf');if(null==i.value)throw new Error('Protocol error: value for required field "value" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(Cp||(Cp={}));var Ej=N(2005);class Rx extends Error{constructor(e){super(e),this.name="TimeoutError"}}class wj extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const Px=n=>void 0===globalThis.DOMException?new wj(n):new DOMException(n),Nx=n=>{const e=void 0===n.reason?Px("This operation was aborted."):n.reason;return e instanceof Error?e:Px(e)};function Mx(n,e,t,r){let i;const s=new Promise((o,a)=>{if("number"!=typeof e||1!==Math.sign(e))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e!==Number.POSITIVE_INFINITY){if((r={customTimers:{setTimeout,clearTimeout},...r}).signal){const{signal:c}=r;c.aborted&&a(Nx(c)),c.addEventListener("abort",()=>{a(Nx(c))})}i=r.customTimers.setTimeout.call(void 0,()=>{if("function"==typeof t){try{o(t())}catch(T){a(T)}return}const m=t instanceof Error?t:new Rx("string"==typeof t?t:`Promise timed out after ${e} milliseconds`);"function"==typeof n.cancel&&n.cancel(),a(m)},e),V(function*(){try{o(yield n)}catch(c){a(c)}finally{r.customTimers.clearTimeout.call(void 0,i)}})()}else o(n)});return s.clear=()=>{clearTimeout(i),i=void 0},s}var jo,cc=function(n,e,t,r){if("a"===t&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===t?r:"a"===t?r.call(n):r?r.value:e.get(n)};class _j{constructor(){jo.set(this,[])}enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,run:e};if(this.size&&cc(this,jo,"f")[this.size-1].priority>=t.priority)return void cc(this,jo,"f").push(r);const i=function bj(n,e,t){let r=0,i=n.length;for(;i>0;){const s=Math.trunc(i/2);let o=r+s;t(n[o],e)<=0?(r=++o,i-=s+1):i=s}return r}(cc(this,jo,"f"),r,(s,o)=>o.priority-s.priority);cc(this,jo,"f").splice(i,0,r)}dequeue(){return cc(this,jo,"f").shift()?.run}filter(e){return cc(this,jo,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return cc(this,jo,"f").length}}jo=new WeakMap;var Dr,Mf,Of,Ia,Tp,Lf,Ap,$s,kf,Zi,xp,Xi,Bf,Ca,Rp,Ox,Lx,kx,Bx,Fx,Ux,Pp,XE,JE,Np,Mp,pr=function(n,e,t,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?n!==e||!i:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(n,t):i?i.value=t:e.set(n,t),t},gt=function(n,e,t,r){if("a"===t&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===t?r:"a"===t?r.call(n):r?r.value:e.get(n)};const Dj=new Rx;class Sj extends Error{}class Vx extends Ej{constructor(e){var t,r,i,s;if(super(),Dr.add(this),Mf.set(this,void 0),Of.set(this,void 0),Ia.set(this,0),Tp.set(this,void 0),Lf.set(this,void 0),Ap.set(this,0),$s.set(this,void 0),kf.set(this,void 0),Zi.set(this,void 0),xp.set(this,void 0),Xi.set(this,0),Bf.set(this,void 0),Ca.set(this,void 0),Rp.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:_j,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(s=null===(i=e.interval)||void 0===i?void 0:i.toString())&&void 0!==s?s:""}\` (${typeof e.interval})`);pr(this,Mf,e.carryoverConcurrencyCount,"f"),pr(this,Of,e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,"f"),pr(this,Tp,e.intervalCap,"f"),pr(this,Lf,e.interval,"f"),pr(this,Zi,new e.queueClass,"f"),pr(this,xp,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,pr(this,Rp,!0===e.throwOnTimeout,"f"),pr(this,Ca,!1===e.autoStart,"f")}get concurrency(){return gt(this,Bf,"f")}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);pr(this,Bf,e,"f"),gt(this,Dr,"m",Np).call(this)}add(e,t={}){var r=this;return V(function*(){return new Promise((i,s)=>{const o=function(){var a=V(function*(){var c,m,T;pr(r,Xi,(m=gt(r,Xi,"f"),++m),"f"),pr(r,Ia,(T=gt(r,Ia,"f"),++T),"f");try{if(null!==(c=t.signal)&&void 0!==c&&c.aborted)return void s(new Sj("The task was aborted."));const k=yield void 0===r.timeout&&void 0===t.timeout?e({signal:t.signal}):Mx(Promise.resolve(e({signal:t.signal})),void 0===t.timeout?r.timeout:t.timeout,()=>{(void 0===t.throwOnTimeout?gt(r,Rp,"f"):t.throwOnTimeout)&&s(Dj)});i(k),r.emit("completed",k)}catch(R){s(R),r.emit("error",R)}gt(r,Dr,"m",kx).call(r)});return function(){return a.apply(this,arguments)}}();gt(r,Zi,"f").enqueue(o,t),gt(r,Dr,"m",Pp).call(r),r.emit("add")})})()}addAll(e,t){var r=this;return V(function*(){return Promise.all(e.map(function(){var i=V(function*(s){return r.add(s,t)});return function(s){return i.apply(this,arguments)}}()))})()}start(){return gt(this,Ca,"f")?(pr(this,Ca,!1,"f"),gt(this,Dr,"m",Np).call(this),this):this}pause(){pr(this,Ca,!0,"f")}clear(){pr(this,Zi,new(gt(this,xp,"f")),"f")}onEmpty(){var e=this;return V(function*(){0!==gt(e,Zi,"f").size&&(yield gt(e,Dr,"m",Mp).call(e,"empty"))})()}onSizeLessThan(e){var t=this;return V(function*(){gt(t,Zi,"f").sizegt(t,Zi,"f").size{gt(this,Dr,"m",Fx).call(this)},t),"f"),!0;pr(this,Ia,gt(this,Mf,"f")?gt(this,Xi,"f"):0,"f")}return!1},Pp=function(){if(0===gt(this,Zi,"f").size)return gt(this,$s,"f")&&clearInterval(gt(this,$s,"f")),pr(this,$s,void 0,"f"),gt(this,Dr,"m",Bx).call(this),!1;if(!gt(this,Ca,"f")){const e=!gt(this,Dr,"a",Ux);if(gt(this,Dr,"a",Ox)&>(this,Dr,"a",Lx)){const t=gt(this,Zi,"f").dequeue();return!!t&&(this.emit("active"),t(),e&>(this,Dr,"m",XE).call(this),!0)}}return!1},XE=function(){gt(this,Of,"f")||void 0!==gt(this,$s,"f")||(pr(this,$s,setInterval(()=>{gt(this,Dr,"m",JE).call(this)},gt(this,Lf,"f")),"f"),pr(this,Ap,Date.now()+gt(this,Lf,"f"),"f"))},JE=function(){0===gt(this,Ia,"f")&&0===gt(this,Xi,"f")&>(this,$s,"f")&&(clearInterval(gt(this,$s,"f")),pr(this,$s,void 0,"f")),pr(this,Ia,gt(this,Mf,"f")?gt(this,Xi,"f"):0,"f"),gt(this,Dr,"m",Np).call(this)},Np=function(){for(;gt(this,Dr,"m",Pp).call(this););},Mp=function(){var n=V(function*(t,r){return new Promise(i=>{const s=()=>{r&&!r()||(this.off(t,s),i())};this.on(t,s)})});return function e(t,r){return n.apply(this,arguments)}}();class Ij extends Error{constructor(e){super(e),this.name="TimeoutError"}}class Cj extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const Hx=n=>void 0===globalThis.DOMException?new Cj(n):new DOMException(n),Kx=n=>{const e=void 0===n.reason?Hx("This operation was aborted."):n.reason;return e instanceof Error?e:Hx(e)};function Tj(n,e){const{milliseconds:t,fallback:r,message:i,customTimers:s={setTimeout,clearTimeout}}=e;let o;const a=new Promise((c,m)=>{if("number"!=typeof t||1!==Math.sign(t))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t!==Number.POSITIVE_INFINITY){if(e.signal){const{signal:T}=e;T.aborted&&m(Kx(T)),T.addEventListener("abort",()=>{m(Kx(T))})}o=s.setTimeout.call(void 0,()=>{if(r){try{c(r())}catch(k){m(k)}return}const R=i instanceof Error?i:new Ij("string"==typeof i?i:`Promise timed out after ${t} milliseconds`);"function"==typeof n.cancel&&n.cancel(),m(R)},t),V(function*(){try{c(yield n)}catch(T){m(T)}finally{s.clearTimeout.call(void 0,o)}})()}else c(n)});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}const jx="lock:worker:request-read",$x="lock:worker:release-read",Gx="lock:master:grant-read",zx="lock:worker:request-write",Wx="lock:worker:release-write",qx="lock:master:grant-write",Ta={},Bu=n=>{n.addEventListener("message",e=>{Bu.dispatchEvent("message",n,e)}),null!=n.port&&n.port.addEventListener("message",e=>{Bu.dispatchEvent("message",n,e)})};Bu.addEventListener=(n,e)=>{null==Ta[n]&&(Ta[n]=[]),Ta[n].push(e)},Bu.removeEventListener=(n,e)=>{null!=Ta[n]&&(Ta[n]=Ta[n].filter(t=>t===e))},Bu.dispatchEvent=function(n,e,t){null!=Ta[n]&&Ta[n].forEach(r=>r(e,t))};const Qx=Bu,Yx=(n,e,t,r,i)=>(s,o)=>{if(o.data.type!==t)return;const a={type:o.data.type,name:o.data.name,identifier:o.data.identifier};var c;n.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:(c=V(function*(){return s.postMessage({type:i,name:a.name,identifier:a.identifier}),yield new Promise(m=>{const T=R=>{null!=R&&null!=R.data&&R.data.type===r&&R.data.identifier===a.identifier&&(s.removeEventListener("message",T),m())};s.addEventListener("message",T)})}),function(){return c.apply(this,arguments)})}}))},Zx=(n,e,t,r)=>V(function*(){const i=((n=21)=>crypto.getRandomValues(new Uint8Array(n)).reduce((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""))();return globalThis.postMessage({type:e,identifier:i,name:n}),yield new Promise(s=>{const o=a=>{null!=a&&null!=a.data&&a.data.type===t&&a.data.identifier===i&&(globalThis.removeEventListener("message",o),s(()=>{globalThis.postMessage({type:r,identifier:i,name:n})}))};globalThis.addEventListener("message",o)})}),Pj={singleProcess:!1},uc={};let Aa;function ew(n,e){return tw.apply(this,arguments)}function tw(){return tw=V(function*(n,e){let t;const r=new Promise(i=>{t=i});return n.add(V(function*(){return yield Tj(V(function*(){return yield new Promise(i=>{t(()=>{i()})})})(),{milliseconds:e.timeout})})),yield r}),tw.apply(this,arguments)}const Oj={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};const Xx=Gt("libp2p:peer-store:store"),Jx="/peers/";class kj{constructor(){this.components=new ko,this.lock=function Lj(n){const e=Object.assign({},Oj,n);return null==Aa&&(Aa=(n=>{if(n=Object.assign({},Pj,n),Boolean(globalThis.document)||n.singleProcess){const t=new EventTarget;return Qx.addEventListener("message",Yx(t,"requestReadLock",jx,$x,Gx)),Qx.addEventListener("message",Yx(t,"requestWriteLock",zx,Wx,qx)),t}return{isWorker:!0,readLock:t=>Zx(t,jx,Gx,$x),writeLock:t=>Zx(t,zx,qx,Wx)}})(e),!0!==Aa.isWorker&&(Aa.addEventListener("requestReadLock",t=>{null!=uc[t.data.name]&&uc[t.data.name].readLock().then(function(){var r=V(function*(i){return yield t.data.handler().finally(()=>i())});return function(i){return r.apply(this,arguments)}}())}),Aa.addEventListener("requestWriteLock",function(){var t=V(function*(r){null!=uc[r.data.name]&&uc[r.data.name].writeLock().then(function(){var i=V(function*(s){return yield r.data.handler().finally(()=>s())});return function(s){return i.apply(this,arguments)}}())});return function(r){return t.apply(this,arguments)}}()))),null==uc[e.name]&&(uc[e.name]=((n,e)=>{if(!0===Aa.isWorker)return{readLock:Aa.readLock(n,e),writeLock:Aa.writeLock(n,e)};const t=new Vx({concurrency:1});let r;return{readLock:()=>V(function*(){if(null!=r)return yield ew(r,e);r=new Vx({concurrency:e.concurrency,autoStart:!1});const i=r,s=ew(r,e);return t.add(V(function*(){return i.start(),yield i.onIdle().then(()=>{r===i&&(r=null)})})),yield s})(),writeLock:()=>V(function*(){return r=null,yield ew(t,e)})()}})(e.name,e)),uc[e.name]}({name:"peer-store",singleProcess:!0})}init(e){this.components=e}_peerIdToDatastoreKey(e){if(null==e.type)throw Xx.error("peerId must be an instance of peer-id to store data"),se(new Error("peerId must be an instance of peer-id"),"ERR_INVALID_PARAMETERS");const t=e.toCID().toString();return new Xr(`${Jx}${t}`)}has(e){var t=this;return V(function*(){return yield t.components.getDatastore().has(t._peerIdToDatastoreKey(e))})()}delete(e){var t=this;return V(function*(){yield t.components.getDatastore().delete(t._peerIdToDatastoreKey(e))})()}load(e){var t=this;return V(function*(){const r=yield t.components.getDatastore().get(t._peerIdToDatastoreKey(e)),i=Sp.decode(r),s=new Map;for(const o of i.metadata)s.set(o.key,o.value);return{...i,id:e,addresses:i.addresses.map(({multiaddr:o,isCertified:a})=>({multiaddr:new vn(o),isCertified:a??!1})),metadata:s,pubKey:i.pubKey??void 0,peerRecordEnvelope:i.peerRecordEnvelope??void 0}})()}save(e){var t=this;return V(function*(){if(null!=e.pubKey&&null!=e.id.publicKey&&!$r(e.pubKey,e.id.publicKey))throw Xx.error("peer publicKey bytes do not match peer id publicKey bytes"),se(new Error("publicKey bytes do not match peer id publicKey bytes"),"ERR_INVALID_PARAMETERS");const r=new Set,i=e.addresses.filter(a=>!r.has(a.multiaddr.toString())&&(r.add(a.multiaddr.toString()),!0)).sort((a,c)=>a.multiaddr.toString().localeCompare(c.multiaddr.toString())).map(({multiaddr:a,isCertified:c})=>({multiaddr:a.bytes,isCertified:c})),s=[];[...e.metadata.keys()].sort().forEach(a=>{const c=e.metadata.get(a);null!=c&&s.push({key:a,value:c})});const o=Sp.encode({addresses:i,protocols:e.protocols.sort(),pubKey:e.pubKey,metadata:s,peerRecordEnvelope:e.peerRecordEnvelope});return yield t.components.getDatastore().put(t._peerIdToDatastoreKey(e.id),o.subarray()),yield t.load(e.id)})()}patch(e,t){var r=this;return V(function*(){const i=yield r.load(e);return yield r._patch(e,t,i)})()}patchOrCreate(e,t){var r=this;return V(function*(){let i;try{i=yield r.load(e)}catch(s){if("ERR_NOT_FOUND"!==s.code)throw s;i={id:e,addresses:[],protocols:[],metadata:new Map}}return yield r._patch(e,t,i)})()}_patch(e,t,r){var i=this;return V(function*(){return yield i.save({...r,...t,id:e})})()}merge(e,t){var r=this;return V(function*(){const i=yield r.load(e);return yield r._merge(e,t,i)})()}mergeOrCreate(e,t){var r=this;return V(function*(){let i;try{i=yield r.load(e)}catch(s){if("ERR_NOT_FOUND"!==s.code)throw s;i={id:e,addresses:[],protocols:[],metadata:new Map}}return yield r._merge(e,t,i)})()}_merge(e,t,r){var i=this;return V(function*(){const s=new Map;return r.addresses.forEach(o=>{s.set(o.multiaddr.toString(),o.isCertified)}),(t.addresses??[]).forEach(o=>{const a=o.multiaddr.toString(),m=Boolean(s.get(a))||o.isCertified;s.set(a,m)}),yield i.save({id:e,addresses:Array.from(s.entries()).map(([o,a])=>({multiaddr:new vn(o),isCertified:a})),protocols:Array.from(new Set([...r.protocols??[],...t.protocols??[]])),metadata:new Map([...r.metadata?.entries()??[],...t.metadata?.entries()??[]]),pubKey:t.pubKey??r?.pubKey,peerRecordEnvelope:t.peerRecordEnvelope??r?.peerRecordEnvelope})})()}all(){var e=this;return un(function*(){var i,t=!1,r=!1;try{for(var o,s=Tt(e.components.getDatastore().queryKeys({prefix:Jx}));t=!(o=yield ct(s.next())).done;t=!1){const c=o.value.toString().split("/")[2],m=Ro.decode(c);yield e.load(pa(m))}}catch(a){r=!0,i=a}finally{try{t&&null!=s.return&&(yield ct(s.return()))}finally{if(r)throw i}}})()}}var xa,Op;!function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.tags)throw new Error('Protocol error: required field "tags" was not found in object');for(const s of t.tags)r.uint32(10),Op.codec().encode(s,r);!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={tags:[]},s=null==r?t.len:t.pos+r;for(;t.pos>>3==1?i.tags.push(Op.codec().decode(t,t.uint32())):t.skipType(7&o)}return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(xa||(xa={})),function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.name)throw new Error('Protocol error: required field "name" was not found in object');r.uint32(10),r.string(t.name),null!=t.value&&(r.uint32(16),r.uint32(t.value)),null!=t.expiry&&(r.uint32(24),r.uint64(t.expiry)),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={name:""},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:i.name=t.string();break;case 2:i.value=t.uint32();break;case 3:i.expiry=t.uint64();break;default:t.skipType(7&o)}}if(null==i.name)throw new Error('Protocol error: value for required field "name" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(Op||(Op={}));const ys=Gt("libp2p:peer-store");class Bj extends ki{constructor(e={}){super(),this.components=new ko,this.store=new kj,this.addressBook=new gj(this.dispatchEvent.bind(this),this.store,e.addressFilter),this.keyBook=new yj(this.dispatchEvent.bind(this),this.store),this.metadataBook=new mj(this.dispatchEvent.bind(this),this.store),this.protoBook=new vj(this.dispatchEvent.bind(this),this.store)}init(e){this.components=e,this.store.init(e)}forEach(e){var t=this;return V(function*(){ys.trace("getPeers await read lock");const r=yield t.store.lock.readLock();ys.trace("getPeers got read lock");try{var o,i=!1,s=!1;try{for(var c,a=Tt(t.store.all());i=!(c=yield a.next()).done;i=!1){const m=c.value;m.id.equals(t.components.getPeerId())||e(m)}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield a.return())}finally{if(s)throw o}}}finally{ys.trace("getPeers release read lock"),r()}})()}all(){var e=this;return V(function*(){const t=[];return yield e.forEach(r=>{t.push(r)}),t})()}delete(e){var t=this;return V(function*(){ys.trace("delete await write lock");const r=yield t.store.lock.writeLock();ys.trace("delete got write lock");try{yield t.store.delete(e)}finally{ys.trace("delete release write lock"),r()}})()}get(e){var t=this;return V(function*(){ys.trace("get await read lock");const r=yield t.store.lock.readLock();ys.trace("get got read lock");try{return yield t.store.load(e)}finally{ys.trace("get release read lock"),r()}})()}has(e){var t=this;return V(function*(){ys.trace("has await read lock");const r=yield t.store.lock.readLock();ys.trace("has got read lock");try{return yield t.store.has(e)}finally{ys.trace("has release read lock"),r()}})()}tagPeer(e,t,r={}){var i=this;return V(function*(){const s=r.value??0,o=Math.round(s),a=r.ttl??void 0;if(o!==s||o<0||o>100)throw se(new Error("Tag value must be between 0-100"),"ERR_TAG_VALUE_OUT_OF_BOUNDS");const c=yield i.metadataBook.getValue(e,"tags");let m=[];null!=c&&(m=xa.decode(c).tags);for(const T of m)if(T.name===t)throw se(new Error("Peer already tagged"),"ERR_DUPLICATE_TAG");m.push({name:t,value:o,expiry:null==a?void 0:BigInt(Date.now()+a)}),yield i.metadataBook.setValue(e,"tags",xa.encode({tags:m}).subarray())})()}unTagPeer(e,t){var r=this;return V(function*(){const i=yield r.metadataBook.getValue(e,"tags");let s=[];null!=i&&(s=xa.decode(i).tags),s=s.filter(o=>o.name!==t),yield r.metadataBook.setValue(e,"tags",xa.encode({tags:s}).subarray())})()}getTags(e){var t=this;return V(function*(){const r=yield t.metadataBook.getValue(e,"tags");let i=[];null!=r&&(i=xa.decode(r).tags);const s=BigInt(Date.now()),o=i.filter(a=>null==a.expiry||a.expiry>s);return o.length!==i.length&&(yield t.metadataBook.setValue(e,"tags",xa.encode({tags:o}).subarray())),o.map(a=>({name:a.name,value:a.value??0}))})()}}class Fj{constructor(e){this.dht=e}provide(e){var t=this;return V(function*(){yield wa(t.dht.provide(e))})()}findProviders(e,t={}){var r=this;return un(function*(){var o,i=!1,s=!1;try{for(var c,a=Tt(r.dht.findProviders(e,t));i=!(c=yield ct(a.next())).done;i=!1){const m=c.value;"PROVIDER"===m.name&&(yield*jr(Tt(m.providers),ct))}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield ct(a.return()))}finally{if(s)throw o}}})()}put(e,t,r){var i=this;return V(function*(){yield wa(i.dht.put(e,t,r))})()}get(e,t){var r=this;return V(function*(){var o,i=!1,s=!1;try{for(var c,a=Tt(r.dht.get(e,t));i=!(c=yield a.next()).done;i=!1){const m=c.value;if("VALUE"===m.name)return m.value}}catch(m){s=!0,o=m}finally{try{i&&null!=a.return&&(yield a.return())}finally{if(s)throw o}}throw se(new Error("Not found"),"ERR_NOT_FOUND")})()}}const eR=Gt("libp2p:dialer:auto-dialer");class Uj{constructor(e,t){this.components=e,this.enabled=t.enabled,this.minConnections=t.minConnections,this.dialTimeout=t.dialTimeout}handle(e){const{detail:t}=e;if(this.enabled&&0===this.components.getConnectionManager().getConnections(t.id).length&&(this.minConnections??0)>this.components.getConnectionManager().getConnections().length){eR("auto-dialing discovered peer %p with timeout %d",t.id,this.dialTimeout);const o=new Bi.TimeoutController(this.dialTimeout);try{(0,Jr.setMaxListeners)?.(1/0,o.signal)}catch{}this.components.getConnectionManager().openConnection(t.id,{signal:o.signal}).catch(a=>{eR.error("could not connect to discovered peer %p with %o",t.id,a)}).finally(()=>{o.clear()})}}}var tR=N(4033);const Vj=globalThis.fetch,Hj=globalThis.Headers;function nw(n,e,t){return`${n}?name=${e}&type=${t}`}function Kj(n,e){return rw.apply(this,arguments)}function rw(){return rw=V(function*(n,e){return yield(yield Vj(n,{headers:new Hj({accept:"application/dns-json"}),signal:e})).json()}),rw.apply(this,arguments)}function Fu(n,e){return`${e}_${n}`}globalThis,globalThis;const iw=Object.assign(Ur("dns-over-http-resolver"),{error:Ur("dns-over-http-resolver:error")}),$j=class jj{constructor(e={}){this._cache=new tR({max:e?.maxCache??100}),this._TXTcache=new tR({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Kj,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){const e=[...this._servers];for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*t),i=e[t];e[t]=e[r],e[r]=i}return e}setServers(e){this._servers=e}resolve(e,t="A"){var r=this;return V(function*(){switch(t){case"A":return yield r.resolve4(e);case"AAAA":return yield r.resolve6(e);case"TXT":return yield r.resolveTxt(e);default:throw new Error(`${t} is not supported`)}})()}resolve4(e){var t=this;return V(function*(){const i=t._cache.get(Fu(e,"A"));if(null!=i)return i;let s=!1;for(const o of t._getShuffledServers()){const a=new AbortController;t._abortControllers.push(a);try{const c=yield t._request(nw(o,e,"A"),a.signal),m=c.Answer.map(R=>R.data),T=Math.min(...c.Answer.map(R=>R.TTL));return t._cache.set(Fu(e,"A"),m,{ttl:T}),m}catch{a.signal.aborted&&(s=!0),iw.error(`${o} could not resolve ${e} record A`)}finally{t._abortControllers=t._abortControllers.filter(c=>c!==a)}}throw s?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record A`)})()}resolve6(e){var t=this;return V(function*(){const r="AAAA",i=t._cache.get(Fu(e,r));if(null!=i)return i;let s=!1;for(const o of t._getShuffledServers()){const a=new AbortController;t._abortControllers.push(a);try{const c=yield t._request(nw(o,e,r),a.signal),m=c.Answer.map(R=>R.data),T=Math.min(...c.Answer.map(R=>R.TTL));return t._cache.set(Fu(e,r),m,{ttl:T}),m}catch{a.signal.aborted&&(s=!0),iw.error(`${o} could not resolve ${e} record AAAA`)}finally{t._abortControllers=t._abortControllers.filter(c=>c!==a)}}throw s?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record AAAA`)})()}resolveTxt(e){var t=this;return V(function*(){const r="TXT",i=t._TXTcache.get(Fu(e,r));if(null!=i)return i;let s=!1;for(const o of t._getShuffledServers()){const a=new AbortController;t._abortControllers.push(a);try{const c=yield t._request(nw(o,e,r),a.signal),m=c.Answer.map(R=>[R.data.replace(/['"]+/g,"")]),T=Math.min(...c.Answer.map(R=>R.TTL));return t._TXTcache.set(Fu(e,r),m,{ttl:T}),m}catch{a.signal.aborted&&(s=!0),iw.error(`${o} could not resolve ${e} record TXT`)}finally{t._abortControllers=t._abortControllers.filter(c=>c!==a)}}throw s?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record TXT`)})()}clearCache(){this._cache.clear(),this._TXTcache.clear()}},{code:Gj}=Nr("dnsaddr");function sw(){return sw=V(function*(n,e={}){const t=new $j;null!=e.signal&&e.signal.addEventListener("abort",()=>{t.cancel()});const r=n.getPeerId(),[,i]=n.stringTuples().find(([a])=>a===Gj)??[];if(null==i)throw new Error("No hostname found in multiaddr");let o=(yield t.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]);return null!=r&&(o=o.filter(a=>a.includes(r))),o}),sw.apply(this,arguments)}const Wj={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:n=>n},connectionManager:{maxConnections:300,minConnections:50,autoDial:!0,autoDialInterval:1e4,maxParallelDials:100,maxDialsPerPeer:4,dialTimeout:3e4,inboundUpgradeTimeout:3e4,resolvers:{dnsaddr:function zj(n){return sw.apply(this,arguments)}},addressSorter:yE},connectionGater:{},transportManager:{faultTolerance:oc.FATAL_ALL},metrics:{enabled:!1,computeThrottleMaxQueueSize:1e3,computeThrottleTimeout:2e3,movingAverageIntervals:[6e4,3e5,9e5],maxOldPeersRetention:50},peerRouting:{refreshManager:{enabled:!0,interval:6e5,bootDelay:1e4}},nat:{enabled:!0,ttl:7200,keepAlive:!0},relay:{enabled:!0,advertise:{bootDelay:9e5,enabled:!1,ttl:18e5},hop:{enabled:!1,active:!1,timeout:3e4},autoRelay:{enabled:!1,maxListeners:2}},identify:{protocolPrefix:"ipfs",host:{agentVersion:Ix},timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1},ping:{protocolPrefix:"ipfs",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4},fetch:{protocolPrefix:"libp2p",maxInboundStreams:1,maxOutboundStreams:1,timeout:1e4}};function qj(n){const e=Df(Wj,n);if(null==e.transports||e.transports.length<1)throw se(new Error(Cn.ERR_TRANSPORTS_REQUIRED),Ie.ERR_TRANSPORTS_REQUIRED);if(null==e.connectionEncryption||0===e.connectionEncryption.length)throw se(new Error(Cn.CONN_ENCRYPTION_REQUIRED),Ie.CONN_ENCRYPTION_REQUIRED);if(null===e.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw se(new Error(Cn.ERR_PROTECTOR_REQUIRED),Ie.ERR_PROTECTOR_REQUIRED);return e.identify.host.agentVersion===Ix&&(X9||Y9?e.identify.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(fp||_A||Z9||J9)&&(e.identify.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`)),e}var nR;!function(n){let e;n.codec=()=>(null==e&&(e=fi((t,r,i={})=>{if(!1!==i.lengthDelimited&&r.fork(),null==t.id)throw new Error('Protocol error: required field "id" was not found in object');r.uint32(10),r.bytes(t.id),null!=t.pubKey&&(r.uint32(18),r.bytes(t.pubKey)),null!=t.privKey&&(r.uint32(26),r.bytes(t.privKey)),!1!==i.lengthDelimited&&r.ldelim()},(t,r)=>{const i={id:new Uint8Array(0)},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(7&o)}}if(null==i.id)throw new Error('Protocol error: value for required field "id" was not found in protobuf');return i})),e),n.encode=t=>li(t,n.codec()),n.decode=t=>ui(t,n.codec())}(nR||(nR={}));const Qj=function(){var n=V(function*(){const e=yield bT("Ed25519"),t=yield function rR(n){return aw.apply(this,arguments)}(e);if("Ed25519"===t.type)return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)});return function(){return n.apply(this,arguments)}}();function aw(){return aw=V(function*(n){return yield xu(BV(n.public),FV(n))}),aw.apply(this,arguments)}const fw=Symbol.for("@libp2p/peer-discovery");class Zj extends ki{get[fw](){return!0}get[Symbol.toStringTag](){return"@libp2p/dummy-dht"}get wan(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)}get lan(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)}get(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)}findProviders(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)}findPeer(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)}getClosestPeers(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)}provide(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)}put(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)}getMode(){return V(function*(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)})()}setMode(){return V(function*(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)})()}refreshRoutingTable(){return V(function*(){throw se(new Error(Cn.DHT_DISABLED),Ie.DHT_DISABLED)})()}}class Xj extends ki{isStarted(){return!1}start(){}stop(){}get globalSignaturePolicy(){throw se(new Error(Cn.PUBSUB_DISABLED),Ie.ERR_PUBSUB_DISABLED)}get multicodecs(){throw se(new Error(Cn.PUBSUB_DISABLED),Ie.ERR_PUBSUB_DISABLED)}getPeers(){throw se(new Error(Cn.PUBSUB_DISABLED),Ie.ERR_PUBSUB_DISABLED)}getTopics(){throw se(new Error(Cn.PUBSUB_DISABLED),Ie.ERR_PUBSUB_DISABLED)}subscribe(){throw se(new Error(Cn.PUBSUB_DISABLED),Ie.ERR_PUBSUB_DISABLED)}unsubscribe(){throw se(new Error(Cn.PUBSUB_DISABLED),Ie.ERR_PUBSUB_DISABLED)}getSubscribers(){throw se(new Error(Cn.PUBSUB_DISABLED),Ie.ERR_PUBSUB_DISABLED)}publish(){return V(function*(){throw se(new Error(Cn.PUBSUB_DISABLED),Ie.ERR_PUBSUB_DISABLED)})()}}const $o=Gt("libp2p");class Jj extends ki{constructor(e){var o;super(),this.initializables=[],this.started=!1,this.peerId=e.peerId,this.components=new ko({peerId:e.peerId,datastore:e.datastore??new SH,connectionGater:{denyDialPeer:(o=V(function*(){return yield Promise.resolve(!1)}),function(){return o.apply(this,arguments)}),denyDialMultiaddr:function(){var o=V(function*(){return yield Promise.resolve(!1)});return function(){return o.apply(this,arguments)}}(),denyInboundConnection:function(){var o=V(function*(){return yield Promise.resolve(!1)});return function(){return o.apply(this,arguments)}}(),denyOutboundConnection:function(){var o=V(function*(){return yield Promise.resolve(!1)});return function(){return o.apply(this,arguments)}}(),denyInboundEncryptedConnection:function(){var o=V(function*(){return yield Promise.resolve(!1)});return function(){return o.apply(this,arguments)}}(),denyOutboundEncryptedConnection:function(){var o=V(function*(){return yield Promise.resolve(!1)});return function(){return o.apply(this,arguments)}}(),denyInboundUpgradedConnection:function(){var o=V(function*(){return yield Promise.resolve(!1)});return function(){return o.apply(this,arguments)}}(),denyOutboundUpgradedConnection:function(){var o=V(function*(){return yield Promise.resolve(!1)});return function(){return o.apply(this,arguments)}}(),filterMultiaddrForPeer:function(){var o=V(function*(){return yield Promise.resolve(!0)});return function(){return o.apply(this,arguments)}}(),...e.connectionGater}}),this.components.setPeerStore(new Bj({addressFilter:this.components.getConnectionGater().filterMultiaddrForPeer,...e.peerStore})),this.services=[this.components],e.metrics.enabled&&(this.metrics=this.components.setMetrics(new wK(e.metrics))),this.peerStore=this.components.getPeerStore(),this.peerStore.addEventListener("peer",o=>{const{detail:a}=o;this.dispatchEvent(new rn("peer:discovery",{detail:a}))}),null!=e.connectionProtector&&this.components.setConnectionProtector(e.connectionProtector),this.components.setUpgrader(new UK(this.components,{connectionEncryption:(e.connectionEncryption??[]).map(o=>this.configureComponent(o)),muxers:(e.streamMuxers??[]).map(o=>this.configureComponent(o)),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout})),this.connectionManager=this.components.setConnectionManager(new GH(e.connectionManager)),this.registrar=this.components.setRegistrar(new kK(this.components)),this.components.setTransportManager(new xK(this.components,e.transportManager)),this.components.setAddressManager(new xH(this.components,e.addresses)),this.configureComponent(new dj(this.components)),this.configureComponent(new WH(this.components,{enabled:e.connectionManager.autoDial,minConnections:e.connectionManager.minConnections,autoDialInterval:e.connectionManager.autoDialInterval}));const t=fx.generateOptions();this.keychain=this.configureComponent(new fx(this.components,{...t,...e.keychain})),this.services.push(new lj(this.components,e.nat)),e.transports.forEach(o=>{this.components.getTransportManager().add(this.configureComponent(o))}),null!=e.streamMuxers&&e.streamMuxers.length>0&&(this.identifyService=new $E(this.components,{...e.identify}),this.configureComponent(this.identifyService)),this.dht=null!=e.dht?this.components.setDHT(e.dht):new Zj,this.pubsub=null!=e.pubsub?this.components.setPubSub(e.pubsub):new Xj;const r=(e.peerRouters??[]).map(o=>this.configureComponent(o));null!=e.dht&&(r.push(this.configureComponent(new hj(this.dht))),this.dht.addEventListener("peer",o=>{this.onDiscoveryPeer(o)})),this.peerRouting=this.components.setPeerRouting(this.configureComponent(new IH(this.components,{...e.peerRouting,routers:r})));const i=(e.contentRouters??[]).map(o=>this.configureComponent(o));null!=e.dht&&i.push(this.configureComponent(new Fj(this.dht))),this.contentRouting=this.components.setContentRouting(this.configureComponent(new CH(this.components,{routers:i}))),e.relay.enabled&&(this.components.getTransportManager().add(this.configureComponent(new nK(e.relay))),this.configureComponent(new cK(this.components,{addressSorter:e.connectionManager.addressSorter,...e.relay}))),this.fetchService=this.configureComponent(new tj(this.components,{...e.fetch})),this.pingService=this.configureComponent(new sj(this.components,{...e.ping}));const s=this.configureComponent(new Uj(this.components,{enabled:!1!==e.connectionManager.autoDial,minConnections:e.connectionManager.minConnections,dialTimeout:e.connectionManager.dialTimeout??3e4}));this.addEventListener("peer:discovery",o=>{!this.isStarted()||s.handle(o)});for(const o of e.peerDiscovery??[])this.configureComponent(o),o.addEventListener("peer",a=>{this.onDiscoveryPeer(a)})}configureComponent(e){return Lo(e)&&this.services.push(e),hi(e)&&this.initializables.push(e),e}start(){var e=this;return V(function*(){if(!e.started){e.started=!0,$o("libp2p is starting");try{e.initializables.forEach(t=>{t.init(e.components)}),yield Promise.all(e.services.map(function(){var t=V(function*(r){null!=r.beforeStart&&(yield r.beforeStart())});return function(r){return t.apply(this,arguments)}}())),yield Promise.all(e.services.map(t=>t.start())),yield Promise.all(e.services.map(function(){var t=V(function*(r){null!=r.afterStart&&(yield r.afterStart())});return function(r){return t.apply(this,arguments)}}())),$o("libp2p has started")}catch(t){throw $o.error("An error occurred starting libp2p",t),yield e.stop(),t}}})()}stop(){var e=this;return V(function*(){!e.started||($o("libp2p is stopping"),e.started=!1,yield Promise.all(e.services.map(function(){var t=V(function*(r){null!=r.beforeStop&&(yield r.beforeStop())});return function(r){return t.apply(this,arguments)}}())),yield Promise.all(e.services.map(t=>t.stop())),yield Promise.all(e.services.map(function(){var t=V(function*(r){null!=r.afterStop&&(yield r.afterStop())});return function(r){return t.apply(this,arguments)}}())),$o("libp2p has stopped"))})()}isStarted(){return this.started}getConnections(e){return this.components.getConnectionManager().getConnections(e)}getPeers(){const e=new B7;for(const t of this.components.getConnectionManager().getConnections())e.add(t.remotePeer);return Array.from(e)}dial(e,t={}){var r=this;return V(function*(){const{id:i,multiaddrs:s}=_f(e);return yield r.components.getPeerStore().addressBook.add(i,s),yield r.components.getConnectionManager().openConnection(i,t)})()}dialProtocol(e,t,r={}){var i=this;return V(function*(){if(null==t)throw se(new Error("no protocols were provided to open a stream"),Ie.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(0===(t=Array.isArray(t)?t:[t]).length)throw se(new Error("no protocols were provided to open a stream"),Ie.ERR_INVALID_PROTOCOLS_FOR_STREAM);return yield(yield i.dial(e,r)).newStream(t,r)})()}getMultiaddrs(){return this.components.getAddressManager().getAddresses()}hangUp(e){var t=this;return V(function*(){const{id:r}=_f(e);yield t.components.getConnectionManager().closeConnections(r)})()}getPublicKey(e,t={}){var r=this;return V(function*(){if($o("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;const i=yield r.peerStore.get(e);if(null!=i.pubKey)return i.pubKey;if(null==r.dht)throw se(new Error("Public key was not in the peer store and the DHT is not enabled"),Ie.ERR_NO_ROUTERS_AVAILABLE);const s=or([_t("/pk/"),e.multihash.digest]);var c,o=!1,a=!1;try{for(var T,m=Tt(r.dht.get(s,t));o=!(T=yield m.next()).done;o=!1){const R=T.value;if("VALUE"===R.name){const k=Tu(R.value);return yield r.peerStore.keyBook.set(e,R.value),k.bytes}}}catch(R){a=!0,c=R}finally{try{o&&null!=m.return&&(yield m.return())}finally{if(a)throw c}}throw se(new Error(`Node not responding with its public key: ${e.toString()}`),Ie.ERR_INVALID_RECORD)})()}fetch(e,t,r={}){var i=this;return V(function*(){const{id:s,multiaddrs:o}=_f(e);return null!=o&&(yield i.components.getPeerStore().addressBook.add(s,o)),yield i.fetchService.fetch(s,t,r)})()}ping(e,t={}){var r=this;return V(function*(){const{id:i,multiaddrs:s}=_f(e);return s.length>0&&(yield r.components.getPeerStore().addressBook.add(i,s)),yield r.pingService.ping(i,t)})()}handle(e,t,r){var i=this;return V(function*(){Array.isArray(e)||(e=[e]),yield Promise.all(e.map(function(){var s=V(function*(o){yield i.components.getRegistrar().handle(o,t,r)});return function(o){return s.apply(this,arguments)}}()))})()}unhandle(e){var t=this;return V(function*(){Array.isArray(e)||(e=[e]),yield Promise.all(e.map(function(){var r=V(function*(i){yield t.components.getRegistrar().unhandle(i)});return function(i){return r.apply(this,arguments)}}()))})()}onDiscoveryPeer(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?(t.multiaddrs.length>0&&this.components.getPeerStore().addressBook.add(t.id,t.multiaddrs).catch(r=>$o.error(r)),t.protocols.length>0&&this.components.getPeerStore().protoBook.set(t.id,t.protocols).catch(r=>$o.error(r)),this.dispatchEvent(new rn("peer:discovery",{detail:t}))):$o.error(new Error(Ie.ERR_DISCOVERED_SELF))}}function e$(n){return dw.apply(this,arguments)}function dw(){return dw=V(function*(n){return null==n.peerId&&(n.peerId=yield Qj()),new Jj(qj(n))}),dw.apply(this,arguments)}function t$(n){return hw.apply(this,arguments)}function hw(){return hw=V(function*(n){return yield e$(n)}),hw.apply(this,arguments)}function sR(n,e){return n.length<=e||n.length<=1?n:function r$(n){if(n.length<=1)return n;for(let t=0;t{class n extends ki{constructor(t,r){super(),this.interval=r?.interval??n.DefaultInterval;const i=r?.maxPeers??t?.length,s=t.map(o=>"string"==typeof o?new vn(o):o);this.peers=function n$(n){return n.map(e=>{const t=e.getPeerId();return{id:t?_r(t):null,multiaddrs:[e.decapsulateCode(421)],protocols:[]}}).filter(e=>null!==e.id)}(sR(s,i)),oR("Use provided list of peers (reduced to maxPeers)",this.peers.map(o=>o.toString()))}start(){this._startTimer()}_startTimer(){if(this.peers){if(oR("Starting to emit static peers."),null!=this.timer)return;this.timer=setInterval(()=>this._returnPeers(),this.interval),this._returnPeers()}}_returnPeers(){null!=this.timer&&this.peers.forEach(t=>{this.dispatchEvent(new rn("peer",{detail:t}))})}stop(){null!=this.timer&&clearInterval(this.timer),this.timer=void 0}get[fw](){return!0}get[Symbol.toStringTag](){return"@waku/peer-discovery-static-list"}}return n.DefaultInterval=200,n})();var Uu=(()=>(function(n){n.Prod="prod",n.Test="test"}(Uu||(Uu={})),Uu))();const pw_fleets={"wakuv2.prod":{"waku-websocket":{"node-01.ac-cn-hongkong-c.wakuv2.prod":"/dns4/node-01.ac-cn-hongkong-c.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAm4v86W3bmT1BiH6oSPzcsSr24iDQpSN5Qa992BCjjwgrD","node-01.do-ams3.wakuv2.prod":"/dns4/node-01.do-ams3.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAmL5okWopX7NqZWBUKVqW8iUxCEmd5GMHLVPwCgzYzQv3e","node-01.gc-us-central1-a.wakuv2.prod":"/dns4/node-01.gc-us-central1-a.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAmVkKntsECaYfefR1V2yCR79CegLATuTPE6B9TxgxBiiiA"}},"wakuv2.test":{"waku-websocket":{"node-01.ac-cn-hongkong-c.wakuv2.test":"/dns4/node-01.ac-cn-hongkong-c.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAkvWiyFsgRhuJEb9JfjYxEkoHLgnUQmr1N5mKWnYjxYRVm","node-01.do-ams3.wakuv2.test":"/dns4/node-01.do-ams3.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAmPLe7Mzm8TsYUubgCAW1aJoeFScxrLj8ppHFivPo97bUZ","node-01.gc-us-central1-a.wakuv2.test":"/dns4/node-01.gc-us-central1-a.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAmJb2e28qLXxT5kZxVUUoJt72EMzNGXB47Rxx5hw3q4YjS"}}},aR=Symbol.for("@achingbrain/uint8arraylist");function cR(n,e,t){if(null==e||e<0||e>=t)throw new RangeError("index is out of bounds");let r=0;for(const i of n){const s=r+i.byteLength;if(e0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}slice(e,t){const{bufs:r,length:i}=this._subList(e,t);return or(r,i)}subarray(e,t){const{bufs:r}=this._subList(e,t),i=new Vr;return i.appendAll(r),i}_subList(e,t){if(null==e&&null==t)return{bufs:this.bufs,length:this.length};if((e=e??0)<0&&(e=this.length+e),(t=t??(this.length>0?this.length:0))<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index out of bounds");if(e===t)return{bufs:[],length:0};const r=[];let i=0;for(const s of this.bufs){const o=i,a=o+s.byteLength,m=t>o&&t<=a;let R,k;if(i=a,e>=o&&e=a&&(R=0,k=s.byteLength),null!=R&&null!=k&&r.push(s.subarray(R,k)),m)break}return{bufs:r,length:t-e}}getInt8(e){const t=this.slice(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=new Uint8Array(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.slice(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const i=new Uint8Array(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,r),this.write(i,e)}getInt32(e,t){const r=this.slice(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const i=new Uint8Array(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,r),this.write(i,e)}getBigInt64(e,t){const r=this.slice(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const i=new Uint8Array(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,r),this.write(i,e)}getUint8(e){const t=this.slice(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=new Uint8Array(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.slice(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const i=new Uint8Array(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,r),this.write(i,e)}getUint32(e,t){const r=this.slice(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const i=new Uint8Array(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,r),this.write(i,e)}getBigUint64(e,t){const r=this.slice(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const i=new Uint8Array(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,r),this.write(i,e)}getFloat32(e,t){const r=this.slice(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const i=new Uint8Array(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,r),this.write(i,e)}getFloat64(e,t){const r=this.slice(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const i=new Uint8Array(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,r),this.write(i,e)}}const Lp=(n,e,t)=>{const r=Vn.encode(n,e,t);return Lp.bytes=Vn.encode.bytes,e??Uint8Array.from(r)};function Ff(n){n=n??{};const e=Math.max(n.poolSize??10240,n.minPoolSize??8),t=n.lengthEncoder??Lp;return function(){var i=un(function*(s){let o=new Uint8Array(e),a=0;var T,c=!1,m=!1;try{for(var k,R=Tt(s);c=!(k=yield ct(R.next())).done;c=!1){const U=k.value;t(U.length,o,a);const Q=o.slice(a,a+t.bytes);a+=t.bytes,o.length-a<8&&(o=new Uint8Array(e),a=0),yield or([Q,U.slice()],Q.length+U.length)}}catch(U){m=!0,T=U}finally{try{c&&null!=R.return&&(yield ct(R.return()))}finally{if(m)throw T}}});return function(o){return i.apply(this,arguments)}}()}Lp.bytes=0,Ff.single=(n,e)=>new Vr(((e=e??{}).lengthEncoder??Lp)(n.length),n.slice());const gw=n=>{const e=Vn.decode(n);return gw.bytes=Vn.decode.bytes,e};gw.bytes=0;const l$=new Vr,f$={readLength:(n,e,t,r)=>{const i=r?.lengthDecoder??gw,s=r?.maxLengthLength??8,o=r?.maxDataLength??4194304;let a;e.append(n);try{a=i(e.slice())}catch(c){if(e.length>s)throw se(new Error("message length too long"),"ERR_MSG_LENGTH_TOO_LONG");if(c instanceof RangeError)return{mode:"readLength",buffer:e,chunk:void 0,state:void 0,data:void 0};throw c}if(a>o)throw se(new Error("message data too long"),"ERR_MSG_DATA_TOO_LONG");return n=e.subarray(i.bytes),e=new Vr,null!=r?.onLength&&r.onLength(a),a<=0?{mode:"readLength",chunk:n,buffer:e,data:l$}:{mode:"readData",chunk:n,buffer:e,state:{dataLength:a},data:void 0}},readData:(n,e,t,r)=>{if(e.append(n),null==t)throw new Error("state is required");if(e.lengthi?e.subarray(i):void 0,buffer:e=new Vr,state:void 0,data:s}}};function Vu(n){return function(){var t=un(function*(r){let o,i=new Vr,s="readLength";var m,a=!1,c=!1;try{for(var R,T=Tt(r);a=!(R=yield ct(T.next())).done;a=!1){let U=new Vr(R.value);for(;null!=U;){const Q=f$[s](U,i,o,n);if(s=Q.mode,U=Q.chunk,i=Q.buffer,o=Q.state,null!=Q.data){const X=Q.data.slice();null!=n?.onData&&n.onData(X),yield X}}}}catch(k){c=!0,m=k}finally{try{a&&null!=T.return&&(yield ct(T.return()))}finally{if(c)throw m}}if(i.length>0)throw se(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")});return function(i){return t.apply(this,arguments)}}()}Vu.fromReader=(n,e)=>{let t=1;const r=un(function*(){for(;;)try{const{done:s,value:o}=yield ct(n.next(t));if(!0===s)return;null!=o&&(yield o)}catch(s){if("ERR_UNDER_READ"===s.code)return{done:!0,value:null};throw s}finally{t=1}})();return Vu({...e??{},onLength:s=>{t=s}})(r)};const kp="/waku/2/default-waku/proto";var lc=(()=>(function(n){n.V2Beta3="/vac/waku/store/2.0.0-beta3",n.V2Beta4="/vac/waku/store/2.0.0-beta4"}(lc||(lc={})),lc))();function yw(n){return mw.apply(this,arguments)}function mw(){return mw=V(function*(n){if(0!==n.length)return n[Math.round(Math.random()*(n.length-1))]}),mw.apply(this,arguments)}function vw(n,e){return Ew.apply(this,arguments)}function Ew(){return Ew=V(function*(n,e){const t=[];return yield n.peerStore.forEach(r=>{for(let i=0;is+o.length,0),r=new Uint8Array(t);let i=0;for(const s of n)r.set(s,i),i+=s.length;return r}function Hu(n){return n instanceof Uint8Array?{get:e=>n[e],set(e,t){n[e]=t}}:{get:e=>n.get(e),set(e,t){n.set(e,t)}}}const fR=4294967296;class Fi{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const t=1+~this.lo>>>0;let r=~this.hi>>>0;return 0===t&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}zzDecode(){const e=-(1&this.lo);return new Fi((this.hi>>>1^e)>>>0,((this.lo>>>1|this.hi<<31)^e)>>>0)}zzEncode(){const e=this.hi>>31;return new Fi(((this.hi<<1|this.lo>>>31)^e)>>>0,(this.lo<<1^e)>>>0)}toBytes(e,t=0){const r=Hu(e);for(;this.hi>0;)r.set(t++,127&this.lo|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)r.set(t++,127&this.lo|128),this.lo=this.lo>>>7;r.set(t++,this.lo)}static fromBigInt(e){if(0n===e)return new Fi;const t=e<0;t&&(e=-e);let r=0|Number(e>>32n),i=0|Number(e-(BigInt(r)<<32n));return t&&(r=~r>>>0,i=~i>>>0,++i>fR&&(i=0,++r>fR&&(r=0))),new Fi(r,i)}static fromNumber(e){if(0===e)return new Fi;const t=e<0;t&&(e=-e);let r=e>>>0,i=(e-r)/4294967296>>>0;return t&&(i=~i>>>0,r=~r>>>0,++r>4294967295&&(r=0,++i>4294967295&&(i=0))),new Fi(i,r)}static fromBytes(e,t){const r=Hu(e),i=new Fi;let s=0;if(!(e.length-t>4)){for(;s<3;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(127&r.get(t))<<7*s)>>>0,r.get(t++)<128)return i}return i.lo=(i.lo|(127&r.get(t++))<<7*s)>>>0,i}for(;s<4;++s)if(i.lo=(i.lo|(127&r.get(t))<<7*s)>>>0,r.get(t++)<128)return i;if(i.lo=(i.lo|(127&r.get(t))<<28)>>>0,i.hi=(i.hi|(127&r.get(t))>>4)>>>0,r.get(t++)<128)return i;if(s=0,e.length-t>4){for(;s<5;++s)if(i.hi=(i.hi|(127&r.get(t))<<7*s+3)>>>0,r.get(t++)<128)return i}else for(;s<5;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(127&r.get(t))<<7*s+3)>>>0,r.get(t++)<128)return i}throw Error("invalid varint encoding")}}const v$=Math.pow(2,31),E$=Math.pow(2,7),w$=Math.pow(2,14),b$=Math.pow(2,21),_$=Math.pow(2,28),D$=Math.pow(2,35),S$=Math.pow(2,42),I$=Math.pow(2,49),C$=Math.pow(2,56),T$=Math.pow(2,63),Yt={encodingLength:n=>n=v$;)r.set(t++,255&n|128),n/=128;for(;(-128&n)>0;)r.set(t++,255&n|128),n>>>=7;r.set(t,0|n)},decode(n,e=0){const t=Hu(n);let r=4294967295;if(r=(127&t.get(e))>>>0,t.get(e++)<128||(r=(r|(127&t.get(e))<<7)>>>0,t.get(e++)<128)||(r=(r|(127&t.get(e))<<14)>>>0,t.get(e++)<128)||(r=(r|(127&t.get(e))<<21)>>>0,t.get(e++)<128)||(r=(r|(15&t.get(e))<<28)>>>0,t.get(e++)<128))return r;if((e+=5)>n.length)throw RangeError(`index out of range: ${e} > ${n.length}`);return r}},ww={encodingLength:n=>n<0?10:Yt.encodingLength(n),encode(n,e){if(n<0){let t=0;const r=Hu(e),i=Fi.fromNumber(n);for(;i.hi>0;)r.set(t++,127&i.lo|128),i.lo=(i.lo>>>7|i.hi<<25)>>>0,i.hi>>>=7;for(;i.lo>127;)r.set(t++,127&i.lo|128),i.lo=i.lo>>>7;r.set(t++,i.lo)}else Yt.encode(n,e)},decode:(n,e=0)=>0|Yt.decode(n,e)},bw={encodingLength:n=>Yt.encodingLength(n=(n<<1^n>>31)>>>0),encode:(n,e,t=0)=>Yt.encode(n=(n<<1^n>>31)>>>0,e),decode(n,e=0){const t=Yt.decode(n,e);return t>>>1^-(1&t)|0}};function ar(n,e){const t=new Uint8Array(Yt.encodingLength(n.length));return Yt.encode(n.length,t),e.decode(new Vr(t,n),0)}function cr(n,e){const t=e.encode(n),r=Yt.encodingLength(Yt.decode(t));return t.slice(r)}var Xn=(()=>(function(n){n[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32"}(Xn||(Xn={})),Xn))();function ei(n,e,t,r,i){return{name:n,type:e,encode:t,decode:r,encodingLength:i}}const hR=ei("bool",Xn.VARINT,function(e){return Uint8Array.from([e?1:0])},function(e,t){return e.get(t)>0},function(){return 1}),fc=ei("bytes",Xn.LENGTH_DELIMITED,function(e){const t=new Uint8Array(Yt.encodingLength(e.byteLength));return Yt.encode(e.byteLength,t),new Vr(t,e)},function(e,t){const r=Yt.decode(e,t);return t+=Yt.encodingLength(r),e.slice(t,t+r)},function(e){const t=e.byteLength;return Yt.encodingLength(t)+t}),Go=ei("double",Xn.BIT64,function(e){const t=new Vr(new Uint8Array(8));return t.setFloat64(0,e,!0),t},function(e,t){return e.getFloat64(t,!0)},function(){return 8});function Bp(n){function e(s){if(null==n[s.toString()])throw new Error("Invalid enum value");return"number"==typeof s?s:n[s]}return ei("enum",Xn.VARINT,function(o){const a=e(o),c=new Uint8Array(Yt.encodingLength(a));return Yt.encode(a,c),c},function(o,a){const m=Yt.decode(o,a).toString();if(null==n[m])throw new Error("Invalid enum value");return n[m]},function(o){return Yt.encodingLength(e(o))})}const yR=(ei("fixed32",Xn.BIT32,function(e){const t=new Vr(new Uint8Array(4));return t.setInt32(0,e,!0),t},function(e,t){return e.getInt32(t,!0)},function(){return 4}),function(e){return 8}),mR=(ei("fixed64",Xn.BIT64,function(e){const t=new Vr(new Uint8Array(8));return t.setBigInt64(0,e,!0),t},function(e,t){return e.getBigInt64(t,!0)},yR),function(){return 4}),vR=(ei("float",Xn.BIT32,function(e){const t=new Vr(new Uint8Array(4));return t.setFloat32(0,e,!0),t},function(e,t){return e.getFloat32(t,!0)},mR),function(e){return ww.encodingLength(e)}),ER=(ei("int32",Xn.VARINT,function(e){const t=new Uint8Array(vR(e));return ww.encode(e,t),t},function(e,t){return ww.decode(e,t)},vR),0x7fn),dc={encodingLength(n){let e=0;for(;n>=0x80n;e++)n>>=7n;return e+1},encode(n,e){const t=Hu(e);let r=0;for(;ER>=7n;t.set(r,Number(n))},decode:(n,e=0)=>Fi.fromBytes(n,e).toBigInt(!0)},_w={encodingLength:n=>n<0n?10:dc.encodingLength(n),encode(n,e,t=0){if(!(n<0n))return dc.encode(n,e);Fi.fromBigInt(n).toBytes(e,t)},decode:(n,e=0)=>Fi.fromBytes(n,e).toBigInt(!1)},Dw={encodingLength:n=>dc.encodingLength(n>=0?2n*n:-2n*n-1n),encode(n,e,t=0){Fi.fromBigInt(n).zzEncode().toBytes(e,t)},decode:(n,e=0)=>Fi.fromBytes(n,e).zzDecode().toBigInt(!1)},wR=function(e){return _w.encodingLength(e)};function ur(n){return ei("message",Xn.LENGTH_DELIMITED,function(s){const o=new Vr;function a(m,T,R){if(null==m){if(!0===R.optional)return;throw new Error(`Non optional field "${R.name}" was ${null===m?"null":"undefined"}`)}const k=T<<3|R.codec.type,U=new Uint8Array(Yt.encodingLength(k));Yt.encode(k,U);const Q=R.codec.encode(m);o.append(U),o.append(Q)}for(const[m,T]of Object.entries(n)){const R=parseInt(m);if(!0===T.repeats){if(!Array.isArray(s[T.name]))throw new Error(`Repeating field "${T.name}" was not an array`);for(const k of s[T.name])a(k,R,T)}else a(s[T.name],R,T)}const c=new Uint8Array(Yt.encodingLength(o.length));return Yt.encode(o.length,c),new Vr(c,o)},function(s,o){const a=Yt.decode(s,o),c=(o+=Yt.encodingLength(a))+a,m={};for(;o>3];let Q=0;if(R===Xn.VARINT)if(null!=U){const X=U.codec.decode(s,o);Q=U.codec.encodingLength(X)}else{const X=Yt.decode(s,o);Q=Yt.encodingLength(X)}else if(R===Xn.BIT64)Q=8;else if(R===Xn.LENGTH_DELIMITED){const X=Yt.decode(s,o);Q=X+Yt.encodingLength(X)}else if(R===Xn.BIT32)Q=4;else{if(R===Xn.START_GROUP)throw new Error("Unsupported wire type START_GROUP");if(R===Xn.END_GROUP)throw new Error("Unsupported wire type END_GROUP")}if(null!=U){const X=U.codec.decode(s,o);!0===U.repeats?(null==m[U.name]&&(m[U.name]=[]),m[U.name].push(X)):m[U.name]=X}o+=Q}for(const T of Object.values(n))!0===T.repeats&&null==m[T.name]&&(m[T.name]=[]);return m},function(s){let o=0;for(const a of Object.values(n))o+=a.codec.encodingLength(s[a.name]);return Yt.encodingLength(o)+o})}ei("int64",Xn.VARINT,function(e){const t=new Uint8Array(wR(e));return _w.encode(e,t),t},function(e,t){return 0n|_w.decode(e,t)},wR);const _R=(ei("sfixed32",Xn.BIT32,function(e){const t=new Vr(new Uint8Array(4));return t.setInt32(0,e,!0),t},function(e,t){return e.getInt32(t,!0)},function(){return 4}),function(){return 8}),DR=(ei("sfixed64",Xn.BIT64,function(e){const t=new Vr(new Uint8Array(8));return t.setBigInt64(0,e,!0),t},function(e,t){return e.getBigInt64(t,!0)},_R),function(e){return bw.encodingLength(e)}),SR=(ei("sint32",Xn.VARINT,function(e){const t=new Uint8Array(DR(e));return bw.encode(e,t),t},function(e,t){return bw.decode(e,t)},DR),function(e){return Dw.encodingLength(e)}),zo=ei("sint64",Xn.VARINT,function(e){const t=new Uint8Array(SR(e));return Dw.encode(e,t),t},function(e,t){return Dw.decode(e,t)},SR),Gr=ei("string",Xn.LENGTH_DELIMITED,function(e){const t=_t(e),r=new Uint8Array(Yt.encodingLength(t.byteLength));return Yt.encode(t.length,r),new Vr(r,t)},function(e,t){const r=Yt.decode(e,t);return t+=Yt.encodingLength(r),Mt(e.slice(t,t+r))},function(e){const t=_t(e).byteLength;return Yt.encodingLength(t)+t}),IR=function(e){return Yt.encodingLength(e)},Uf=ei("uint32",Xn.VARINT,function(e){const t=new Uint8Array(IR(e));return Yt.encode(e,t),t},function(e,t){return Yt.decode(e,t)},IR),CR=ei("uint64",Xn.VARINT,function(e){const t=new Uint8Array(dc.encodingLength(e));return dc.encode(e,t),t},function(e,t){return dc.decode(e,t)},function(e){return dc.encodingLength(e)});var Vf=(()=>(function(n){n.codec=()=>ur({1:{name:"payload",codec:fc,optional:!0},2:{name:"contentTopic",codec:Gr,optional:!0},3:{name:"version",codec:Uf,optional:!0},4:{name:"timestampDeprecated",codec:Go,optional:!0},10:{name:"timestamp",codec:zo,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Vf||(Vf={})),Vf))(),cG=N(6577),uG=N(4237);const Ku_algorithm={name:"AES-GCM",length:128},Fp={node:cG,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0};function ms(){if(Fp.web)return Fp.web.subtle;if(Fp.node)return Fp.node.webcrypto.subtle;throw new Error("The environment doesn't have Crypto Subtle API (if in the browser, be sure to use to be in a secure context, ie, https)")}const ju=er.randomBytes,Sw=er.sha256;function lG(n,e){return Iw.apply(this,arguments)}function Iw(){return Iw=V(function*(n,e){const[t,r]=yield z2(n,e,{recovered:!0,der:!1});return Ji([t,new Uint8Array([r])],t.length+1)}),Iw.apply(this,arguments)}function Cw(n){return new Uint8Array(uG.keccak256.arrayBuffer(n))}function TR(n,e){let t=1,r=0,i=Promise.resolve(new Uint8Array);for(;r>24,t>>16,t>>8,t]),o=Ji([s,n],s.length+n.length),a=Sw(o);i=i.then(c=>a.then(m=>{const T=new Uint8Array(m);return Ji([c,T],c.length+T.length)})),r+=32,t+=1}return i}function fG(n,e,t){return ms().importKey("raw",e,"AES-CTR",!1,["encrypt"]).then(r=>ms().encrypt({name:"AES-CTR",counter:n,length:128},r,t)).then(r=>new Uint8Array(r))}function dG(n,e,t){return ms().importKey("raw",e,"AES-CTR",!1,["decrypt"]).then(r=>ms().decrypt({name:"AES-CTR",counter:n,length:128},r,t)).then(r=>new Uint8Array(r))}function hG(n,e){const t={name:"HMAC",hash:{name:"SHA-256"}};return ms().importKey("raw",n,t,!1,["sign"]).then(r=>ms().sign(t,r,e)).then(r=>new Uint8Array(r))}function pG(n,e,t){const r={name:"HMAC",hash:{name:"SHA-256"}};return ms().importKey("raw",n,r,!1,["verify"]).then(s=>ms().verify(r,s,t,e))}function AR(n,e){if(32!==n.length)throw new Error(`Bad private key, it should be 32 bytes but it's actually ${n.length} bytes long`);if(65!==e.length)throw new Error(`Bad public key, it should be 65 bytes but it's actually ${e.length} bytes long`);if(4!==e[0])throw new Error("Bad public key, a valid public key would begin with 4");{const t=function MU(n,e,t=!1){if(H2(n))throw new TypeError("getSharedSecret: first arg must be private key");if(!H2(e))throw new TypeError("getSharedSecret: second arg must be public key");const r=Bm(e);return r.assertValidity(),r.multiply(io(n)).toRawBytes(t)}(n,e,!0);return new Uint8Array(Gs(t).slice(1))}}function gG(n,e){return Tw.apply(this,arguments)}function Tw(){return Tw=V(function*(n,e){const t=ju(32),r=yield AR(t,n),i=yield TR(r,32),s=ju(16),o=i.slice(0,16),a=yield fG(s,o,e),c=Ji([s,a],s.length+a.length),m=yield Sw(i.slice(16)),T=yield hG(m,c),R=rf(t,!1);return Ji([R,c,T],R.length+c.length+T.length)}),Tw.apply(this,arguments)}function yG(n,e){return xw.apply(this,arguments)}function xw(){return xw=V(function*(n,e){if(e.length<=113)throw new Error("Invalid Ciphertext. Data is too small. It should ba at least 113 bytes");if(4!==e[0])throw new Error(`Not a valid ciphertext. It should begin with 4 but actually begin with ${e[0]}`);{const t=e.slice(0,65),r=e.length-113,i=e.slice(65,81),s=e.slice(65,81+r),o=s.slice(16),a=e.slice(81+r),c=AR(n,t),m=yield TR(c,32),[T,R]=yield Sw(m.slice(16)).then(k=>[m.slice(0,16),k]);if(!(yield pG(R,s,a)))throw new Error("Incorrect MAC");return dG(i,T,o)}}),xw.apply(this,arguments)}function mG(n,e,t){return Rw.apply(this,arguments)}function Rw(){return Rw=V(function*(n,e,t){return ms().importKey("raw",e,Ku_algorithm,!1,["encrypt"]).then(r=>ms().encrypt({iv:n,...Ku_algorithm},r,t)).then(r=>new Uint8Array(r))}),Rw.apply(this,arguments)}function vG(n,e,t){return Pw.apply(this,arguments)}function Pw(){return Pw=V(function*(n,e,t){return ms().importKey("raw",e,Ku_algorithm,!1,["decrypt"]).then(r=>ms().decrypt({iv:n,...Ku_algorithm},r,t)).then(r=>new Uint8Array(r))}),Pw.apply(this,arguments)}function EG(){return ju(12)}function RR(n,e){return Ow.apply(this,arguments)}function Ow(){return Ow=V(function*(n,e){let t=new Uint8Array([0]);t=AG(t,n),t=Ji([t,n]);let r=1+MR(n)+n.length;e&&(r+=65);const s=256-r%256,o=ju(s);if(!xG(o,s))throw new Error("failed to generate random padding of size "+s);let a;if(t=Ji([t,o]),e){t[0]|=4;const c=Cw(t),m=yield lG(c,e);t=Ji([t,m]),a={signature:m,publicKey:rf(e,!1)}}return{payload:t,sig:a}}),Ow.apply(this,arguments)}function Lw(){return Lw=V(function*(n,e){return gG(Gs(e),n)}),Lw.apply(this,arguments)}function PR(n,e){return kw.apply(this,arguments)}function kw(){return kw=V(function*(n,e){return yG(e,n)}),kw.apply(this,arguments)}function Bw(){return Bw=V(function*(n,e){const t=EG();return Ji([yield mG(t,Gs(e),n),t])}),Bw.apply(this,arguments)}function NR(n,e){return Fw.apply(this,arguments)}function Fw(){return Fw=V(function*(n,e){const t=n.length-12,r=n.slice(0,t);return vG(n.slice(t),Gs(e),r)}),Fw.apply(this,arguments)}function AG(n,e){const t=MR(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e.length,!0),r=r.slice(0,t),(n=Ji([n,r]))[0]|=t,n}function MR(n){let e=1;for(let t=n.length;t>=256;t/=256)e++;return e}function xG(n,e){return n.length===e&&(e<=3||-1!==n.findIndex(t=>0!==t))}const Pa=Ur("waku:message"),OR=BigInt(1e6);var Hf=(()=>(function(n){n.Asymmetric="asymmetric",n.Symmetric="symmetric"}(Hf||(Hf={})),Hf))();class uo{constructor(e,t,r){this.proto=e,this._signaturePublicKey=t,this._signature=r}static fromUtf8String(e,t,r){return V(function*(){const i=(n=>_t(n,"utf8"))(e);return uo.fromBytes(i,t,r)})()}static fromBytes(e,t,r){return V(function*(){const{timestamp:i,encPublicKey:s,symKey:o,sigPrivKey:a}=Object.assign({timestamp:new Date},r||{});let T,c=e,m=0;if(s&&o)throw"Pass either `encPublicKey` or `symKey`, not both.";if(s){const R=yield RR(c,a);c=yield function CG(n,e){return Lw.apply(this,arguments)}(R.payload,s),T=R.sig,m=1}else if(o){const R=yield RR(c,a);c=yield function TG(n,e){return Bw.apply(this,arguments)}(R.payload,o),T=R.sig,m=1}return new uo({payload:c,timestampDeprecated:i.valueOf()/1e3,timestamp:BigInt(i.valueOf())*OR,version:m,contentTopic:t},T?.publicKey,T?.signature)})()}static decode(e,t){return V(function*(){const r=Vf.decode(e);return uo.decodeProto(r,t)})()}static decodeProto(e,t){return V(function*(){const r=e.payload;let i,s;if(1===e.version&&r){if(void 0===t)return void Pa("Payload is encrypted but no private keys have been provided.");const o=yield Promise.all(t.map(function(){var R=V(function*({key:k,method:U,contentTopics:Q}){if(!Q||e.contentTopic&&Q.includes(e.contentTopic))switch(U){case Hf.Asymmetric:try{return yield PR(r,k)}catch(X){return void Pa("Failed to decrypt message using asymmetric encryption despite decryption method being specified",X)}case Hf.Symmetric:try{return yield NR(r,k)}catch(X){return void Pa("Failed to decrypt message using asymmetric encryption despite decryption method being specified",X)}default:try{return yield NR(r,k)}catch(X){Pa("Failed to decrypt message using symmetric encryption",X);try{return yield PR(r,k)}catch(ae){return void Pa("Failed to decrypt message using asymmetric encryption",ae)}}}});return function(k){return R.apply(this,arguments)}}())),c=o.filter(R=>!!R);if(0===c.length)return void Pa("Failed to decrypt payload.");const m=c[0],T=yield function _G(n){const e=function DG(n){return 3&new DataView(n.buffer).getUint8(0)}(n);if(0===e)return;const t=function SG(n,e){let t=n.slice(1,1+e);return e<4&&(t=Ji([t,new Uint8Array(4-e)],4)),new DataView(t.buffer).getInt32(0,!0)}(n,e),r=1+e,i=n.slice(r,r+t),s=function IG(n){return 4==(4&new DataView(n.buffer).getUint8(0))}(n);let o;if(s){const a=function RG(n){return n.slice(n.length-65,n.length)}(n),c=function PG(n,e){return Cw(e?n.slice(0,n.length-65):n)}(n,s),m=function NG(n,e){const r=new DataView(e.slice(64).buffer).getUint8(0);return function NU(n,e,t,r=!1){return dn.fromSignature(n,e,t).toRawBytes(r)}(n,Po.fromCompact(e.slice(0,64)),r,!1)}(c,a);o={signature:a,publicKey:m}}return{payload:i,sig:o}}(m);if(!T)return void Pa("Failed to decode payload.");Object.assign(e,{payload:T.payload}),i=T.sig?.publicKey,s=T.sig?.signature}return new uo(e,i,s)})()}encode(){return Vf.encode(this.proto)}get payloadAsUtf8(){if(!this.payload)return"";try{return(n=>Mt(this.payload,"utf8"))()}catch(e){return Pa("Could not decode byte as UTF-8",e),""}}get payload(){if(this.proto.payload)return new Uint8Array(this.proto.payload)}get contentTopic(){return this.proto.contentTopic}get version(){return this.proto.version??0}get timestamp(){try{if(this.proto.timestamp)return new Date(Number(this.proto.timestamp/OR));if(this.proto.timestampDeprecated)return new Date(1e3*this.proto.timestampDeprecated)}catch{return}}get signaturePublicKey(){return this._signaturePublicKey}get signature(){return this._signature}}var Up,OG=new Uint8Array(16);function LG(){if(!Up&&!(Up=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Up(OG)}const kG=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,FG=function BG(n){return"string"==typeof n&&kG.test(n)};for(var ti=[],Uw=0;Uw<256;++Uw)ti.push((Uw+256).toString(16).substr(1));const Vp=function HG(n,e,t){var r=(n=n||{}).random||(n.rng||LG)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,e){t=t||0;for(var i=0;i<16;++i)e[t+i]=r[i];return e}return function UG(n){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,t=(ti[n[e+0]]+ti[n[e+1]]+ti[n[e+2]]+ti[n[e+3]]+"-"+ti[n[e+4]]+ti[n[e+5]]+"-"+ti[n[e+6]]+ti[n[e+7]]+"-"+ti[n[e+8]]+ti[n[e+9]]+"-"+ti[n[e+10]]+ti[n[e+11]]+ti[n[e+12]]+ti[n[e+13]]+ti[n[e+14]]+ti[n[e+15]]).toLowerCase();if(!FG(t))throw TypeError("Stringified UUID is invalid");return t}(r)};var Vw;!function(n){let e;var t;(t=e=n.ContentFilter||(n.ContentFilter={})).codec=()=>ur({1:{name:"contentTopic",codec:Gr,optional:!0}}),t.encode=r=>cr(r,t.codec()),t.decode=r=>ar(r,t.codec()),n.codec=()=>ur({1:{name:"subscribe",codec:hR,optional:!0},2:{name:"topic",codec:Gr,optional:!0},3:{name:"contentFilters",codec:n.ContentFilter.codec(),repeats:!0}}),n.encode=t=>cr(t,n.codec()),n.decode=t=>ar(t,n.codec())}(Vw||(Vw={}));var Hp=(()=>(function(n){n.codec=()=>ur({1:{name:"messages",codec:Kp.codec(),repeats:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Hp||(Hp={})),Hp))(),Kf=(()=>(function(n){n.codec=()=>ur({1:{name:"requestId",codec:Gr,optional:!0},2:{name:"request",codec:Vw.codec(),optional:!0},3:{name:"push",codec:Hp.codec(),optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Kf||(Kf={})),Kf))(),Kp=(()=>(function(n){n.codec=()=>ur({1:{name:"payload",codec:fc,optional:!0},2:{name:"contentTopic",codec:Gr,optional:!0},3:{name:"version",codec:Uf,optional:!0},4:{name:"timestampDeprecated",codec:Go,optional:!0},10:{name:"timestamp",codec:zo,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Kp||(Kp={})),Kp))();class $u{constructor(e){this.proto=e}static createRequest(e,t,r,i=!0){return new $u({requestId:r||Vp(),request:{subscribe:i,topic:e,contentFilters:t},push:void 0})}static decode(e){const t=Kf.decode(e);return new $u(t)}encode(){return Kf.encode(this.proto)}get push(){return this.proto.push}get requestId(){return this.proto.requestId}}const jf="/vac/waku/filter/2.0.0-beta1",lo=Ur("waku:filter");class KG{constructor(e,t){this.libp2p=e,this.subscriptions=new Map,this.decryptionKeys=new Map,this.pubSubTopic=t?.pubSubTopic??kp,this.libp2p.handle(jf,this.onRequest.bind(this)).catch(r=>lo("Failed to register filter protocol",r))}subscribe(e,t,r){var i=this;return V(function*(){const s=r?.pubsubTopic??i.pubSubTopic,o=t.map(R=>({contentTopic:R})),a=$u.createRequest(s,o,void 0,!0),c=a.requestId;if(!c)throw new Error("Internal error: createRequest expected to set `requestId`");const m=yield i.getPeer(r?.peerId),T=yield i.newStream(m);try{const R=yield Ln([a.encode()],Ff(),T,Vu(),function(){var k=V(function*(U){return yield Ea(U)});return function(U){return k.apply(this,arguments)}}());lo("response",R)}catch(R){throw lo("Error subscribing to peer ",m.id.toString(),"for content topics",t,": ",R),R}return i.addCallback(c,e),V(function*(){yield i.unsubscribe(s,o,c,m),i.removeCallback(c)})})()}onRequest(e){var t=this;lo("Receiving message push");try{Ln(e.stream,Vu(),function(){var r=V(function*(i){var a,s=!1,o=!1;try{for(var m,c=Tt(i);s=!(m=yield c.next()).done;s=!1){const R=$u.decode(m.value.slice());R.requestId&&R.push?.messages?.length&&(yield t.pushMessages(R.requestId,R.push.messages))}}catch(T){o=!0,a=T}finally{try{s&&null!=c.return&&(yield c.return())}finally{if(o)throw a}}});return function(i){return r.apply(this,arguments)}}()).then(()=>{lo("Receiving pipe closed.")},r=>{lo("Error with receiving pipe",r)})}catch(r){lo("Error decoding message",r)}}pushMessages(e,t){var r=this;return V(function*(){const i=r.subscriptions.get(e);if(!i)return void lo(`No callback registered for request ID ${e}`);const s=Array.from(r.decryptionKeys).map(([o,{method:a,contentTopics:c}])=>({key:o,method:a,contentTopics:c}));for(const o of t){const a=yield uo.decodeProto(o,s);a?i(a):lo("Not able to decode message")}})()}addCallback(e,t){this.subscriptions.set(e,t)}removeCallback(e){this.subscriptions.delete(e)}unsubscribe(e,t,r,i){var s=this;return V(function*(){const o=$u.createRequest(e,t,r,!1),a=yield s.newStream(i);try{yield Ln([o.encode()],Ff(),a.sink)}catch(c){throw lo("Error unsubscribing",c),c}})()}newStream(e){var t=this;return V(function*(){const r=t.libp2p.connectionManager.getConnections(e.id);if(!r)throw new Error("Failed to get a connection to the peer");return r[0].newStream(jf)})()}getPeer(e){var t=this;return V(function*(){let r;if(e){if(r=yield t.libp2p.peerStore.get(e),!r)throw new Error(`Failed to retrieve connection details for provided peer in peer store: ${e.toString()}`)}else if(r=yield t.randomPeer(),!r)throw new Error("Failed to find known peer that registers waku filter protocol");return r})()}addDecryptionKey(e,t){this.decryptionKeys.set(Gs(e),t??{})}deleteDecryptionKey(e){this.decryptionKeys.delete(Gs(e))}peers(){var e=this;return V(function*(){return vw(e.libp2p,[jf])})()}randomPeer(){var e=this;return V(function*(){return yw(yield e.peers())})()}}var jp=(()=>(function(n){n.codec=()=>ur({1:{name:"pubSubTopic",codec:Gr,optional:!0},2:{name:"message",codec:Gp.codec(),optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(jp||(jp={})),jp))(),$p=(()=>(function(n){n.codec=()=>ur({1:{name:"isSuccess",codec:hR,optional:!0},2:{name:"info",codec:Gr,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}($p||($p={})),$p))(),$f=(()=>(function(n){n.codec=()=>ur({1:{name:"requestId",codec:Gr,optional:!0},2:{name:"request",codec:jp.codec(),optional:!0},3:{name:"response",codec:$p.codec(),optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}($f||($f={})),$f))(),Gp=(()=>(function(n){n.codec=()=>ur({1:{name:"payload",codec:fc,optional:!0},2:{name:"contentTopic",codec:Gr,optional:!0},3:{name:"version",codec:Uf,optional:!0},4:{name:"timestampDeprecated",codec:Go,optional:!0},10:{name:"timestamp",codec:zo,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Gp||(Gp={})),Gp))();class Gf{constructor(e){this.proto=e}static createRequest(e,t){return new Gf({requestId:Vp(),request:{message:e.proto,pubSubTopic:t},response:void 0})}static decode(e){const t=$f.decode(e);return new Gf(t)}encode(){return $f.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const zf="/vac/waku/lightpush/2.0.0-beta1";class jG{constructor(e,t){this.libp2p=e,this.pubSubTopic=t?.pubSubTopic??kp}push(e,t){var r=this;return V(function*(){let i;if(t?.peerId){if(i=yield r.libp2p.peerStore.get(t.peerId),!i)throw"Peer is unknown"}else i=yield r.randomPeer();if(!i)throw"No peer available";if(!i.protocols.includes(zf))throw"Peer does not register waku light push protocol";const s=r.libp2p.connectionManager.getConnections(i.id);if(!s)throw"Failed to get a connection to the peer";const o=yield s[0].newStream(zf);try{const c=Gf.createRequest(e,t?.pubSubTopic?t.pubSubTopic:r.pubSubTopic),m=yield Ln([c.encode()],Ff(),o,Vu(),function(){var T=V(function*(R){return yield Ea(R)});return function(R){return T.apply(this,arguments)}}());try{const T=Ji(m);return Gf.decode(T).response||(console.log("No response in PushRPC"),null)}catch(T){console.log("Failed to decode push reply",T)}}catch(a){console.log("Failed to send waku light push request",a)}return null})()}peers(){var e=this;return V(function*(){return vw(e.libp2p,[zf])})()}randomPeer(){var e=this;return V(function*(){return yw(yield e.peers())})()}}const Hw=["/vac/waku/relay/2.0.0-beta2","/vac/waku/relay/2.0.0"];var hc,zp=(()=>(function(n){n.codec=()=>ur({1:{name:"digest",codec:fc,optional:!0},2:{name:"receivedTime",codec:zo,optional:!0},3:{name:"senderTime",codec:zo,optional:!0},4:{name:"pubsubTopic",codec:Gr,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(zp||(zp={})),zp))();!function(n){let e;var r;let t;(r=e=n.Direction||(n.Direction={})).DIRECTION_BACKWARD_UNSPECIFIED="DIRECTION_BACKWARD_UNSPECIFIED",r.DIRECTION_FORWARD="DIRECTION_FORWARD",function(r){r[r.DIRECTION_BACKWARD_UNSPECIFIED=0]="DIRECTION_BACKWARD_UNSPECIFIED",r[r.DIRECTION_FORWARD=1]="DIRECTION_FORWARD"}(t||(t={})),function(r){r.codec=()=>Bp(t)}(e=n.Direction||(n.Direction={})),n.codec=()=>ur({1:{name:"pageSize",codec:CR,optional:!0},2:{name:"cursor",codec:zp.codec(),optional:!0},3:{name:"direction",codec:n.Direction.codec(),optional:!0}}),n.encode=r=>cr(r,n.codec()),n.decode=r=>ar(r,n.codec())}(hc||(hc={}));var Qp,Wp=(()=>(function(n){n.codec=()=>ur({1:{name:"contentTopic",codec:Gr,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Wp||(Wp={})),Wp))(),qp=(()=>(function(n){n.codec=()=>ur({2:{name:"pubSubTopic",codec:Gr,optional:!0},3:{name:"contentFilters",codec:Wp.codec(),repeats:!0},4:{name:"pagingInfo",codec:hc.codec(),optional:!0},5:{name:"startTime",codec:zo,optional:!0},6:{name:"endTime",codec:zo,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(qp||(qp={})),qp))();!function(n){let e;var r;let t;(r=e=n.Error||(n.Error={})).ERROR_NONE_UNSPECIFIED="ERROR_NONE_UNSPECIFIED",r.ERROR_INVALID_CURSOR="ERROR_INVALID_CURSOR",function(r){r[r.ERROR_NONE_UNSPECIFIED=0]="ERROR_NONE_UNSPECIFIED",r[r.ERROR_INVALID_CURSOR=1]="ERROR_INVALID_CURSOR"}(t||(t={})),function(r){r.codec=()=>Bp(t)}(e=n.Error||(n.Error={})),n.codec=()=>ur({2:{name:"messages",codec:Zp.codec(),repeats:!0},3:{name:"pagingInfo",codec:hc.codec(),optional:!0},4:{name:"error",codec:n.Error.codec(),optional:!0}}),n.encode=r=>cr(r,n.codec()),n.decode=r=>ar(r,n.codec())}(Qp||(Qp={}));var Jp,Yp=(()=>(function(n){n.codec=()=>ur({1:{name:"requestId",codec:Gr,optional:!0},2:{name:"query",codec:qp.codec(),optional:!0},3:{name:"response",codec:Qp.codec(),optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Yp||(Yp={})),Yp))(),Zp=(()=>(function(n){n.codec=()=>ur({1:{name:"payload",codec:fc,optional:!0},2:{name:"contentTopic",codec:Gr,optional:!0},3:{name:"version",codec:Uf,optional:!0},4:{name:"timestampDeprecated",codec:Go,optional:!0},10:{name:"timestamp",codec:zo,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Zp||(Zp={})),Zp))(),Xp=(()=>(function(n){n.codec=()=>ur({1:{name:"digest",codec:fc,optional:!0},2:{name:"receivedTime",codec:Go,optional:!0},3:{name:"senderTime",codec:Go,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(Xp||(Xp={})),Xp))();!function(n){let e;var r;let t;(r=e=n.Direction||(n.Direction={})).DIRECTION_BACKWARD_UNSPECIFIED="DIRECTION_BACKWARD_UNSPECIFIED",r.DIRECTION_FORWARD="DIRECTION_FORWARD",function(r){r[r.DIRECTION_BACKWARD_UNSPECIFIED=0]="DIRECTION_BACKWARD_UNSPECIFIED",r[r.DIRECTION_FORWARD=1]="DIRECTION_FORWARD"}(t||(t={})),function(r){r.codec=()=>Bp(t)}(e=n.Direction||(n.Direction={})),n.codec=()=>ur({1:{name:"pageSize",codec:CR,optional:!0},2:{name:"cursor",codec:Xp.codec(),optional:!0},3:{name:"direction",codec:n.Direction.codec(),optional:!0}}),n.encode=r=>cr(r,n.codec()),n.decode=r=>ar(r,n.codec())}(Jp||(Jp={}));var Kw,eg=(()=>(function(n){n.codec=()=>ur({1:{name:"contentTopic",codec:Gr,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(eg||(eg={})),eg))(),tg=(()=>(function(n){n.codec=()=>ur({2:{name:"pubSubTopic",codec:Gr,optional:!0},3:{name:"contentFilters",codec:eg.codec(),repeats:!0},4:{name:"pagingInfo",codec:Jp.codec(),optional:!0},5:{name:"startTime",codec:Go,optional:!0},6:{name:"endTime",codec:Go,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(tg||(tg={})),tg))();!function(n){let e;var r;let t;(r=e=n.Error||(n.Error={})).ERROR_NONE_UNSPECIFIED="ERROR_NONE_UNSPECIFIED",r.ERROR_INVALID_CURSOR="ERROR_INVALID_CURSOR",function(r){r[r.ERROR_NONE_UNSPECIFIED=0]="ERROR_NONE_UNSPECIFIED",r[r.ERROR_INVALID_CURSOR=1]="ERROR_INVALID_CURSOR"}(t||(t={})),function(r){r.codec=()=>Bp(t)}(e=n.Error||(n.Error={})),n.codec=()=>ur({2:{name:"messages",codec:rg.codec(),repeats:!0},3:{name:"pagingInfo",codec:Jp.codec(),optional:!0},4:{name:"error",codec:n.Error.codec(),optional:!0}}),n.encode=r=>cr(r,n.codec()),n.decode=r=>ar(r,n.codec())}(Kw||(Kw={}));var ng=(()=>(function(n){n.codec=()=>ur({1:{name:"requestId",codec:Gr,optional:!0},2:{name:"query",codec:tg.codec(),optional:!0},3:{name:"response",codec:Kw.codec(),optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(ng||(ng={})),ng))(),rg=(()=>(function(n){n.codec=()=>ur({1:{name:"payload",codec:fc,optional:!0},2:{name:"contentTopic",codec:Gr,optional:!0},3:{name:"version",codec:Uf,optional:!0},4:{name:"timestampDeprecated",codec:Go,optional:!0},10:{name:"timestamp",codec:zo,optional:!0}}),n.encode=e=>cr(e,n.codec()),n.decode=e=>ar(e,n.codec())}(rg||(rg={})),rg))(),Na=(()=>(function(n){n.V2Beta3="/vac/waku/store/2.0.0-beta3",n.V2Beta4="/vac/waku/store/2.0.0-beta4"}(Na||(Na={})),Na))();const LR=BigInt(1e6);var Gu=(()=>(function(n){n.BACKWARD="backward",n.FORWARD="forward"}(Gu||(Gu={})),Gu))();class Wf{constructor(e,t){switch(this.proto=e,this.storeCodec=t,t){case Na.V2Beta3:this.historyRpc=ng;break;case Na.V2Beta4:this.historyRpc=Yp;break;default:throw`Internal Error: Unexpected store codec value received in constructor: ${t}`}}get query(){return this.proto.query}get response(){return this.proto.response}static createQuery(e){const t=e.storeCodec??Na.V2Beta4,r=e.contentTopics.map(s=>({contentTopic:s})),i=function GG(n){switch(n){case Gu.BACKWARD:return hc.Direction.DIRECTION_BACKWARD_UNSPECIFIED;case Gu.FORWARD:return hc.Direction.DIRECTION_FORWARD;default:return hc.Direction.DIRECTION_BACKWARD_UNSPECIFIED}}(e.pageDirection);switch(t){case Na.V2Beta3:return(()=>{const s={pageSize:BigInt(e.pageSize),cursor:e.cursor,direction:i};let o,a;return e.startTime&&(o=e.startTime.valueOf()/1e3),e.endTime&&(a=e.endTime.valueOf()/1e3),new Wf({requestId:Vp(),query:{pubSubTopic:e.pubSubTopic,contentFilters:r,pagingInfo:s,startTime:o,endTime:a},response:void 0},t)})();case Na.V2Beta4:return(()=>{const s={pageSize:BigInt(e.pageSize),cursor:e.cursor,direction:i};let o,a;return e.startTime&&(o=BigInt(e.startTime.valueOf())*LR),e.endTime&&(a=BigInt(e.endTime.valueOf())*LR),new Wf({requestId:Vp(),query:{pubSubTopic:e.pubSubTopic,contentFilters:r,pagingInfo:s,startTime:o,endTime:a},response:void 0},t)})();default:throw`Internal Error: Unexpected store codec value received in createQuery: ${t}`}}decode(e){const t=this.historyRpc.decode(e);return new Wf(t,this.storeCodec)}encode(){return this.historyRpc.encode(this.proto)}}var zG=Qp.Error;const pc=Ur("waku:store");class qG{constructor(e,t){this.libp2p=e,this.pubSubTopic=t?.pubSubTopic??kp,this.decryptionKeys=new Map}queryHistory(e,t){var r=this;return V(function*(){let i,s;t?.timeFilter&&(i=t.timeFilter.startTime,s=t.timeFilter.endTime);const o=Object.assign({pubSubTopic:r.pubSubTopic,pageDirection:Gu.BACKWARD,pageSize:10},t,{contentTopics:e,startTime:i,endTime:s});let a;if(pc("Querying history with the following options",{peerId:t?.peerId?.toString(),...t}),o.peerId){if(a=yield r.libp2p.peerStore.get(o.peerId),!a)throw`Failed to retrieve connection details for provided peer in peer store: ${o.peerId.toString()}`}else if(a=yield r.randomPeer(),!a)throw"Failed to find known peer that registers waku store protocol";let c="";for(const U of Object.values(lc))a.protocols.includes(U)&&(c=U);if(pc(`Use store codec ${c}`),!c)throw`Peer does not register waku store protocol: ${a.id.toString()}`;Object.assign(o,{storeCodec:c});const m=r.libp2p.connectionManager.getConnections(a.id);if(!m||!m.length)throw"Failed to get a connection to the peer";const T=Array.from(r.decryptionKeys).map(([U,{method:Q,contentTopics:X}])=>({key:U,method:Q,contentTopics:X}));o.decryptionKeys&&o.decryptionKeys.forEach(U=>{T.push({key:Gs(U),contentTopics:e.length?e:void 0,method:void 0})});const R=[];let k;for(;;){const U=yield m[0].newStream(c),Q=Object.assign(o,{cursor:k}),X=Wf.createQuery(Q);pc("Querying store peer",m[0].remoteAddr.toString());const ae=yield Ln([X.encode()],Ff(),U,Vu(),function(){var mt=V(function*(Zt){return yield Ea(Zt)});return function(Zt){return mt.apply(this,arguments)}}()),he=Ji(ae),Ae=X.decode(he);if(!Ae.response)return pc("No message returned from store: `response` field missing"),R;const ue=Ae.response;if(ue.error&&ue.error!==zG.ERROR_NONE_UNSPECIFIED)throw"History response contains an Error: "+ue.error;if(!ue.messages||!ue.messages.length)return pc("No message returned from store: `messages` array empty"),R;pc(`${ue.messages.length} messages retrieved for (${o.pubSubTopic})`,e);const Re=[];yield Promise.all(ue.messages.map(function(){var mt=V(function*(Zt){const wn=yield uo.decodeProto(Zt,T);wn&&(R.push(wn),Re.push(wn))});return function(Zt){return mt.apply(this,arguments)}}()));let Le=!1;o.callback&&(Le=Boolean(o.callback(Re)));const Fe=ue.pagingInfo?.pageSize,wt=X.query?.pagingInfo?.pageSize;if(Le||Fe&&wt&&Fe(function(n){n.Relay="relay",n.Store="store",n.LightPush="lightpush",n.Filter="filter"}(es||(es={})),es))();class ZG{constructor(e,t,r,i,s){this.libp2p=t,this.relay=t.pubsub,this.store=r,this.filter=s,this.lightPush=i,this.pingKeepAliveTimers={},this.relayKeepAliveTimers={};const o=e.pingKeepAlive||0,a=e.relayKeepAlive||300;t.connectionManager.addEventListener("peer:connect",c=>{this.startKeepAlive(c.detail.remotePeer,o,a)}),t.connectionManager.addEventListener("peer:disconnect",c=>{this.stopKeepAlive(c.detail.remotePeer)}),e?.decryptionKeys?.forEach(c=>{this.addDecryptionKey(c)})}dial(e,t){var r=this;return V(function*(){const i=t??[es.Relay],s=[];if(i.includes(es.Relay)&&Hw.forEach(o=>s.push(o)),i.includes(es.Store))for(const o of Object.values(lc))s.push(o);return i.includes(es.LightPush)&&s.push(zf),i.includes(es.Filter)&&s.push(jf),r.libp2p.dialProtocol(e,s)})()}addPeerToAddressBook(e,t){let r;r="string"==typeof e?_r(e):e;const i=t.map(s=>"string"==typeof s?function G9(n){return new vn(n)}(s):s);this.libp2p.peerStore.addressBook.set(r,i)}start(){var e=this;return V(function*(){yield e.libp2p.start()})()}stop(){var e=this;return V(function*(){e.stopAllKeepAlives(),yield e.libp2p.stop()})()}isStarted(){return this.libp2p.isStarted()}addDecryptionKey(e,t){this.relay.addDecryptionKey(e,t),this.store.addDecryptionKey(e,t),this.filter.addDecryptionKey(e,t)}deleteDecryptionKey(e){this.relay.deleteDecryptionKey(e),this.store.deleteDecryptionKey(e),this.filter.deleteDecryptionKey(e)}getLocalMultiaddrWithID(){const e=this.libp2p.getMultiaddrs().find(t=>t.toString().match(/127\.0\.0\.1/));if(!e||""===e.toString())throw"Not listening on localhost";return e+"/p2p/"+this.libp2p.peerId.toString()}startKeepAlive(e,t,r){this.stopKeepAlive(e);const i=e.toString();0!==t&&(this.pingKeepAliveTimers[i]=setInterval(()=>{this.libp2p.ping(e).catch(s=>{kR(`Ping failed (${i})`,s)})},1e3*t)),0!==r&&(this.relayKeepAliveTimers[i]=setInterval(()=>{kR("Sending Waku Relay ping message"),uo.fromBytes(new Uint8Array,"/relay-ping/1/ping/null").then(s=>this.relay.send(s))},1e3*r))}stopKeepAlive(e){const t=e.toString();this.pingKeepAliveTimers[t]&&(clearInterval(this.pingKeepAliveTimers[t]),delete this.pingKeepAliveTimers[t]),this.relayKeepAliveTimers[t]&&(clearInterval(this.relayKeepAliveTimers[t]),delete this.relayKeepAliveTimers[t])}stopAllKeepAlives(){for(const e of[...Object.values(this.pingKeepAliveTimers),...Object.values(this.relayKeepAliveTimers)])clearInterval(e);this.pingKeepAliveTimers={},this.relayKeepAliveTimers={}}}const BR=Symbol.for("@achingbrain/uint8arraylist");function FR(n,e,t){if(null==e||e<0||e>=t)throw new RangeError("index is out of bounds");let r=0;for(const i of n){const s=r+i.byteLength;if(e0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}slice(e,t){const{bufs:r,length:i}=this._subList(e,t);return or(r,i)}subarray(e,t){const{bufs:r}=this._subList(e,t),i=new ts;return i.appendAll(r),i}_subList(e,t){if(null==e&&null==t)return{bufs:this.bufs,length:this.length};if((e=e??0)<0&&(e=this.length+e),(t=t??(this.length>0?this.length:0))<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index out of bounds");if(e===t)return{bufs:[],length:0};const r=[];let i=0;for(const s of this.bufs){const o=i,a=o+s.byteLength,m=t>o&&t<=a;let R,k;if(i=a,e>=o&&e=a&&(R=0,k=s.byteLength),null!=R&&null!=k&&r.push(s.subarray(R,k)),m)break}return{bufs:r,length:t-e}}getInt8(e){const t=this.slice(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=new Uint8Array(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.slice(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const i=new Uint8Array(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,r),this.write(i,e)}getInt32(e,t){const r=this.slice(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const i=new Uint8Array(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,r),this.write(i,e)}getBigInt64(e,t){const r=this.slice(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const i=new Uint8Array(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,r),this.write(i,e)}getUint8(e){const t=this.slice(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=new Uint8Array(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.slice(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const i=new Uint8Array(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,r),this.write(i,e)}getUint32(e,t){const r=this.slice(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const i=new Uint8Array(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,r),this.write(i,e)}getBigUint64(e,t){const r=this.slice(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const i=new Uint8Array(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,r),this.write(i,e)}getFloat32(e,t){const r=this.slice(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const i=new Uint8Array(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,r),this.write(i,e)}getFloat64(e,t){const r=this.slice(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const i=new Uint8Array(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,r),this.write(i,e)}}function zu(n){return n instanceof Uint8Array?{get:e=>n[e],set(e,t){n[e]=t}}:{get:e=>n.get(e),set(e,t){n.set(e,t)}}}const VR=4294967296;class Ui{constructor(e=0,t=0){this.hi=e,this.lo=t}toBigInt(e){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const t=1+~this.lo>>>0;let r=~this.hi>>>0;return 0===t&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}zzDecode(){const e=-(1&this.lo);return new Ui((this.hi>>>1^e)>>>0,((this.lo>>>1|this.hi<<31)^e)>>>0)}zzEncode(){const e=this.hi>>31;return new Ui(((this.hi<<1|this.lo>>>31)^e)>>>0,(this.lo<<1^e)>>>0)}toBytes(e,t=0){const r=zu(e);for(;this.hi>0;)r.set(t++,127&this.lo|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)r.set(t++,127&this.lo|128),this.lo=this.lo>>>7;r.set(t++,this.lo)}static fromBigInt(e){if(0n===e)return new Ui;const t=e<0;t&&(e=-e);let r=0|Number(e>>32n),i=0|Number(e-(BigInt(r)<<32n));return t&&(r=~r>>>0,i=~i>>>0,++i>VR&&(i=0,++r>VR&&(r=0))),new Ui(r,i)}static fromNumber(e){if(0===e)return new Ui;const t=e<0;t&&(e=-e);let r=e>>>0,i=(e-r)/4294967296>>>0;return t&&(i=~i>>>0,r=~r>>>0,++r>4294967295&&(r=0,++i>4294967295&&(i=0))),new Ui(i,r)}static fromBytes(e,t){const r=zu(e),i=new Ui;let s=0;if(!(e.length-t>4)){for(;s<3;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.lo=(i.lo|(127&r.get(t))<<7*s)>>>0,r.get(t++)<128)return i}return i.lo=(i.lo|(127&r.get(t++))<<7*s)>>>0,i}for(;s<4;++s)if(i.lo=(i.lo|(127&r.get(t))<<7*s)>>>0,r.get(t++)<128)return i;if(i.lo=(i.lo|(127&r.get(t))<<28)>>>0,i.hi=(i.hi|(127&r.get(t))>>4)>>>0,r.get(t++)<128)return i;if(s=0,e.length-t>4){for(;s<5;++s)if(i.hi=(i.hi|(127&r.get(t))<<7*s+3)>>>0,r.get(t++)<128)return i}else for(;s<5;++s){if(t>=e.length)throw RangeError(`index out of range: ${t} > ${e.length}`);if(i.hi=(i.hi|(127&r.get(t))<<7*s+3)>>>0,r.get(t++)<128)return i}throw Error("invalid varint encoding")}}const ez=Math.pow(2,31),tz=Math.pow(2,7),nz=Math.pow(2,14),rz=Math.pow(2,21),iz=Math.pow(2,28),sz=Math.pow(2,35),oz=Math.pow(2,42),az=Math.pow(2,49),cz=Math.pow(2,56),uz=Math.pow(2,63),fn={encodingLength:n=>n=ez;)r.set(t++,255&n|128),n/=128;for(;(-128&n)>0;)r.set(t++,255&n|128),n>>>=7;r.set(t,0|n)},decode(n,e=0){const t=zu(n);let r=4294967295;if(r=(127&t.get(e))>>>0,t.get(e++)<128||(r=(r|(127&t.get(e))<<7)>>>0,t.get(e++)<128)||(r=(r|(127&t.get(e))<<14)>>>0,t.get(e++)<128)||(r=(r|(127&t.get(e))<<21)>>>0,t.get(e++)<128)||(r=(r|(15&t.get(e))<<28)>>>0,t.get(e++)<128))return r;if((e+=5)>n.length)throw RangeError(`index out of range: ${e} > ${n.length}`);return r}},jw={encodingLength:n=>n<0?10:fn.encodingLength(n),encode(n,e){if(n<0){let t=0;const r=zu(e),i=Ui.fromNumber(n);for(;i.hi>0;)r.set(t++,127&i.lo|128),i.lo=(i.lo>>>7|i.hi<<25)>>>0,i.hi>>>=7;for(;i.lo>127;)r.set(t++,127&i.lo|128),i.lo=i.lo>>>7;r.set(t++,i.lo)}else fn.encode(n,e)},decode:(n,e=0)=>0|fn.decode(n,e)},$w={encodingLength:n=>fn.encodingLength(n=(n<<1^n>>31)>>>0),encode:(n,e,t=0)=>fn.encode(n=(n<<1^n>>31)>>>0,e),decode(n,e=0){const t=fn.decode(n,e);return t>>>1^-(1&t)|0}};function Gw(n,e){const t=new Uint8Array(fn.encodingLength(n.length));return fn.encode(n.length,t),e.decode(new ts(t,n),0)}function zw(n,e){const t=e.encode(n),r=fn.encodingLength(fn.decode(t));return t.slice(r)}var nr=(()=>(function(n){n[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32"}(nr||(nr={})),nr))();function yi(n,e,t,r,i){return{name:n,type:e,encode:t,decode:r,encodingLength:i}}yi("bool",nr.VARINT,function(e){return Uint8Array.from([e?1:0])},function(e,t){return e.get(t)>0},function(){return 1});const Wu=yi("bytes",nr.LENGTH_DELIMITED,function(e){const t=new Uint8Array(fn.encodingLength(e.byteLength));return fn.encode(e.byteLength,t),new ts(t,e)},function(e,t){const r=fn.decode(e,t);return t+=fn.encodingLength(r),e.slice(t,t+r)},function(e){const t=e.byteLength;return fn.encodingLength(t)+t});yi("double",nr.BIT64,function(e){const t=new ts(new Uint8Array(8));return t.setFloat64(0,e,!0),t},function(e,t){return e.getFloat64(t,!0)},function(){return 8});const $R=(yi("fixed32",nr.BIT32,function(e){const t=new ts(new Uint8Array(4));return t.setInt32(0,e,!0),t},function(e,t){return e.getInt32(t,!0)},function(){return 4}),function(e){return 8}),GR=(yi("fixed64",nr.BIT64,function(e){const t=new ts(new Uint8Array(8));return t.setBigInt64(0,e,!0),t},function(e,t){return e.getBigInt64(t,!0)},$R),function(){return 4}),zR=(yi("float",nr.BIT32,function(e){const t=new ts(new Uint8Array(4));return t.setFloat32(0,e,!0),t},function(e,t){return e.getFloat32(t,!0)},GR),function(e){return jw.encodingLength(e)}),WR=(yi("int32",nr.VARINT,function(e){const t=new Uint8Array(zR(e));return jw.encode(e,t),t},function(e,t){return jw.decode(e,t)},zR),0x7fn),gc={encodingLength(n){let e=0;for(;n>=0x80n;e++)n>>=7n;return e+1},encode(n,e){const t=zu(e);let r=0;for(;WR>=7n;t.set(r,Number(n))},decode:(n,e=0)=>Ui.fromBytes(n,e).toBigInt(!0)},Ww={encodingLength:n=>n<0n?10:gc.encodingLength(n),encode(n,e,t=0){if(!(n<0n))return gc.encode(n,e);Ui.fromBigInt(n).toBytes(e,t)},decode:(n,e=0)=>Ui.fromBytes(n,e).toBigInt(!1)},qw={encodingLength:n=>gc.encodingLength(n>=0?2n*n:-2n*n-1n),encode(n,e,t=0){Ui.fromBigInt(n).zzEncode().toBytes(e,t)},decode:(n,e=0)=>Ui.fromBytes(n,e).zzDecode().toBigInt(!1)},qR=function(e){return Ww.encodingLength(e)};function Qw(n){return yi("message",nr.LENGTH_DELIMITED,function(s){const o=new ts;function a(m,T,R){if(null==m){if(!0===R.optional)return;throw new Error(`Non optional field "${R.name}" was ${null===m?"null":"undefined"}`)}const k=T<<3|R.codec.type,U=new Uint8Array(fn.encodingLength(k));fn.encode(k,U);const Q=R.codec.encode(m);o.append(U),o.append(Q)}for(const[m,T]of Object.entries(n)){const R=parseInt(m);if(!0===T.repeats){if(!Array.isArray(s[T.name]))throw new Error(`Repeating field "${T.name}" was not an array`);for(const k of s[T.name])a(k,R,T)}else a(s[T.name],R,T)}const c=new Uint8Array(fn.encodingLength(o.length));return fn.encode(o.length,c),new ts(c,o)},function(s,o){const a=fn.decode(s,o),c=(o+=fn.encodingLength(a))+a,m={};for(;o>3];let Q=0;if(R===nr.VARINT)if(null!=U){const X=U.codec.decode(s,o);Q=U.codec.encodingLength(X)}else{const X=fn.decode(s,o);Q=fn.encodingLength(X)}else if(R===nr.BIT64)Q=8;else if(R===nr.LENGTH_DELIMITED){const X=fn.decode(s,o);Q=X+fn.encodingLength(X)}else if(R===nr.BIT32)Q=4;else{if(R===nr.START_GROUP)throw new Error("Unsupported wire type START_GROUP");if(R===nr.END_GROUP)throw new Error("Unsupported wire type END_GROUP")}if(null!=U){const X=U.codec.decode(s,o);!0===U.repeats?(null==m[U.name]&&(m[U.name]=[]),m[U.name].push(X)):m[U.name]=X}o+=Q}for(const T of Object.values(n))!0===T.repeats&&null==m[T.name]&&(m[T.name]=[]);return m},function(s){let o=0;for(const a of Object.values(n))o+=a.codec.encodingLength(s[a.name]);return fn.encodingLength(o)+o})}yi("int64",nr.VARINT,function(e){const t=new Uint8Array(qR(e));return Ww.encode(e,t),t},function(e,t){return 0n|Ww.decode(e,t)},qR);const YR=(yi("sfixed32",nr.BIT32,function(e){const t=new ts(new Uint8Array(4));return t.setInt32(0,e,!0),t},function(e,t){return e.getInt32(t,!0)},function(){return 4}),function(){return 8}),ZR=(yi("sfixed64",nr.BIT64,function(e){const t=new ts(new Uint8Array(8));return t.setBigInt64(0,e,!0),t},function(e,t){return e.getBigInt64(t,!0)},YR),function(e){return $w.encodingLength(e)}),XR=(yi("sint32",nr.VARINT,function(e){const t=new Uint8Array(ZR(e));return $w.encode(e,t),t},function(e,t){return $w.decode(e,t)},ZR),function(e){return qw.encodingLength(e)}),JR=(yi("sint64",nr.VARINT,function(e){const t=new Uint8Array(XR(e));return qw.encode(e,t),t},function(e,t){return qw.decode(e,t)},XR),yi("string",nr.LENGTH_DELIMITED,function(e){const t=_t(e),r=new Uint8Array(fn.encodingLength(t.byteLength));return fn.encode(t.length,r),new ts(r,t)},function(e,t){const r=fn.decode(e,t);return t+=fn.encodingLength(r),Mt(e.slice(t,t+r))},function(e){const t=_t(e).byteLength;return fn.encodingLength(t)+t}),function(e){return fn.encodingLength(e)}),$z=(yi("uint32",nr.VARINT,function(e){const t=new Uint8Array(JR(e));return fn.encode(e,t),t},function(e,t){return fn.decode(e,t)},JR),yi("uint64",nr.VARINT,function(e){const t=new Uint8Array(gc.encodingLength(e));return gc.encode(e,t),t},function(e,t){return gc.decode(e,t)},function(e){return gc.encodingLength(e)}));var qf=(()=>(function(n){n.codec=()=>Qw({1:{name:"publicKey",codec:Wu},2:{name:"payloadType",codec:Wu},3:{name:"payload",codec:Wu},5:{name:"signature",codec:Wu}}),n.encode=e=>zw(e,n.codec()),n.decode=e=>Gw(e,n.codec())}(qf||(qf={})),qf))();class Ma{constructor(e){const{peerId:t,payloadType:r,payload:i,signature:s}=e;this.peerId=t,this.payloadType=r,this.payload=i,this.signature=s}marshal(){if(null==this.peerId.publicKey)throw new Error("Missing public key");return null==this.marshaled&&(this.marshaled=qf.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload,signature:this.signature})),this.marshaled}equals(e){return $r(this.marshal(),e.marshal())}validate(e){var t=this;return V(function*(){const r=eP(e,t.payloadType,t.payload);if(null==t.peerId.publicKey)throw new Error("Missing public key");return yield Tu(t.peerId.publicKey).verify(r,t.signature)})()}}Ma.createFromProtobuf=function(){var n=V(function*(e){const t=qf.decode(e),r=yield xu(t.publicKey);return new Ma({peerId:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})});return function(e){return n.apply(this,arguments)}}(),Ma.seal=function(){var n=V(function*(e,t){const r=e.domain,i=e.codec,s=e.marshal(),o=eP(r,i,s);if(null==t.privateKey)throw new Error("Missing private key");const c=yield(yield Au(t.privateKey)).sign(o);return new Ma({peerId:t,payloadType:i,payload:s,signature:c})});return function(e,t){return n.apply(this,arguments)}}(),Ma.openAndCertify=function(){var n=V(function*(e,t){const r=yield Ma.createFromProtobuf(e);if(!(yield r.validate(t)))throw se(new Error("envelope signature is not valid for the given domain"),"ERR_SIGNATURE_NOT_VALID");return r});return function(e,t){return n.apply(this,arguments)}}();const eP=(n,e,t)=>{const r=_t(n),i=Vn.encode(r.byteLength),s=Vn.encode(e.length),o=Vn.encode(t.length);return or([new Uint8Array(i),r,new Uint8Array(s),e,new Uint8Array(o),t])};var tP;!function(n){let e;var t;(t=e=n.AddressInfo||(n.AddressInfo={})).codec=()=>Qw({1:{name:"multiaddr",codec:Wu}}),t.encode=r=>zw(r,t.codec()),t.decode=r=>Gw(r,t.codec()),n.codec=()=>Qw({1:{name:"peerId",codec:Wu},2:{name:"seq",codec:$z},3:{name:"addresses",codec:n.AddressInfo.codec(),repeats:!0}}),n.encode=t=>zw(t,n.codec()),n.decode=t=>Gw(t,n.codec())}(tP||(tP={})),Uint8Array.from([3,1]);const nP=()=>{};class zz{constructor(e){this.min=e.min??0,this.max=e.max??1/0,this.peers=new Set,this.onConnect=e.onConnect??nP,this.onDisconnect=e.onDisconnect??nP}get[Symbol.toStringTag](){return jE.toString()}get[jE](){return!0}setRegistrar(e){var t=this;return V(function*(){t.registrar=e})()}disconnect(e){this.onDisconnect(e)}}class qz{constructor(e,t,r){this.gossip=e,this.msgs=new Map,this.history=[],this.msgIdToStrFn=r;for(let i=0;i{const s=this.msgs.get(i.msgIdStr);if(s&&s.validated&&e.has(i.topic)){let o=t.get(i.topic);o||(o=[],t.set(i.topic,o)),o.push(i.msgId)}});return t}validate(e){const t=this.msgs.get(e);if(!t)return null;const{message:r,originatingPeers:i}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:i}}shift(){this.history[this.history.length-1].forEach(t=>{this.msgs.delete(t.msgIdStr)}),this.history.pop(),this.history.unshift([])}remove(e){const t=this.msgs.get(e);return t?(this.msgs.delete(e),t):null}}var Qz=N(8479);const{RPC:ig}=Qz,rP="/floodsub/1.0.0",iP="/meshsub/1.0.0",Zw="/meshsub/1.1.0",Qu=5e3;function Wo(n=[],e){return{subscriptions:[],messages:n,control:e?{graft:e.graft||[],prune:e.prune||[],ihave:e.ihave||[],iwant:e.iwant||[]}:void 0}}function qo(n){if(n.length<=1)return n;for(let t=0;t(function(n){n.StrictSign="StrictSign",n.StrictNoSign="StrictNoSign"}(og||(og={})),og))(),Oa=(()=>(function(n){n[n.Signing=0]="Signing",n[n.Author=1]="Author",n[n.Anonymous=2]="Anonymous"}(Oa||(Oa={})),Oa))(),fo=(()=>(function(n){n.Accept="accept",n.Ignore="ignore",n.Reject="reject"}(fo||(fo={})),fo))(),vs=(()=>(function(n){n.Error="error",n.Ignore="ignore",n.Reject="reject",n.Blacklisted="blacklisted"}(vs||(vs={})),vs))(),Ai=(()=>(function(n){n.InvalidSignature="invalid_signature",n.InvalidSeqno="invalid_seqno",n.InvalidPeerId="invalid_peerid",n.SignaturePresent="signature_present",n.SeqnoPresent="seqno_present",n.FromPresent="from_present",n.TransformFailed="transform_failed"}(Ai||(Ai={})),Ai))(),Es=(()=>(function(n){n.duplicate="duplicate",n.invalid="invalid",n.valid="valid"}(Es||(Es={})),Es))();function oP(n){switch(n){case fo.Ignore:return vs.Ignore;case fo.Reject:return vs.Reject}}function Jw(){return Jw=V(function*(n,e){switch(n){case sg:{if(!e)throw Error("Must provide PeerId");if(null==e.privateKey)throw Error("Cannot sign message, no private key present");if(null==e.publicKey)throw Error("Cannot sign message, no public key present");const t=yield Au(e.privateKey);return{type:Oa.Signing,author:e,key:e.publicKey,privateKey:t}}case Xw:return{type:Oa.Anonymous};default:throw new Error(`Unknown signature policy "${n}"`)}}),Jw.apply(this,arguments)}const qn="ERR_INVALID_PEER_SCORE_PARAMS",AW={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:36e5},xW={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function RW(n={}){return{...AW,...n,topics:n.topics?Object.entries(n.topics).reduce((e,[t,r])=>(e[t]=function PW(n={}){return{...xW,...n}}(r),e),{}):{}}}function MW(n){if(n.topicWeight<0)throw se(new Error("invalid topic weight; must be >= 0"),qn);if(0===n.timeInMeshQuantum)throw se(new Error("invalid TimeInMeshQuantum; must be non zero"),qn);if(n.timeInMeshWeight<0)throw se(new Error("invalid TimeInMeshWeight; must be positive (or 0 to disable)"),qn);if(0!==n.timeInMeshWeight&&n.timeInMeshQuantum<=0)throw se(new Error("invalid TimeInMeshQuantum; must be positive"),qn);if(0!==n.timeInMeshWeight&&n.timeInMeshCap<=0)throw se(new Error("invalid TimeInMeshCap; must be positive"),qn);if(n.firstMessageDeliveriesWeight<0)throw se(new Error("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)"),qn);if(0!==n.firstMessageDeliveriesWeight&&(n.firstMessageDeliveriesDecay<=0||n.firstMessageDeliveriesDecay>=1))throw se(new Error("invalid FirstMessageDeliveriesDecay; must be between 0 and 1"),qn);if(0!==n.firstMessageDeliveriesWeight&&n.firstMessageDeliveriesCap<=0)throw se(new Error("invalid FirstMessageDeliveriesCap; must be positive"),qn);if(n.meshMessageDeliveriesWeight>0)throw se(new Error("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)"),qn);if(0!==n.meshMessageDeliveriesWeight&&(n.meshMessageDeliveriesDecay<=0||n.meshMessageDeliveriesDecay>=1))throw se(new Error("invalid MeshMessageDeliveriesDecay; must be between 0 and 1"),qn);if(0!==n.meshMessageDeliveriesWeight&&n.meshMessageDeliveriesCap<=0)throw se(new Error("invalid MeshMessageDeliveriesCap; must be positive"),qn);if(0!==n.meshMessageDeliveriesWeight&&n.meshMessageDeliveriesThreshold<=0)throw se(new Error("invalid MeshMessageDeliveriesThreshold; must be positive"),qn);if(n.meshMessageDeliveriesWindow<0)throw se(new Error("invalid MeshMessageDeliveriesWindow; must be non-negative"),qn);if(0!==n.meshMessageDeliveriesWeight&&n.meshMessageDeliveriesActivation<1e3)throw se(new Error("invalid MeshMessageDeliveriesActivation; must be at least 1s"),qn);if(n.meshFailurePenaltyWeight>0)throw se(new Error("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)"),qn);if(0!==n.meshFailurePenaltyWeight&&(n.meshFailurePenaltyDecay<=0||n.meshFailurePenaltyDecay>=1))throw se(new Error("invalid MeshFailurePenaltyDecay; must be between 0 and 1"),qn);if(n.invalidMessageDeliveriesWeight>0)throw se(new Error("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)"),qn);if(n.invalidMessageDeliveriesDecay<=0||n.invalidMessageDeliveriesDecay>=1)throw se(new Error("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1"),qn)}const OW={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function LW(n={}){return{...OW,...n}}function kW(n,e,t,r){let i=0;if(Object.entries(e.topics).forEach(([o,a])=>{const c=t.topics[o];if(void 0===c)return;let m=0;if(a.inMesh){let U=a.meshTime/c.timeInMeshQuantum;U>c.timeInMeshCap&&(U=c.timeInMeshCap),m+=U*c.timeInMeshWeight}let T=a.firstMessageDeliveries;if(T>c.firstMessageDeliveriesCap&&(T=c.firstMessageDeliveriesCap),m+=T*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries0&&i>t.topicScoreCap&&(i=t.topicScoreCap),i+=t.appSpecificScore(n)*t.appSpecificWeight,e.ips.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;const a=r.get(o),c=a?a.size:0;if(c>t.IPColocationFactorThreshold){const m=c-t.IPColocationFactorThreshold;i+=m*m*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){const o=e.behaviourPenalty-t.behaviourPenaltyThreshold;i+=o*o*t.behaviourPenaltyWeight}return i}var BW=N(1807),xi=(()=>(function(n){n[n.unknown=0]="unknown",n[n.valid=1]="valid",n[n.invalid=2]="invalid",n[n.ignored=3]="ignored"}(xi||(xi={})),xi))();class FW{constructor(){this.records=new Map,this.queue=new BW}ensureRecord(e){let t=this.records.get(e);if(t)return t;t={status:xi.unknown,firstSeen:Date.now(),validated:0,peers:new Set},this.records.set(e,t);const r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){const e=Date.now();let t=this.queue.peekFront();for(;t&&t.expire0)throw se(new Error("invalid IPColocationFactorWeight; must be negative (or 0 to disable)"),qn);if(0!==n.IPColocationFactorWeight&&n.IPColocationFactorThreshold<1)throw se(new Error("invalid IPColocationFactorThreshold; must be at least 1"),qn);if(n.behaviourPenaltyWeight>0)throw se(new Error("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)"),qn);if(0!==n.behaviourPenaltyWeight&&(n.behaviourPenaltyDecay<=0||n.behaviourPenaltyDecay>=1))throw se(new Error("invalid BehaviourPenaltyDecay; must be between 0 and 1"),qn);if(n.decayInterval<1e3)throw se(new Error("invalid DecayInterval; must be at least 1s"),qn);if(n.decayToZero<=0||n.decayToZero>=1)throw se(new Error("invalid DecayToZero; must be between 0 and 1"),qn)}(e),this.scoreCacheValidityMs=r.scoreCacheValidityMs,this.computeScore=r.computeScore??kW}init(e){this.components=e}get size(){return this.peerStats.size}start(){this._backgroundInterval?Yu("Peer score already running"):(this._backgroundInterval=setInterval(()=>this.background(),this.params.decayInterval),Yu("started"))}stop(){this._backgroundInterval?(clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),Yu("stopped")):Yu("Peer score already stopped")}background(){this.refreshScores(),this.updateIPs(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}refreshScores(){const e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((r,i)=>{r.connected?(Object.entries(r.topics).forEach(([s,o])=>{const a=this.params.topics[s];void 0!==a&&(o.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,o.firstMessageDeliveriesa.meshMessageDeliveriesActivation&&(o.meshMessageDeliveriesActive=!0)))}),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenaltyr.expire&&(this.removeIPs(i,r.ips),this.peerStats.delete(i),this.scoreCache.delete(i))})}score(e){this.metrics?.scoreFnCalls.inc();const t=this.peerStats.get(e);if(!t)return 0;const r=Date.now(),i=this.scoreCache.get(e);if(i&&i.cacheUntil>r)return i.score;this.metrics?.scoreFnRuns.inc();const s=this.computeScore(e,t,this.params,this.peerIPs),o=r+this.scoreCacheValidityMs;return i?(this.metrics?.scoreCachedDelta.observe(Math.abs(s-i.score)),i.score=s,i.cacheUntil=o):this.scoreCache.set(e,{score:s,cacheUntil:o}),s}addPenalty(e,t,r){const i=this.peerStats.get(e);i&&(i.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){const t={connected:!0,expire:0,topics:{},ips:[],behaviourPenalty:0};this.peerStats.set(e,t);const r=this.getIPs(e);this.setIPs(e,r,t.ips),t.ips=r}removePeer(e){const t=this.peerStats.get(e);if(t){if(this.score(e)>0)return this.removeIPs(e,t.ips),void this.peerStats.delete(e);Object.entries(t.topics).forEach(([r,i])=>{i.firstMessageDeliveries=0;const s=this.params.topics[r].meshMessageDeliveriesThreshold;if(i.inMesh&&i.meshMessageDeliveriesActive&&i.meshMessageDeliveries{o!==e.toString()&&this.markDuplicateMessageDelivery(o,r)})):Yu("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,s-i.firstSeen,xi[i.status])}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,i){switch(i){case vs.Error:return void this.markInvalidMessageDelivery(e,r);case vs.Blacklisted:return}const s=this.deliveryRecords.ensureRecord(t);if(s.status===xi.unknown)return i===vs.Ignore?(s.status=xi.ignored,void s.peers.clear()):(s.status=xi.invalid,this.markInvalidMessageDelivery(e,r),s.peers.forEach(o=>{this.markInvalidMessageDelivery(o,r)}),void s.peers.clear());Yu("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-s.firstSeen,xi[s.status])}duplicateMessage(e,t,r){const i=this.deliveryRecords.ensureRecord(t);if(!i.peers.has(e))switch(i.status){case xi.unknown:i.peers.add(e);break;case xi.valid:i.peers.add(e),this.markDuplicateMessageDelivery(e,r,i.validated);break;case xi.invalid:this.markInvalidMessageDelivery(e,r)}}markInvalidMessageDelivery(e,t){const r=this.peerStats.get(e);if(r){const i=this.getPtopicStats(r,t);i&&(i.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){const r=this.peerStats.get(e);if(r){const i=this.getPtopicStats(r,t);if(i){let s=this.params.topics[t].firstMessageDeliveriesCap;i.firstMessageDeliveries=Math.min(s,i.firstMessageDeliveries+1),i.inMesh&&(s=this.params.topics[t].meshMessageDeliveriesCap,i.meshMessageDeliveries=Math.min(s,i.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){const i=this.peerStats.get(e);if(i){const s=void 0!==r?Date.now():0,o=this.getPtopicStats(i,t);if(o&&o.inMesh){const a=this.params.topics[t];if(void 0!==r){const m=s-r,T=m>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,m,T),T)return}o.meshMessageDeliveries=Math.min(a.meshMessageDeliveriesCap,o.meshMessageDeliveries+1)}}}getIPs(e){return this.components.getConnectionManager().getConnections(_r(e)).map(t=>t.remoteAddr.toOptions().host)}setIPs(e,t,r){e:for(const i of t){for(const o of r)if(i===o)continue e;let s=this.peerIPs.get(i);s||(s=new Set,this.peerIPs.set(i,s)),s.add(e)}e:for(const i of r){for(const o of t)if(i===o)continue e;const s=this.peerIPs.get(i);!s||(s.delete(e),s.size||this.peerIPs.delete(i))}}removeIPs(e,t){t.forEach(r=>{const i=this.peerIPs.get(r);!i||(i.delete(e),i.size||this.peerIPs.delete(r))})}updateIPs(){this.peerStats.forEach((e,t)=>{const r=this.getIPs(t);this.setIPs(t,r,e.ips),e.ips=r})}getPtopicStats(e,t){let r=e.topics[t];return void 0!==r?r:void 0!==this.params.topics[t]?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}}class VW{constructor(e,t,r){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=r,this.promises=new Map,this.requestMsByMsg=new Map,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){const r=Math.floor(Math.random()*t.length),s=this.msgIdToStrFn(t[r]);let o=this.promises.get(s);o||(o=new Map,this.promises.set(s,o));const a=Date.now();o.has(e)||(o.set(e,a+this.gossipsubIWantFollowupMs),this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(s)||this.requestMsByMsg.set(s,a)))}getBrokenPromises(){const e=Date.now(),t=new Map;let r=0;return this.promises.forEach((i,s)=>{i.forEach((o,a)=>{o=Date.now()?t.value:void 0}clear(){this.entries.clear()}}var Qo=(()=>(function(n){n.Fanout="fanout",n.Random="random",n.Subscribed="subscribed",n.Outbound="outbound",n.NotEnough="not_enough",n.Opportunistic="opportunistic"}(Qo||(Qo={})),Qo))(),yc=(()=>(function(n){n.Dc="disconnected",n.BadScore="bad_score",n.Prune="prune",n.Unsub="unsubscribed",n.Excess="excess"}(yc||(yc={})),yc))(),Zu=(()=>(function(n){n.GraftBackoff="graft_backoff",n.BrokenPromise="broken_promise",n.MessageDeficit="message_deficit",n.IPColocation="IP_colocation"}(Zu||(Zu={})),Zu))(),Xu=(()=>(function(n){n.LowScore="low_score",n.MaxIhave="max_ihave",n.MaxIasked="max_iasked"}(Xu||(Xu={})),Xu))(),mc=(()=>(function(n){n.graylist="graylist",n.publish="publish",n.gossip="gossip",n.mesh="mesh"}(mc||(mc={})),mc))();const aP=_t("libp2p-pubsub:");function tb(){return tb=V(function*(n,e,t){switch(n.type){case Oa.Signing:{const r={from:n.author.toBytes(),data:t,seqno:sf(8),topic:e,signature:void 0,key:void 0},i=or([aP,ig.Message.encode(r).finish()]);return r.signature=yield n.privateKey.sign(i),r.key=n.key,r}case Oa.Author:return{from:n.author.toBytes(),data:t,seqno:sf(8),topic:e,signature:void 0,key:void 0};case Oa.Anonymous:return{from:void 0,data:t,seqno:void 0,topic:e,signature:void 0,key:void 0}}}),tb.apply(this,arguments)}function nb(){return nb=V(function*(n,e){switch(n){case Xw:return null!=e.signature?{valid:!1,error:Ai.SignaturePresent}:null!=e.seqno?{valid:!1,error:Ai.SeqnoPresent}:null!=e.key?{valid:!1,error:Ai.FromPresent}:{valid:!0,fromPeerId:null};case sg:{if(null==e.seqno)return{valid:!1,error:Ai.InvalidSeqno};if(8!==e.seqno.length)return{valid:!1,error:Ai.InvalidSeqno};if(null==e.signature)return{valid:!1,error:Ai.InvalidSignature};if(null==e.from)return{valid:!1,error:Ai.InvalidPeerId};let t,r;try{t=pa(e.from)}catch{return{valid:!1,error:Ai.InvalidPeerId}}if(e.key){if(r=Tu(e.key),void 0!==t.publicKey&&!$r(r.bytes,t.publicKey))return{valid:!1,error:Ai.InvalidPeerId}}else{if(null==t.publicKey)return{valid:!1,error:Ai.InvalidPeerId};r=Tu(t.publicKey)}const s=or([aP,ig.Message.encode({from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0}).finish()]);return(yield r.verify(s,e.signature))?{valid:!0,fromPeerId:t}:{valid:!1,error:Ai.InvalidSignature}}}}),nb.apply(this,arguments)}function WW(n){if(null==n.sequenceNumber)throw Error("missing seqno field");return((n,e)=>{const t=_t(e.toString(16).padStart(16,"0"),"base16"),r=new Uint8Array(n.length+t.length);return r.set(n,0),r.set(t,n.length),r})(n.from.toBytes(),n.sequenceNumber)}function qW(n){return rb.apply(this,arguments)}function rb(){return rb=V(function*(n){return yield Li.encode(n.data)}),rb.apply(this,arguments)}function QW(n,e,t,r,i){let s=0;const o=new Map;if(Object.entries(e.topics).forEach(([k,U])=>{const Q=i.get(k)??"unknown",X=t.topics[k];if(void 0===X)return;let ae=o.get(Q);ae||(ae={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(Q,ae));let he=0,Ae=0,ue=0,Re=0,Le=0;U.inMesh&&(he+=Math.max(U.meshTime/X.timeInMeshQuantum,X.timeInMeshCap)*X.timeInMeshWeight);let Fe=U.firstMessageDeliveries;if(Fe>X.firstMessageDeliveriesCap&&(Fe=X.firstMessageDeliveriesCap),Ae+=Fe*X.firstMessageDeliveriesWeight,U.meshMessageDeliveriesActive&&U.meshMessageDeliveries0&&s>t.topicScoreCap){s=t.topicScoreCap;const k=t.topicScoreCap/s;for(const U of o.values())U.p1w*=k,U.p2w*=k,U.p3w*=k,U.p3bw*=k,U.p4w*=k}let a=0,c=0,m=0;return a+=t.appSpecificScore(n)*t.appSpecificWeight,e.ips.forEach(k=>{if(t.IPColocationFactorWhitelist.has(k))return;const U=r.get(k),Q=U?U.size:0;if(Q>t.IPColocationFactorThreshold){const X=Q-t.IPColocationFactorThreshold;c+=X*X*t.IPColocationFactorWeight}}),m+=e.behaviourPenalty*e.behaviourPenalty*t.behaviourPenaltyWeight,s+=a+c+m,{byTopic:o,p5w:a,p6w:c,p7w:m,score:s}}function ib(n,e,t=(()=>!0)){const r=new Set;if(e<=0)return r;for(const i of n){if(r.size>=e)break;t(i)&&(r.add(i),n.delete(i))}return r}class XW{constructor(e,t){this.rawStream=e,this.pushable=lu(),this.closeController=new AbortController,Ln(Fs(this.pushable,this.closeController.signal,{returnOnAbort:!0}),to(),this.rawStream).catch(t)}get protocol(){return this.rawStream.stat.protocol}push(e){this.pushable.push(e)}close(){this.closeController.abort(),this.pushable.return(),this.rawStream.close()}}class JW{constructor(e){this.rawStream=e,this.closeController=new AbortController,this.source=Fs(Ln(this.rawStream,Ms()),this.closeController.signal,{returnOnAbort:!0})}close(){this.closeController.abort(),this.rawStream.close()}}var Vi=(()=>(function(n){n[n.started=0]="started",n[n.stopped=1]="stopped"}(Vi||(Vi={})),Vi))();class cP extends ki{constructor(e={}){super(),this.multicodecs=[Zw,iP],this.peers=new Set,this.streamsInbound=new Map,this.streamsOutbound=new Map,this.outboundInflightQueue=lu({objectMode:!0}),this.direct=new Set,this.floodsubPeers=new Set,this.acceptFromWhitelist=new Map,this.topics=new Map,this.subscriptions=new Set,this.mesh=new Map,this.fanout=new Map,this.fanoutLastpub=new Map,this.gossip=new Map,this.control=new Map,this.peerhave=new Map,this.iasked=new Map,this.backoff=new Map,this.outbound=new Map,this.topicValidators=new Map,this.heartbeatTicks=0,this.components=new ko,this.directPeerInitial=null,this.status={code:Vi.stopped},this.heartbeatTimer=null,this.runHeartbeat=()=>{const r=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(i=>{this.log("Error running heartbeat",i)}).finally(()=>{if(r?.(),this.status.code===Vi.started){clearTimeout(this.status.heartbeatTimeout);let i=(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;i<.25*this.opts.heartbeatInterval&&(i+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,i)}})};const t={fallbackToFloodsub:!0,floodPublish:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,...e,scoreParams:RW(e.scoreParams),scoreThresholds:LW(e.scoreThresholds)};if(this.globalSignaturePolicy=t.globalSignaturePolicy??sg,t.fallbackToFloodsub&&this.multicodecs.push(rP),this.log=Gt(t.debugName??"libp2p:gossipsub"),this.opts=t,this.direct=new Set(t.directPeers.map(r=>r.id.toString())),this.seenCache=new eb({validityMs:t.seenTTL}),this.publishedMessageIds=new eb({validityMs:t.seenTTL}),e.msgIdFn)this.msgIdFn=e.msgIdFn;else switch(this.globalSignaturePolicy){case sg:this.msgIdFn=WW;break;case Xw:this.msgIdFn=qW}if(e.fastMsgIdFn&&(this.fastMsgIdFn=e.fastMsgIdFn,this.fastMsgIdCache=new eb({validityMs:t.seenTTL})),this.msgIdToStrFn=e.msgIdToStrFn??CW,this.mcache=e.messageCache||new qz(t.mcacheGossip,t.mcacheLength,this.msgIdToStrFn),e.dataTransform&&(this.dataTransform=e.dataTransform),e.metricsRegister){if(!e.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");const r=Math.max(...Object.values(t.scoreParams.topics).map(s=>s.meshMessageDeliveriesWindow),1e3),i=function HW(n,e,t){return{protocolsEnabled:n.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:n.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:n.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:n.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEvents:n.gauge({name:"gossipsub_mesh_peer_inclusion_events_total",help:"Number of times we include peers in a topic mesh for different reasons",labelNames:["topic","reason"]}),meshPeerChurnEvents:n.gauge({name:"gossipsub_peer_churn_events_total",help:"Number of times we remove peers in a topic mesh for different reasons",labelNames:["topic","reason"]}),peersPerProtocol:n.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:n.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:n.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),asyncValidationResult:n.gauge({name:"gossipsub_async_validation_result_total",help:"Message validation result for each topic",labelNames:["topic","acceptance"]}),asyncValidationMcacheHit:n.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),rpcRecvBytes:n.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:n.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:n.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:n.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:n.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:n.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:n.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:n.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:n.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcRecvNotAccepted:n.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:n.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:n.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:n.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:n.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:n.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:n.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:n.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:n.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:n.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:n.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeers:n.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),msgPublishPeersByGroup:n.gauge({name:"gossipsub_msg_publish_peers_by_group",help:"Total count of peers (by group) that we publish a msg to",labelNames:["topic","peerGroup"]}),msgPublishBytes:n.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgForwardCount:n.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:n.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:n.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedStatus:n.gauge({name:"gossipsub_msg_received_status_total",help:"Tracks distribution of recv msgs by duplicate, invalid, valid",labelNames:["topic","status"]}),msgReceivedInvalid:n.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["topic","error"]}),duplicateMsgDeliveryDelay:n.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,1*t.maxMeshMessageDeliveriesWindowSec,2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:n.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),scoreFnCalls:n.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:n.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:n.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:n.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:n.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores",labelNames:["topic","p"]}),scoreWeights:n.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:n.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:n.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:n.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,1*t.behaviourPenaltyThreshold,2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:n.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:n.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:n.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:n.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:n.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:n.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:n.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedPeers:n.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:n.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantPromiseDeliveryTime:n.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,1*t.gossipPromiseExpireSec,2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),cacheSize:n.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:n.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),topicStrToLabel:e,toTopic(r){return this.topicStrToLabel.get(r)??r},onJoin(r){this.topicSubscriptionStatus.set({topicStr:r},1),this.meshPeerCounts.set({topicStr:r},0)},onLeave(r){this.topicSubscriptionStatus.set({topicStr:r},0),this.meshPeerCounts.set({topicStr:r},0)},onAddToMesh(r,i,s){const o=this.toTopic(r);this.meshPeerInclusionEvents.inc({topic:o,reason:i},s)},onRemoveFromMesh(r,i,s){const o=this.toTopic(r);this.meshPeerChurnEvents.inc({topic:o,reason:i},s)},onReportValidationMcacheHit(r){this.asyncValidationMcacheHit.inc({hit:r?"hit":"miss"})},onReportValidation(r,i){const s=this.toTopic(r);this.asyncValidationResult.inc({topic:s,acceptance:i})},onScorePenalty(r){this.scoringPenalties.inc({penalty:r},1)},onIhaveRcv(r,i,s){const o=this.toTopic(r);this.ihaveRcvMsgids.inc({topic:o},i),this.ihaveRcvNotSeenMsgids.inc({topic:o},s)},onIwantRcv(r,i){for(const[s,o]of r){const a=this.toTopic(s);this.iwantRcvMsgids.inc({topic:a},o)}this.iwantRcvDonthaveMsgids.inc(i)},onForwardMsg(r,i){const s=this.toTopic(r);this.msgForwardCount.inc({topic:s},1),this.msgForwardPeers.inc({topic:s},i)},onPublishMsg(r,i,s,o){const a=this.toTopic(r);this.msgPublishCount.inc({topic:a},1),this.msgPublishBytes.inc({topic:a},s*o),this.msgPublishPeers.inc({topic:a},s),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"direct"},i.direct),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"floodsub"},i.floodsub),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"mesh"},i.mesh),this.msgPublishPeersByGroup.inc({topic:a,peerGroup:"fanout"},i.fanout)},onMsgRecvPreValidation(r){const i=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:i},1)},onMsgRecvResult(r,i){const s=this.toTopic(r);this.msgReceivedStatus.inc({topic:s,status:i})},onMsgRecvInvalid(r,i){const s=this.toTopic(r);this.msgReceivedInvalid.inc({topic:s,error:i.reason===vs.Error?i.error:i.reason},1)},onDuplicateMsgDelivery(r,i,s){if(this.duplicateMsgDeliveryDelay.observe(i/1e3),s){const o=this.toTopic(r);this.duplicateMsgLateDelivery.inc({topic:o},1)}},onRpcRecv(r,i){this.rpcRecvBytes.inc(i),this.rpcRecvCount.inc(1),r.subscriptions&&this.rpcRecvSubscription.inc(r.subscriptions.length),r.messages&&this.rpcRecvMessage.inc(r.messages.length),r.control&&(this.rpcRecvControl.inc(1),r.control.ihave&&this.rpcRecvIHave.inc(r.control.ihave.length),r.control.iwant&&this.rpcRecvIWant.inc(r.control.iwant.length),r.control.graft&&this.rpcRecvGraft.inc(r.control.graft.length),r.control.prune&&this.rpcRecvPrune.inc(r.control.prune.length))},onRpcSent(r,i){if(this.rpcSentBytes.inc(i),this.rpcSentCount.inc(1),r.subscriptions&&this.rpcSentSubscription.inc(r.subscriptions.length),r.messages&&this.rpcSentMessage.inc(r.messages.length),r.control){const s=r.control.ihave?.length??0,o=r.control.iwant?.length??0,a=r.control.graft?.length??0,c=r.control.prune?.length??0;s>0&&this.rpcSentIHave.inc(s),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),(s>0||o>0||a>0||c>0)&&this.rpcSentControl.inc(1)}},registerScores(r,i){let s=0,o=0,a=0,c=0;for(const m of r)m>=i.graylistThreshold&&s++,m>=i.publishThreshold&&o++,m>=i.gossipThreshold&&a++,m>=0&&c++;this.peersByScoreThreshold.set({threshold:mc.graylist},s),this.peersByScoreThreshold.set({threshold:mc.publish},o),this.peersByScoreThreshold.set({threshold:mc.gossip},a),this.peersByScoreThreshold.set({threshold:mc.mesh},c),this.score.set(r)},registerScoreWeights(r){for(const[i,s]of r.byTopic)this.scoreWeights.set({topic:i,p:"p1"},s.p1w),this.scoreWeights.set({topic:i,p:"p2"},s.p2w),this.scoreWeights.set({topic:i,p:"p3"},s.p3w),this.scoreWeights.set({topic:i,p:"p3b"},s.p3bw),this.scoreWeights.set({topic:i,p:"p4"},s.p4w);this.scoreWeights.set({p:"p5"},r.p5w),this.scoreWeights.set({p:"p6"},r.p6w),this.scoreWeights.set({p:"p7"},r.p7w)},registerScorePerMesh(r,i){const s=new Map;r.forEach((o,a)=>{const c=this.topicStrToLabel.get(a)??"unknown";let m=s.get(c);m||(m=new Set,s.set(c,m)),o.forEach(T=>m?.add(T))});for(const[o,a]of s){const c=[];a.forEach(m=>{c.push(i.get(m)??0)}),this.scorePerMesh.set({topic:o},c)}}}}(e.metricsRegister,e.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:t.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:r/1e3});i.mcacheSize.addCollect(()=>this.onScrapeMetrics(i));for(const s of this.multicodecs)i.protocolsEnabled.set({protocol:s},1);this.metrics=i}else this.metrics=null;this.gossipTracer=new VW(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new UW(this.opts.scoreParams,this.metrics,{scoreCacheValidityMs:t.heartbeatInterval}),this.maxInboundStreams=e.maxInboundStreams,this.maxOutboundStreams=e.maxOutboundStreams}getPeers(){return[...this.peers.keys()].map(e=>_r(e))}isStarted(){return this.status.code===Vi.started}init(e){var t=this;return V(function*(){t.components=e,t.score.init(e)})()}start(){var e=this;return V(function*(){if(e.isStarted())return;e.log("starting"),e.publishConfig=yield function TW(n,e){return Jw.apply(this,arguments)}(e.globalSignaturePolicy,e.components.getPeerId()),e.outboundInflightQueue=lu({objectMode:!0}),Ln(e.outboundInflightQueue,function(){var o=V(function*(a){var T,c=!1,m=!1;try{for(var k,R=Tt(a);c=!(k=yield R.next()).done;c=!1){const{peerId:U,connection:Q}=k.value;yield e.createOutboundStream(U,Q)}}catch(U){m=!0,T=U}finally{try{c&&null!=R.return&&(yield R.return())}finally{if(m)throw T}}});return function(a){return o.apply(this,arguments)}}()).catch(o=>e.log.error("outbound inflight queue error",o)),yield Promise.all(e.opts.directPeers.map(function(){var o=V(function*(a){yield e.components.getPeerStore().addressBook.add(a.id,a.addrs)});return function(a){return o.apply(this,arguments)}}()));const t=e.components.getRegistrar();yield Promise.all(e.multicodecs.map(o=>t.handle(o,e.onIncomingStream.bind(e),{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams})));const r=function Wz(n){return new zz(n)}({onConnect:e.onPeerConnected.bind(e),onDisconnect:e.onPeerDisconnected.bind(e)}),i=yield Promise.all(e.multicodecs.map(o=>t.register(o,r))),s=setTimeout(e.runHeartbeat,100);e.status={code:Vi.started,registrarTopologyIds:i,heartbeatTimeout:s,hearbeatStartMs:Date.now()+100},e.score.start(),e.directPeerInitial=setTimeout(()=>{Promise.resolve().then(V(function*(){yield Promise.all(Array.from(e.direct).map(function(){var o=V(function*(a){return yield e.connect(a)});return function(a){return o.apply(this,arguments)}}()))})).catch(o=>{e.log(o)})},1e3),e.log("started")})()}stop(){var e=this;return V(function*(){if(e.log("stopping"),e.status.code!==Vi.started)return;const{registrarTopologyIds:t}=e.status;e.status={code:Vi.stopped};const r=e.components.getRegistrar();t.forEach(i=>r.unregister(i)),e.outboundInflightQueue.end();for(const i of e.streamsOutbound.values())i.close();e.streamsOutbound.clear();for(const i of e.streamsInbound.values())i.close();e.streamsInbound.clear(),e.peers.clear(),e.subscriptions.clear(),e.heartbeatTimer&&(e.heartbeatTimer.cancel(),e.heartbeatTimer=null),e.score.stop(),e.mesh.clear(),e.fanout.clear(),e.fanoutLastpub.clear(),e.gossip.clear(),e.control.clear(),e.peerhave.clear(),e.iasked.clear(),e.backoff.clear(),e.outbound.clear(),e.gossipTracer.clear(),e.seenCache.clear(),e.fastMsgIdCache&&e.fastMsgIdCache.clear(),e.directPeerInitial&&clearTimeout(e.directPeerInitial),e.log("stopped")})()}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;const r=t.remotePeer;this.addPeer(r,t.stat.direction),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){!this.isStarted()||(this.addPeer(e,t.stat.direction),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}createOutboundStream(e,t){var r=this;return V(function*(){if(!r.isStarted())return;const i=e.toString();if(r.peers.has(i)&&!r.streamsOutbound.has(i))try{const s=new XW(yield t.newStream(r.multicodecs),a=>r.log.error("outbound pipe error",a));r.log("create outbound stream %p",e),r.streamsOutbound.set(i,s);const o=s.protocol;o===rP&&r.floodsubPeers.add(i),r.metrics?.peersPerProtocol.inc({protocol:o},1),r.subscriptions.size>0&&(r.log("send subscriptions to",i),r.sendSubscriptions(i,Array.from(r.subscriptions),!0))}catch(s){r.log.error("createOutboundStream error",s)}})()}createInboundStream(e,t){var r=this;return V(function*(){if(!r.isStarted())return;const i=e.toString();if(!r.peers.has(i))return;const s=r.streamsInbound.get(i);void 0!==s&&(r.log("replacing existing inbound steam %s",i),s.close()),r.log("create inbound stream %s",i);const o=new JW(t);r.streamsInbound.set(i,o),r.pipePeerReadStream(e,o.source).catch(a=>r.log(a))})()}addPeer(e,t){const r=e.toString();this.peers.has(r)||(this.log("new peer %p",e),this.peers.add(r),this.score.addPeer(r),this.outbound.has(r)||this.outbound.set(r,"outbound"===t))}removePeer(e){const t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);const r=this.streamsOutbound.get(t),i=this.streamsInbound.get(t);r&&this.metrics?.peersPerProtocol.inc({protocol:r.protocol},-1),r?.close(),i?.close(),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(const s of this.topics.values())s.delete(t);for(const[s,o]of this.mesh)!0===o.delete(t)&&this.metrics?.onRemoveFromMesh(s,yc.Dc,1);for(const s of this.fanout.values())s.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===Vi.started}getMeshPeers(e){const t=this.mesh.get(e);return t?Array.from(t):[]}getSubscribers(e){const t=this.topics.get(e);return(t?Array.from(t):[]).map(r=>_r(r))}getTopics(){return Array.from(this.subscriptions)}pipePeerReadStream(e,t){var r=this;return V(function*(){try{yield Ln(t,function(){var i=V(function*(s){var c,o=!1,a=!1;try{for(var T,m=Tt(s);o=!(T=yield m.next()).done;o=!1){const R=T.value;try{const k=R.subarray(),U=ig.decode(k);r.metrics?.onRpcRecv(U,k.length),r.opts.awaitRpcHandler?yield r.handleReceivedRpc(e,U):r.handleReceivedRpc(e,U).catch(Q=>r.log(Q))}catch(k){r.log(k)}}}catch(R){a=!0,c=R}finally{try{o&&null!=m.return&&(yield m.return())}finally{if(a)throw c}}});return function(s){return i.apply(this,arguments)}}())}catch(i){r.log.error(i),r.onPeerDisconnected(e)}})()}handleReceivedRpc(e,t){var r=this;return V(function*(){if(!r.acceptFrom(e.toString()))return r.log("received message from unacceptable peer %p",e),void r.metrics?.rpcRecvNotAccepted.inc();if(r.log("rpc from %p",e),t.subscriptions&&t.subscriptions.length>0&&(t.subscriptions.forEach(i=>{r.handleReceivedSubscription(e,i)}),r.dispatchEvent(new rn("subscription-change",{detail:{peerId:e,subscriptions:t.subscriptions.filter(i=>null!==i.topic).map(i=>({topic:i.topic??"",subscribe:Boolean(i.subscribe)}))}}))),t.messages)for(const i of t.messages){const s=r.handleReceivedMessage(e,i).catch(o=>r.log(o));r.opts.awaitRpcMessageHandler&&(yield s)}t.control&&(yield r.handleControlMessage(e.toString(),t.control))})()}handleReceivedSubscription(e,t){if(null==t.topic)return;this.log("subscription update from %p topic %s",e,t.topic);let r=this.topics.get(t.topic);null==r&&(r=new Set,this.topics.set(t.topic,r)),t.subscribe?r.add(e.toString()):r.delete(e.toString())}handleReceivedMessage(e,t){var r=()=>super.dispatchEvent,i=this;return V(function*(){i.metrics?.onMsgRecvPreValidation(t.topic);const s=yield i.validateReceivedMessage(e,t);switch(i.metrics?.onMsgRecvResult(t.topic,s.code),s.code){case Es.duplicate:return i.score.duplicateMessage(e.toString(),s.msgIdStr,t.topic),void i.mcache.observeDuplicate(s.msgIdStr,e.toString());case Es.invalid:if(s.msgIdStr){const o=s.msgIdStr;i.score.rejectMessage(e.toString(),o,t.topic,s.reason),i.gossipTracer.rejectMessage(o,s.reason)}else i.score.rejectInvalidMessage(e.toString(),t.topic);return void i.metrics?.onMsgRecvInvalid(t.topic,s);case Es.valid:i.score.validateMessage(s.messageId.msgIdStr),i.gossipTracer.deliverMessage(s.messageId.msgIdStr),i.mcache.put(s.messageId,t,!i.opts.asyncValidation),i.subscriptions.has(t.topic)&&(!i.components.getPeerId().equals(e)||i.opts.emitSelf)&&(r().call(i,new rn("gossipsub:message",{detail:{propagationSource:e,msgId:s.messageId.msgIdStr,msg:s.msg}})),r().call(i,new rn("message",{detail:s.msg}))),i.opts.asyncValidation||i.forwardMessage(s.messageId.msgIdStr,t,e.toString())}})()}validateReceivedMessage(e,t){var r=this;return V(function*(){const i=r.fastMsgIdFn?.(t),s=i?r.fastMsgIdCache?.get(i):void 0;if(s)return{code:Es.duplicate,msgIdStr:s};const o=yield function jW(n,e){return nb.apply(this,arguments)}(r.globalSignaturePolicy,t);if(!o.valid)return{code:Es.invalid,reason:vs.Error,error:o.error};let a;try{const U=t.data??new Uint8Array(0);a=r.dataTransform?r.dataTransform.inboundTransform(t.topic,U):U}catch(U){return r.log("Invalid message, transform failed",U),{code:Es.invalid,reason:vs.Error,error:Ai.TransformFailed}}const c={from:null==t.from?void 0:pa(t.from),data:a,sequenceNumber:null==t.seqno?void 0:BigInt(`0x${Mt(t.seqno,"base16")}`),topic:t.topic},m=yield r.msgIdFn(c),T=r.msgIdToStrFn(m),R={msgId:m,msgIdStr:T};if(i&&r.fastMsgIdCache?.put(i,T),r.seenCache.has(T))return{code:Es.duplicate,msgIdStr:T};r.seenCache.put(T);const k=r.topicValidators.get(t.topic);if(null!=k){let U;try{U=yield k(c.topic,c,e)}catch(Q){const X=Q.code;"ERR_TOPIC_VALIDATOR_IGNORE"===X&&(U=fo.Ignore),U="ERR_TOPIC_VALIDATOR_REJECT"===X?fo.Reject:fo.Ignore}if(U!==fo.Accept)return{code:Es.invalid,reason:oP(U),msgIdStr:T}}return{code:Es.valid,messageId:R,msg:c}})()}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,r){this.sendRpc(e,{subscriptions:t.map(i=>({topic:i,subscribe:r})),messages:[]})}handleControlMessage(e,t){var r=this;return V(function*(){if(void 0===t)return;const i=t.ihave?r.handleIHave(e,t.ihave):[],s=t.iwant?r.handleIWant(e,t.iwant):[],o=t.graft?yield r.handleGraft(e,t.graft):[];t.prune&&(yield r.handlePrune(e,t.prune)),(i.length||s.length||o.length)&&r.sendRpc(e,Wo(s,{iwant:i,prune:o}))})()}acceptFrom(e){if(this.direct.has(e))return!0;const t=Date.now(),r=this.acceptFromWhitelist.get(e);if(r&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;const i=this.score.score(e);return i>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),i>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(!t.length)return[];const r=this.score.score(e);if(r10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:Xu.MaxIhave}),[];const s=this.iasked.get(e)??0;if(s>=Qu)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:Xu.MaxIasked}),[];const o=new Map;if(t.forEach(({topicID:m,messageIDs:T})=>{if(!m||!T||!this.mesh.has(m))return;let R=0;T.forEach(k=>{const U=this.msgIdToStrFn(k);this.seenCache.has(U)||(o.set(U,k),R++)}),this.metrics?.onIhaveRcv(m,T.length,R)}),!o.size)return[];let a=o.size;a+s>Qu&&(a=Qu-s),this.log("IHAVE: Asking for %d out of %d messages from %s",a,o.size,e);let c=Array.from(o.values());return qo(c),c=c.slice(0,a),this.iasked.set(e,s+a),this.gossipTracer.addPromise(e,c),[{messageIDs:c}]}handleIWant(e,t){if(!t.length)return[];const r=this.score.score(e);if(r{a&&a.forEach(c=>{const m=this.msgIdToStrFn(c),T=this.mcache.getWithIWantCount(m,e);null!=T?(s.set(T.msg.topic,1+(s.get(T.msg.topic)??0)),T.count>3?this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c):i.set(m,T.msg)):o++})}),this.metrics?.onIwantRcv(s,o),i.size?(this.log("IWANT: Sending %d messages to %s",i.size,e),Array.from(i.values())):(this.log("IWANT: Could not provide any wanted messages to %s",e),[])}handleGraft(e,t){var r=this;return V(function*(){const i=[],s=r.score.score(e),o=Date.now();let a=r.opts.doPX;return t.forEach(({topicID:c})=>{if(!c)return;const m=r.mesh.get(c);if(!m)return void(a=!1);if(m.has(e))return;if(r.direct.has(e))return r.log("GRAFT: ignoring request from direct peer %s",e),i.push(c),void(a=!1);const T=r.backoff.get(c)?.get(e);return"number"==typeof T&&o=r.opts.Dhi&&!r.outbound.get(e)?(i.push(c),void r.addBackoff(e,c)):(r.log("GRAFT: Add mesh link from %s in %s",e,c),r.score.graft(e,c),m.add(e),void r.metrics?.onAddToMesh(c,Qo.Subscribed,1))}),i.length?yield Promise.all(i.map(c=>r.makePrune(e,c,a))):[]})()}handlePrune(e,t){var r=this;return V(function*(){const i=r.score.score(e);for(const{topicID:s,backoff:o,peers:a}of t){if(null==s)continue;const c=r.mesh.get(s);if(!c)return;if(r.log("PRUNE: Remove mesh link to %s in %s",e,s),r.score.prune(e,s),c.has(e)&&(c.delete(e),r.metrics?.onRemoveFromMesh(s,yc.Unsub,1)),"number"==typeof o&&o>0?r.doAddBackoff(e,s,1e3*o):r.addBackoff(e,s),a&&a.length){if(i{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,Zu.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!=0)return;const e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((i,s)=>{i{e.streamsOutbound.has(r)||t.push(r)}),yield Promise.all(t.map(function(){var r=V(function*(i){return yield e.connect(i)});return function(i){return r.apply(this,arguments)}}()))})()}pxConnect(e){var t=this;return V(function*(){e.length>t.opts.prunePeers&&(qo(e),e=e.slice(0,t.opts.prunePeers));const r=[];yield Promise.all(e.map(function(){var i=V(function*(s){if(!s.peerID)return;const o=pa(s.peerID).toString();if(!t.peers.has(o)){if(!s.signedPeerRecord)return void r.push(o);try{const a=yield Ma.openAndCertify(s.signedPeerRecord,"libp2p-peer-record"),c=a.peerId;if(!a.peerId.equals(o))return void t.log("bogus peer record obtained through px: peer ID %p doesn't match expected peer %p",c,o);if(!(yield t.components.getPeerStore().addressBook.consumePeerRecord(a)))return void t.log("bogus peer record obtained through px: could not add peer record to address book");r.push(o)}catch{t.log("bogus peer record obtained through px: invalid signature or not a peer record")}}});return function(s){return i.apply(this,arguments)}}())),r.length&&(yield Promise.all(r.map(function(){var i=V(function*(s){return yield t.connect(s)});return function(s){return i.apply(this,arguments)}}())))})()}connect(e){var t=this;return V(function*(){t.log("Initiating connection with %s",e);const r=_r(e),i=yield t.components.getConnectionManager().openConnection(r);for(const s of t.multicodecs)for(const o of t.components.getRegistrar().getTopologies(s))o.onConnect(r,i)})()}subscribe(e){if(this.status.code!==Vi.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==Vi.started)throw new Error("Pubsub is not started");const t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(const r of this.peers.keys())this.sendSubscriptions(r,[e],!1);this.leave(e).catch(r=>{this.log(r)})}join(e){if(this.status.code!==Vi.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);const t=new Set,r=this.fanout.get(e);if(r&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),r.forEach(i=>{!this.direct.has(i)&&this.score.score(i)>=0&&t.add(i)}),this.metrics?.onAddToMesh(e,Qo.Fanout,t.size)),t.size!t.has(o)&&!this.direct.has(o)&&this.score.score(o)>=0).forEach(o=>{t.add(o)}),this.metrics?.onAddToMesh(e,Qo.Random,t.size-i)}this.mesh.set(e,t),t.forEach(i=>{this.log("JOIN: Add mesh link to %s in %s",i,e),this.sendGraft(i,e)})}leave(e){var t=this;return V(function*(){if(t.status.code!==Vi.started)throw new Error("Gossipsub has not started");t.log("LEAVE %s",e),t.metrics?.onLeave(e);const r=t.mesh.get(e);r&&(yield Promise.all(Array.from(r).map(function(){var i=V(function*(s){return t.log("LEAVE: Remove mesh link to %s in %s",s,e),yield t.sendPrune(s,e)});return function(s){return i.apply(this,arguments)}}())),t.mesh.delete(e))})()}selectPeersToForward(e,t,r){const i=new Set,s=this.topics.get(e);s&&(this.direct.forEach(a=>{s.has(a)&&t!==a&&!r?.has(a)&&i.add(a)}),this.floodsubPeers.forEach(a=>{s.has(a)&&t!==a&&!r?.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&i.add(a)}));const o=this.mesh.get(e);return o&&o.size>0&&o.forEach(a=>{t!==a&&!r?.has(a)&&i.add(a)}),i}selectPeersToPublish(e){const t=new Set,r={direct:0,floodsub:0,mesh:0,fanout:0},i=this.topics.get(e);if(i)if(this.opts.floodPublish)i.forEach(s=>{this.direct.has(s)?(t.add(s),r.direct++):this.score.score(s)>=this.opts.scoreThresholds.publishThreshold&&(t.add(s),r.floodsub++)});else{this.direct.forEach(o=>{i.has(o)&&(t.add(o),r.direct++)}),this.floodsubPeers.forEach(o=>{i.has(o)&&this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),r.floodsub++)});const s=this.mesh.get(e);if(s&&s.size>0)s.forEach(o=>{t.add(o),r.mesh++});else{const o=this.fanout.get(e);if(o&&o.size>0)o.forEach(a=>{t.add(a),r.fanout++});else{const a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,i){r&&this.score.deliverMessage(r,e,t.topic);const s=this.selectPeersToForward(t.topic,r,i),o=Wo([t]);s.forEach(a=>{this.sendRpc(a,o)}),this.metrics?.onForwardMsg(t.topic,s.size)}publish(e,t){var r=()=>super.dispatchEvent,i=this;return V(function*(){const s=i.dataTransform?i.dataTransform.outboundTransform(e,t):t;if(null==i.publishConfig)throw Error("PublishError.Uninitialized");const o=yield function KW(n,e,t){return tb.apply(this,arguments)}(i.publishConfig,e,s),a={from:o.from?pa(o.from):void 0,data:t,sequenceNumber:null==o.seqno?void 0:BigInt(`0x${Mt(o.seqno,"base16")}`),topic:e,signature:o.signature??void 0,key:o.key??void 0},c=yield i.msgIdFn(a),m=i.msgIdToStrFn(c);if(i.seenCache.has(m))throw Error("PublishError.Duplicate");const{tosend:T,tosendCount:R}=i.selectPeersToPublish(o.topic),k=!0===i.opts.emitSelf&&i.subscriptions.has(e);if(0===T.size&&!i.opts.allowPublishToZeroPeers&&!k)throw Error("PublishError.InsufficientPeers");i.seenCache.put(m),i.mcache.put({msgId:c,msgIdStr:m},o,!0),i.publishedMessageIds.put(m);const U=Wo([o]);for(const Q of T)i.sendRpc(Q,U)||T.delete(Q);return i.metrics?.onPublishMsg(e,R,T.size,null!=o.data?o.data.length:0),k&&(T.add(i.components.getPeerId().toString()),r().call(i,new rn("gossipsub:message",{detail:{propagationSource:i.components.getPeerId(),msgId:m,msg:a}})),r().call(i,new rn("message",{detail:a}))),{recipients:Array.from(T.values()).map(Q=>_r(Q))}})()}reportMessageValidationResult(e,t,r){if(r===fo.Accept){const i=this.mcache.validate(e);if(this.metrics?.onReportValidationMcacheHit(null!==i),null!=i){const{message:s,originatingPeers:o}=i;this.score.deliverMessage(t.toString(),e,s.topic),this.forwardMessage(e,i.message,t.toString(),o),this.metrics?.onReportValidation(s.topic,r)}}else{const i=this.mcache.remove(e);if(this.metrics?.onReportValidationMcacheHit(null!==i),i){const s=oP(r),{message:o,originatingPeers:a}=i;this.score.rejectMessage(t.toString(),e,o.topic,s);for(const c of a)this.score.rejectMessage(c,e,o.topic,s);this.metrics?.onReportValidation(o.topic,r)}}}sendGraft(e,t){const i=Wo([],{graft:[{topicID:t}]});this.sendRpc(e,i)}sendPrune(e,t){var r=this;return V(function*(){const s=Wo([],{prune:[yield r.makePrune(e,t,r.opts.doPX)]});r.sendRpc(e,s)})()}sendRpc(e,t){const r=this.streamsOutbound.get(e);if(!r)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;const i=this.control.get(e);i&&(this.piggybackControl(e,t,i),this.control.delete(e));const s=this.gossip.get(e);s&&(this.piggybackGossip(e,t,s),this.gossip.delete(e));const o=ig.encode(t).finish();return r.push(o),this.metrics?.onRpcSent(t,o.length),!0}piggybackControl(e,t,r){const i=(r.graft||[]).filter(({topicID:o})=>(o&&this.mesh.get(o)||new Set).has(e)),s=(r.prune||[]).filter(({topicID:o})=>!(o&&this.mesh.get(o)||new Set).has(e));!i.length&&!s.length||(t.control?(t.control.graft=t.control.graft&&t.control.graft.concat(i),t.control.prune=t.control.prune&&t.control.prune.concat(s)):t.control={graft:i,prune:s,ihave:[],iwant:[]})}piggybackGossip(e,t,r){t.control||(t.control={ihave:[],iwant:[],graft:[],prune:[]}),t.control.ihave=r}sendGraftPrune(e,t,r){var i=this;return V(function*(){const s=i.opts.doPX;for(const[o,a]of e){const c=a.map(k=>({topicID:k}));let m=[];const T=t.get(o);T&&(m=yield Promise.all(T.map(function(){var k=V(function*(U){return yield i.makePrune(o,U,s&&!r.get(o))});return function(U){return k.apply(this,arguments)}}())),t.delete(o));const R=Wo([],{graft:c,prune:m});i.sendRpc(o,R)}for(const[o,a]of t){const c=yield Promise.all(a.map(function(){var T=V(function*(R){return yield i.makePrune(o,R,s&&!r.get(o))});return function(R){return T.apply(this,arguments)}}())),m=Wo([],{prune:c});i.sendRpc(o,m)}})()}emitGossip(e){const t=this.mcache.getGossipIDs(new Set(e.keys()));for(const[r,i]of e)this.doEmitGossip(r,i,t.get(r)??[])}doEmitGossip(e,t,r){if(!r.length||(qo(r),r.length>Qu&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),!t.size))return;let i=this.opts.Dlazy;const s=.25*t.size;let o=t;s>i&&(i=s),i>o.size?i=o.size:o=qo(Array.from(o)).slice(0,i),o.forEach(a=>{let c=r;r.length>Qu&&(c=qo(c.slice()).slice(0,Qu)),this.pushGossip(a,{topicID:e,messageIDs:c})})}flush(){for(const[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Wo([],{ihave:t}));for(const[e,t]of this.control.entries())this.control.delete(e),this.sendRpc(e,Wo([],{graft:t.graft,prune:t.prune}))}pushGossip(e,t){this.log("Add gossip to %s",e);const r=this.gossip.get(e)||[];this.gossip.set(e,r.concat(t))}makePrune(e,t,r){var i=this;return V(function*(){if(i.score.prune(e,t),i.streamsOutbound.get(e).protocol===iP)return{topicID:t,peers:[]};const s=i.opts.pruneBackoff/1e3;if(!r)return{topicID:t,peers:[],backoff:s};const o=i.getRandomGossipPeers(t,i.opts.prunePeers,c=>c!==e&&i.score.score(c)>=0),a=yield Promise.all(Array.from(o).map(function(){var c=V(function*(m){const T=_r(m);return{peerID:T.toBytes(),signedPeerRecord:yield i.components.getPeerStore().addressBook.getRawEnvelope(T)}});return function(m){return c.apply(this,arguments)}}()));return{topicID:t,peers:a,backoff:s}})()}heartbeat(){var e=this;return V(function*(){const{D:t,Dlo:r,Dhi:i,Dscore:s,Dout:o,fanoutTTL:a}=e.opts;e.heartbeatTicks++;const c=new Map,m=X=>{let ae=c.get(X);return void 0===ae&&(ae=e.score.score(X),c.set(X,ae)),ae},T=new Map,R=new Map,k=new Map;e.clearBackoff(),e.peerhave.clear(),e.metrics?.cacheSize.set({cache:"iasked"},e.iasked.size),e.iasked.clear(),e.applyIwantPenalties(),e.heartbeatTicks%e.opts.directConnectTicks==0&&(yield e.directConnect()),e.fastMsgIdCache?.prune(),e.seenCache.prune(),e.gossipTracer.prune(),e.publishedMessageIds.prune();const U=new Map;e.mesh.forEach((X,ae)=>{const he=e.topics.get(ae),Ae=new Set,ue=new Set;if(U.set(ae,ue),he){const Fe=qo(Array.from(he)),wt=e.backoff.get(ae);for(const mt of Fe){const Zt=e.streamsOutbound.get(mt);if(Zt&&e.multicodecs.includes(Zt.protocol)&&!X.has(mt)&&!e.direct.has(mt)){const wn=m(mt);(!wt||!wt.has(mt))&&wn>=0&&Ae.add(mt),wn>=e.opts.scoreThresholds.gossipThreshold&&ue.add(mt)}}}const Re=(Fe,wt)=>{e.log("HEARTBEAT: Remove mesh link to %s in %s",Fe,ae),e.addBackoff(Fe,ae),X.delete(Fe),m(Fe)>=e.opts.scoreThresholds.gossipThreshold&&ue.add(Fe),e.metrics?.onRemoveFromMesh(ae,wt,1);const mt=R.get(Fe);mt?mt.push(ae):R.set(Fe,[ae])},Le=(Fe,wt)=>{e.log("HEARTBEAT: Add mesh link to %s in %s",Fe,ae),e.score.graft(Fe,ae),X.add(Fe),ue.delete(Fe),e.metrics?.onAddToMesh(ae,wt,1);const mt=T.get(Fe);mt?mt.push(ae):T.set(Fe,[ae])};if(X.forEach(Fe=>{const wt=m(Fe);wt<0&&(e.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",Fe,wt,ae),Re(Fe,yc.BadScore),k.set(Fe,!0))}),X.size!0)}(Ae,t-X.size).forEach(mt=>{Le(mt,Qo.NotEnough)}),X.size>i){let Fe=Array.from(X);Fe.sort((mt,Zt)=>m(Zt)-m(mt)),Fe=Fe.slice(0,s).concat(qo(Fe.slice(s)));let wt=0;if(Fe.slice(0,t).forEach(mt=>{e.outbound.get(mt)&&wt++}),wt{const zr=Fe[wn];for(let Rn=wn;Rn>0;Rn--)Fe[Rn]=Fe[Rn-1];Fe[0]=zr};if(wt>0){let wn=wt;for(let zr=1;zr0;zr++)e.outbound.get(Fe[zr])&&(mt(zr),wn--)}let Zt=t-wt;for(let wn=t;wn0;wn++)e.outbound.get(Fe[wn])&&(mt(wn),Zt--)}Fe.slice(t).forEach(mt=>{Re(mt,yc.Excess)})}if(X.size>=r){let Fe=0;X.forEach(wt=>{e.outbound.get(wt)&&Fe++}),Fe!0===e.outbound.get(Zt)).forEach(Zt=>{Le(Zt,Qo.Outbound)})}if(e.heartbeatTicks%e.opts.opportunisticGraftTicks==0&&X.size>1){const Fe=Array.from(X).sort((Zt,wn)=>m(Zt)-m(wn)),wt=Math.floor(X.size/2),mt=m(Fe[wt]);if(mtm(zr)>mt);for(const zr of wn)e.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",zr,ae),Le(zr,Qo.Opportunistic)}}});const Q=Date.now();e.fanoutLastpub.forEach((X,ae)=>{X+a{const he=e.topics.get(ae);X.forEach(Le=>{(!he.has(Le)||m(Le)=e.opts.scoreThresholds.publishThreshold&&ue.push(Fe),mt>=e.opts.scoreThresholds.gossipThreshold&&Re.add(Fe)}}}X.size{X.add(Fe),Re?.delete(Fe)})}),e.emitGossip(U),yield e.sendGraftPrune(T,R,k),e.flush(),e.mcache.shift(),e.dispatchEvent(new rn("gossipsub:heartbeat"))})()}getRandomGossipPeers(e,t,r=(()=>!0)){const i=this.topics.get(e);if(!i)return new Set;let s=[];return i.forEach(o=>{const a=this.streamsOutbound.get(o);!a||this.multicodecs.includes(a.protocol)&&r(o)&&s.push(o)}),s=qo(s),t>0&&s.length>t&&(s=s.slice(0,t)),new Set(s)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0;for(const o of this.backoff.values())t+=o.size;e.cacheSize.set({cache:"backoff"},t);for(const[o,a]of this.topics)e.topicPeersCount.set({topicStr:o},a.size);for(const[o,a]of this.mesh)e.meshPeerCounts.set({topicStr:o},a.size);const r=[],i=new Map;e.behaviourPenalty.reset();for(const o of this.peers.keys()){const a=this.score.score(o);r.push(a),i.set(o,a),e.behaviourPenalty.observe(this.score.peerStats.get(o)?.behaviourPenalty??0)}e.registerScores(r,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);const s=function YW(n,e,t,r,i){const s={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(const o of n){const a=e.get(o);if(a){const c=QW(o,a,t,r,i);for(const[m,T]of c.byTopic){let R=s.byTopic.get(m);R||(R={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},s.byTopic.set(m,R)),R.p1w.push(T.p1w),R.p2w.push(T.p2w),R.p3w.push(T.p3w),R.p3bw.push(T.p3bw),R.p4w.push(T.p4w)}s.p5w.push(c.p5w),s.p6w.push(c.p6w),s.p7w.push(c.p7w),s.score.push(c.score)}else s.p5w.push(0),s.p6w.push(0),s.p7w.push(0),s.score.push(0)}return s}(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(s)}}cP.multicodec=Zw;const sb=Ur("waku:relay");class uP extends cP{constructor(e){super(e=Object.assign(e??{},{globalSignaturePolicy:og.StrictNoSign,fallbackToFloodsub:!1})),this.multicodecs=Hw,this.observers={},this.decryptionKeys=new Map,this.pubSubTopic=e?.pubSubTopic??kp,e?.decryptionKeys?.forEach(t=>{this.addDecryptionKey(t)})}start(){var e=()=>super.start,t=this;return V(function*(){yield e().call(t),t.subscribe(t.pubSubTopic)})()}send(e){var t=this;return V(function*(){const r=e.encode();yield t.publish(t.pubSubTopic,r)})()}addDecryptionKey(e,t){this.decryptionKeys.set(Gs(e),t??{})}deleteDecryptionKey(e){this.decryptionKeys.delete(Gs(e))}addObserver(e,t=[]){0===t.length?(this.observers[""]||(this.observers[""]=new Set),this.observers[""].add(e)):t.forEach(r=>{this.observers[r]||(this.observers[r]=new Set),this.observers[r].add(e)})}deleteObserver(e,t=[]){0===t.length?this.observers[""]&&this.observers[""].delete(e):t.forEach(r=>{this.observers[r]&&this.observers[r].delete(e)})}subscribe(e){this.addEventListener("gossipsub:message",t=>{if(t.detail.msg.topic===e){const r=Array.from(this.decryptionKeys).map(([i,{method:s,contentTopics:o}])=>({key:i,method:s,contentTopics:o}));sb(`Message received on ${e}`),uo.decode(t.detail.msg.data,r).then(i=>{i?(this.observers[""]&&this.observers[""].forEach(s=>{s(i)}),i.contentTopic&&this.observers[i.contentTopic]&&this.observers[i.contentTopic].forEach(s=>{s(i)})):sb("Failed to decode Waku Message")}).catch(i=>{sb("Failed to decode Waku Message",i)})}}),super.subscribe(e)}getMeshPeers(e){return super.getMeshPeers(e??this.pubSubTopic)}}function ob(){return ob=V(function*(n){const e=n?.libp2p??{},t=e.peerDiscovery??[];n?.defaultBootstrap&&(t.push(tq()),Object.assign(e,{peerDiscovery:t}));const r=yield nq(new uP(n),e),i=new qG(r,n),s=new jG(r,n),o=new KG(r,n);return new ZG(n??{},r,i,s,o)}),ob.apply(this,arguments)}function tq(){return new i$(function o$(n=Uu.Prod,e=1){if(e<=0)return[];let t;switch(n){case Uu.Prod:t=pw_fleets["wakuv2.prod"]["waku-websocket"];break;case Uu.Test:t=pw_fleets["wakuv2.test"]["waku-websocket"];break;default:t=pw_fleets["wakuv2.prod"]["waku-websocket"]}return t=Object.values(t),t=t.map(r=>new vn(r)),sR(t,e)}())}function nq(n,e){return ab.apply(this,arguments)}function ab(){return ab=V(function*(n,e){return t$(Object.assign({transports:[new pH({filter:OA})],streamMuxers:[new r9],connectionEncryption:[new GT]},{pubsub:n},e??{}))}),ab.apply(this,arguments)}uP.multicodec=Hw[0];function iq(n,e,t){"function"==typeof t&&(t={filter:t});const r=function rq(n,e,t){let r;const i=new Promise((s,o)=>{if(!((t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t}).count>=0)||t.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(t.count))throw new TypeError("The `count` option should be at least 0 or more");const a=[e].flat(),c=[],{addListener:m,removeListener:T}=(n=>{const e=n.on||n.addListener||n.addEventListener,t=n.off||n.removeListener||n.removeEventListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(n),removeListener:t.bind(n)}})(n),R=(...U)=>{const Q=t.multiArgs?U:U[0];t.filter&&!t.filter(Q)||(c.push(Q),t.count===c.length&&(r(),s(c)))},k=U=>{r(),o(U)};r=()=>{for(const U of a)T(U,R);for(const U of t.rejectionEvents)T(U,k)};for(const U of a)m(U,R);for(const U of t.rejectionEvents)m(U,k);t.resolveImmediately&&s(c)});if(i.cancel=r,"number"==typeof t.timeout){const s=Mx(i,t.timeout);return s.cancel=r,s}return i}(n,e,t={...t,count:1,resolveImmediately:!1}),i=r.then(s=>s[0]);return i.cancel=r.cancel,i}const fP=Ur("waku:wait-for-remote-peer");function cb(){return cb=V(function*(n,e,t){if(e=e??[es.Relay],!n.isStarted())return Promise.reject("Waku node is not started");const r=[];e.includes(es.Relay)&&r.push(oq(n.relay)),e.includes(es.Store)&&r.push(ub(n.store,Object.values(lc))),e.includes(es.LightPush)&&r.push(ub(n.lightPush,[zf])),e.includes(es.Filter)&&r.push(ub(n.filter,[jf])),t?yield cq(Promise.all(r),t,"Timed out waiting for a remote peer."):yield Promise.all(r)}),cb.apply(this,arguments)}function ub(n,e){return lb.apply(this,arguments)}function lb(){return lb=V(function*(n,e){const t=yield n.peers();t.length?fP(`${e} peer found: `,t[0].id.toString()):yield new Promise(r=>{const i=s=>{for(const o of e)if(s.detail.protocols.includes(o)){fP("Resolving for",o,s.detail.protocols),n.libp2p.peerStore.removeEventListener("change:protocols",i),r();break}};n.libp2p.peerStore.addEventListener("change:protocols",i)})}),lb.apply(this,arguments)}function oq(n){return fb.apply(this,arguments)}function fb(){return fb=V(function*(n){let e=n.getMeshPeers();for(;0==e.length;)yield iq(n,"gossipsub:heartbeat"),e=n.getMeshPeers()}),fb.apply(this,arguments)}const aq=(n,e)=>new Promise((t,r)=>setTimeout(()=>r(e),n));function cq(n,e,t){return db.apply(this,arguments)}function db(){return db=V(function*(n,e,t){yield Promise.race([n,aq(e,t)])}),db.apply(this,arguments)}let dP=(()=>{class n{constructor(){this.wakuSubject=new Sr,this.waku=this.wakuSubject.asObservable(),this.wakuStatusSubject=new _5(""),this.wakuStatus=this.wakuStatusSubject.asObservable()}init(){(function eq(n){return ob.apply(this,arguments)})({defaultBootstrap:!0}).then(t=>{t.start().then(()=>{this.wakuSubject.next(t),this.wakuStatusSubject.next("Connecting..."),function sq(n,e,t){return cb.apply(this,arguments)}(t).then(()=>{this.wakuStatusSubject.next("Connected")})})})}}return n.\u0275fac=function(t){return new(t||n)},n.\u0275prov=Jn({token:n,factory:n.\u0275fac,providedIn:"root"}),n})();function lq(n,e){if(1&n&&(bo(0,"li")(1,"span"),ru(2),_o()()),2&n){const t=e.$implicit;Cl(2),u0("",t.timestamp," ",t.text,"")}}Ur("waku:enr");const vb=new(Dm().Type)("ChatMessage").add(new(Dm().Field)("timestamp",1,"uint32")).add(new(Dm().Field)("text",2,"string"));let fq=(()=>{class n{constructor(t){this.wakuService=t,this.contentTopic="/relay-angular-chat/1/chat/proto",this.messages=[],this.messageCount=0,this.processIncomingMessages=r=>{if(!r.payload)return;const{text:i,timestamp:s}=vb.decode(r.payload),o=new Date;o.setTime(Number(s)),this.messages.push({text:i,timestamp:o})}}ngOnInit(){this.wakuService.wakuStatus.subscribe(t=>{this.wakuStatus=t}),this.wakuService.waku.subscribe(t=>{this.waku=t,this.waku.relay.addObserver(this.processIncomingMessages,[this.contentTopic])}),window.onbeforeunload=()=>this.ngOnDestroy()}ngOnDestroy(){this.waku.relay.deleteObserver(this.processIncomingMessages,[this.contentTopic])}sendMessage(){const t=(new Date).getTime(),r=vb.create({timestamp:t,text:`Here is a message #${this.messageCount}`}),i=vb.encode(r).finish();uo.fromBytes(i,this.contentTopic).then(s=>{this.waku.relay.send(s).then(()=>{console.log(`Message #${this.messageCount} sent`),this.messageCount+=1})})}}return n.\u0275fac=function(t){return new(t||n)(qt(dP))},n.\u0275cmp=td({type:n,selectors:[["app-messages"]],decls:6,vars:2,consts:[[3,"disabled","click"],[1,"messages"],[4,"ngFor","ngForOf"]],template:function(t,r){1&t&&(bo(0,"button",0),s0("click",function(){return r.sendMessage()}),ru(1,"Send Message"),_o(),bo(2,"h2"),ru(3,"Messages"),_o(),bo(4,"ul",1),function AD(n,e,t,r,i,s,o,a){const c=Ve(),m=pn(),T=n+22,R=m.firstCreatePass?function aL(n,e,t,r,i,s,o,a,c){const m=e.consts,T=Gc(e,n,4,o||null,ea(m,a));jy(e,t,T,ea(m,c)),fd(e,T);const R=T.tViews=Ky(2,T,r,i,s,e.directiveRegistry,e.pipeRegistry,null,e.schemas,m);return null!==e.queries&&(e.queries.template(e,T),R.queries=e.queries.embeddedTView(T)),T}(T,m,c,e,t,r,i,s,o):m.data[T];Ws(R,!1);const k=c[11].createComment("");Ld(m,c,k,R),si(k,c),jd(c,c[T]=uD(k,c,k,R)),od(R)&&Vy(m,c,R),null!=o&&Hy(c,R,a)}(5,lq,3,2,"li",2),_o()),2&t&&(qd("disabled","Connected"!==r.wakuStatus),Cl(5),qd("ngForOf",r.messages))},dependencies:[DC]}),n})(),dq=(()=>{class n{constructor(t){this.wakuService=t,this.title="relay-angular-chat"}ngOnInit(){this.wakuService.init(),this.wakuService.wakuStatus.subscribe(t=>{this.wakuStatus=t})}}return n.\u0275fac=function(t){return new(t||n)(qt(dP))},n.\u0275cmp=td({type:n,selectors:[["app-root"]],decls:5,vars:2,template:function(t,r){1&t&&(bo(0,"h1"),ru(1),_o(),bo(2,"p"),ru(3),_o(),e0(4,"app-messages")),2&t&&(Cl(1),c0(r.title),Cl(2),Yd("Waku node's status: ",r.wakuStatus,""))},dependencies:[fq],styles:["h1[_ngcontent-%COMP%]{color:#369;font-family:Arial,Helvetica,sans-serif;font-size:250%}h2[_ngcontent-%COMP%], h3[_ngcontent-%COMP%]{color:#444;font-family:Arial,Helvetica,sans-serif;font-weight:lighter}body[_ngcontent-%COMP%]{margin:2em}body[_ngcontent-%COMP%], input[type=text][_ngcontent-%COMP%], button[_ngcontent-%COMP%]{color:#333;font-family:Cambria,Georgia,serif}*[_ngcontent-%COMP%]{font-family:Arial,Helvetica,sans-serif}"]}),n})(),hq=(()=>{class n{}return n.\u0275fac=function(t){return new(t||n)},n.\u0275mod=nl({type:n,bootstrap:[dq]}),n.\u0275inj=vc({imports:[d5]}),n})();N(8583),function Bk(){tC=!1}(),f5().bootstrapModule(hq).catch(n=>console.error(n))},1280:J=>{"use strict";J.exports=function G(N,h){for(var u=new Array(arguments.length-1),g=0,b=2,w=!0;b{"use strict";var N=G;N.length=function(v){var l=v.length;if(!l)return 0;for(var p=0;--l%4>1&&"="===v.charAt(l);)++p;return Math.ceil(3*v.length)/4-p};for(var h=new Array(64),u=new Array(123),g=0;g<64;)u[h[g]=g<26?g+65:g<52?g+71:g<62?g-4:g-59|43]=g++;N.encode=function(v,l,p){for(var y,d=null,_=[],I=0,E=0;l>2],y=(3&f)<<4,E=1;break;case 1:_[I++]=h[y|f>>4],y=(15&f)<<2,E=2;break;case 2:_[I++]=h[y|f>>6],_[I++]=h[63&f],E=0}I>8191&&((d||(d=[])).push(String.fromCharCode.apply(String,_)),I=0)}return E&&(_[I++]=h[y],_[I++]=61,1===E&&(_[I++]=61)),d?(I&&d.push(String.fromCharCode.apply(String,_.slice(0,I))),d.join("")):String.fromCharCode.apply(String,_.slice(0,I))};var b="invalid encoding";N.decode=function(v,l,p){for(var I,d=p,_=0,E=0;E1)break;if(void 0===(y=u[y]))throw Error(b);switch(_){case 0:I=y,_=1;break;case 1:l[p++]=I<<2|(48&y)>>4,I=y,_=2;break;case 2:l[p++]=(15&I)<<4|(60&y)>>2,I=y,_=3;break;case 3:l[p++]=(3&I)<<6|y,_=0}}if(1===_)throw Error(b);return p-d},N.test=function(v){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(v)}},9749:J=>{"use strict";function G(N,h){"string"==typeof N&&(h=N,N=void 0);var u=[];function g(w){if("string"!=typeof w){var v=b();if(G.verbose&&console.log("codegen: "+v),v="return "+v,w){for(var l=Object.keys(w),p=new Array(l.length+1),d=new Array(l.length),_=0;_{"use strict";function G(){this._listeners={}}J.exports=G,G.prototype.on=function(h,u,g){return(this._listeners[h]||(this._listeners[h]=[])).push({fn:u,ctx:g||this}),this},G.prototype.off=function(h,u){if(void 0===h)this._listeners={};else if(void 0===u)this._listeners[h]=[];else for(var g=this._listeners[h],b=0;b{"use strict";J.exports=b;var h=N(1280),g=N(716)("fs");function b(w,v,l){return"function"==typeof v?(l=v,v={}):v||(v={}),l?!v.xhr&&g&&g.readFile?g.readFile(w,function(d,_){return d&&typeof XMLHttpRequest<"u"?b.xhr(w,v,l):d?l(d):l(null,v.binary?_:_.toString("utf8"))}):b.xhr(w,v,l):h(b,this,w,v)}b.xhr=function(v,l,p){var d=new XMLHttpRequest;d.onreadystatechange=function(){if(4===d.readyState){if(0!==d.status&&200!==d.status)return p(Error("status "+d.status));if(l.binary){var I=d.response;if(!I){I=[];for(var E=0;E{"use strict";function G(b){return typeof Float32Array<"u"?function(){var w=new Float32Array([-0]),v=new Uint8Array(w.buffer),l=128===v[3];function p(E,y,f){w[0]=E,y[f]=v[0],y[f+1]=v[1],y[f+2]=v[2],y[f+3]=v[3]}function d(E,y,f){w[0]=E,y[f]=v[3],y[f+1]=v[2],y[f+2]=v[1],y[f+3]=v[0]}function _(E,y){return v[0]=E[y],v[1]=E[y+1],v[2]=E[y+2],v[3]=E[y+3],w[0]}function I(E,y){return v[3]=E[y],v[2]=E[y+1],v[1]=E[y+2],v[0]=E[y+3],w[0]}b.writeFloatLE=l?p:d,b.writeFloatBE=l?d:p,b.readFloatLE=l?_:I,b.readFloatBE=l?I:_}():function(){function w(l,p,d,_){var I=p<0?1:0;if(I&&(p=-p),0===p)l(1/p>0?0:2147483648,d,_);else if(isNaN(p))l(2143289344,d,_);else if(p>34028234663852886e22)l((I<<31|2139095040)>>>0,d,_);else if(p<11754943508222875e-54)l((I<<31|Math.round(p/1401298464324817e-60))>>>0,d,_);else{var E=Math.floor(Math.log(p)/Math.LN2);l((I<<31|E+127<<23|8388607&Math.round(p*Math.pow(2,-E)*8388608))>>>0,d,_)}}function v(l,p,d){var _=l(p,d),I=2*(_>>31)+1,E=_>>>23&255,y=8388607&_;return 255===E?y?NaN:I*(1/0):0===E?1401298464324817e-60*I*y:I*Math.pow(2,E-150)*(y+8388608)}b.writeFloatLE=w.bind(null,N),b.writeFloatBE=w.bind(null,h),b.readFloatLE=v.bind(null,u),b.readFloatBE=v.bind(null,g)}(),typeof Float64Array<"u"?function(){var w=new Float64Array([-0]),v=new Uint8Array(w.buffer),l=128===v[7];function p(E,y,f){w[0]=E,y[f]=v[0],y[f+1]=v[1],y[f+2]=v[2],y[f+3]=v[3],y[f+4]=v[4],y[f+5]=v[5],y[f+6]=v[6],y[f+7]=v[7]}function d(E,y,f){w[0]=E,y[f]=v[7],y[f+1]=v[6],y[f+2]=v[5],y[f+3]=v[4],y[f+4]=v[3],y[f+5]=v[2],y[f+6]=v[1],y[f+7]=v[0]}function _(E,y){return v[0]=E[y],v[1]=E[y+1],v[2]=E[y+2],v[3]=E[y+3],v[4]=E[y+4],v[5]=E[y+5],v[6]=E[y+6],v[7]=E[y+7],w[0]}function I(E,y){return v[7]=E[y],v[6]=E[y+1],v[5]=E[y+2],v[4]=E[y+3],v[3]=E[y+4],v[2]=E[y+5],v[1]=E[y+6],v[0]=E[y+7],w[0]}b.writeDoubleLE=l?p:d,b.writeDoubleBE=l?d:p,b.readDoubleLE=l?_:I,b.readDoubleBE=l?I:_}():function(){function w(l,p,d,_,I,E){var y=_<0?1:0;if(y&&(_=-_),0===_)l(0,I,E+p),l(1/_>0?0:2147483648,I,E+d);else if(isNaN(_))l(0,I,E+p),l(2146959360,I,E+d);else if(_>17976931348623157e292)l(0,I,E+p),l((y<<31|2146435072)>>>0,I,E+d);else{var f;if(_<22250738585072014e-324)l((f=_/5e-324)>>>0,I,E+p),l((y<<31|f/4294967296)>>>0,I,E+d);else{var C=Math.floor(Math.log(_)/Math.LN2);1024===C&&(C=1023),l(4503599627370496*(f=_*Math.pow(2,-C))>>>0,I,E+p),l((y<<31|C+1023<<20|1048576*f&1048575)>>>0,I,E+d)}}}function v(l,p,d,_,I){var E=l(_,I+p),y=l(_,I+d),f=2*(y>>31)+1,C=y>>>20&2047,A=4294967296*(1048575&y)+E;return 2047===C?A?NaN:f*(1/0):0===C?5e-324*f*A:f*Math.pow(2,C-1075)*(A+4503599627370496)}b.writeDoubleLE=w.bind(null,N,0,4),b.writeDoubleBE=w.bind(null,h,4,0),b.readDoubleLE=v.bind(null,u,0,4),b.readDoubleBE=v.bind(null,g,4,0)}(),b}function N(b,w,v){w[v]=255&b,w[v+1]=b>>>8&255,w[v+2]=b>>>16&255,w[v+3]=b>>>24}function h(b,w,v){w[v]=b>>>24,w[v+1]=b>>>16&255,w[v+2]=b>>>8&255,w[v+3]=255&b}function u(b,w){return(b[w]|b[w+1]<<8|b[w+2]<<16|b[w+3]<<24)>>>0}function g(b,w){return(b[w]<<24|b[w+1]<<16|b[w+2]<<8|b[w+3])>>>0}J.exports=G(G)},716:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(J){}return null}module.exports=inquire},1311:(J,G)=>{"use strict";var N=G,h=N.isAbsolute=function(b){return/^(?:\/|\w+:)/.test(b)},u=N.normalize=function(b){var w=(b=b.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),v=h(b),l="";v&&(l=w.shift()+"/");for(var p=0;p0&&".."!==w[p-1]?w.splice(--p,2):v?w.splice(p,1):++p:"."===w[p]?w.splice(p,1):++p;return l+w.join("/")};N.resolve=function(b,w,v){return v||(w=u(w)),h(w)?w:(v||(b=u(b)),(b=b.replace(/(?:\/|^)[^/]+$/,"")).length?u(b+"/"+w):w)}},4479:J=>{"use strict";J.exports=function G(N,h,u){var g=u||8192,b=g>>>1,w=null,v=g;return function(p){if(p<1||p>b)return N(p);v+p>g&&(w=N(g),v=0);var d=h.call(w,v,v+=p);return 7&v&&(v=1+(7|v)),d}}},7768:(J,G)=>{"use strict";var N=G;N.length=function(u){for(var g=0,b=0,w=0;w191&&d<224?l[p++]=(31&d)<<6|63&u[g++]:d>239&&d<365?(d=((7&d)<<18|(63&u[g++])<<12|(63&u[g++])<<6|63&u[g++])-65536,l[p++]=55296+(d>>10),l[p++]=56320+(1023&d)):l[p++]=(15&d)<<12|(63&u[g++])<<6|63&u[g++],p>8191&&((v||(v=[])).push(String.fromCharCode.apply(String,l)),p=0);return v?(p&&v.push(String.fromCharCode.apply(String,l.slice(0,p))),v.join("")):String.fromCharCode.apply(String,l.slice(0,p))},N.write=function(u,g,b){for(var v,l,w=b,p=0;p>6|192,g[b++]=63&v|128):55296==(64512&v)&&56320==(64512&(l=u.charCodeAt(p+1)))?(++p,g[b++]=(v=65536+((1023&v)<<10)+(1023&l))>>18|240,g[b++]=v>>12&63|128,g[b++]=v>>6&63|128,g[b++]=63&v|128):(g[b++]=v>>12|224,g[b++]=v>>6&63|128,g[b++]=63&v|128);return b-w}},4502:(J,G,N)=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});var h=N(8046);function v(Z,q,ne){return void 0===q&&(q=new Uint8Array(2)),void 0===ne&&(ne=0),q[ne+0]=Z>>>8,q[ne+1]=Z>>>0,q}function l(Z,q,ne){return void 0===q&&(q=new Uint8Array(2)),void 0===ne&&(ne=0),q[ne+0]=Z>>>0,q[ne+1]=Z>>>8,q}function p(Z,q){return void 0===q&&(q=0),Z[q]<<24|Z[q+1]<<16|Z[q+2]<<8|Z[q+3]}function d(Z,q){return void 0===q&&(q=0),(Z[q]<<24|Z[q+1]<<16|Z[q+2]<<8|Z[q+3])>>>0}function _(Z,q){return void 0===q&&(q=0),Z[q+3]<<24|Z[q+2]<<16|Z[q+1]<<8|Z[q]}function I(Z,q){return void 0===q&&(q=0),(Z[q+3]<<24|Z[q+2]<<16|Z[q+1]<<8|Z[q])>>>0}function E(Z,q,ne){return void 0===q&&(q=new Uint8Array(4)),void 0===ne&&(ne=0),q[ne+0]=Z>>>24,q[ne+1]=Z>>>16,q[ne+2]=Z>>>8,q[ne+3]=Z>>>0,q}function y(Z,q,ne){return void 0===q&&(q=new Uint8Array(4)),void 0===ne&&(ne=0),q[ne+0]=Z>>>0,q[ne+1]=Z>>>8,q[ne+2]=Z>>>16,q[ne+3]=Z>>>24,q}function D(Z,q,ne){return void 0===q&&(q=new Uint8Array(8)),void 0===ne&&(ne=0),E(Z/4294967296>>>0,q,ne),E(Z>>>0,q,ne+4),q}function x(Z,q,ne){return void 0===q&&(q=new Uint8Array(8)),void 0===ne&&(ne=0),y(Z>>>0,q,ne),y(Z/4294967296>>>0,q,ne+4),q}G.readInt16BE=function u(Z,q){return void 0===q&&(q=0),(Z[q+0]<<8|Z[q+1])<<16>>16},G.readUint16BE=function g(Z,q){return void 0===q&&(q=0),(Z[q+0]<<8|Z[q+1])>>>0},G.readInt16LE=function b(Z,q){return void 0===q&&(q=0),(Z[q+1]<<8|Z[q])<<16>>16},G.readUint16LE=function w(Z,q){return void 0===q&&(q=0),(Z[q+1]<<8|Z[q])>>>0},G.writeUint16BE=v,G.writeInt16BE=v,G.writeUint16LE=l,G.writeInt16LE=l,G.readInt32BE=p,G.readUint32BE=d,G.readInt32LE=_,G.readUint32LE=I,G.writeUint32BE=E,G.writeInt32BE=E,G.writeUint32LE=y,G.writeInt32LE=y,G.readInt64BE=function f(Z,q){void 0===q&&(q=0);var ne=p(Z,q),oe=p(Z,q+4);return 4294967296*ne+oe-4294967296*(oe>>31)},G.readUint64BE=function C(Z,q){return void 0===q&&(q=0),4294967296*d(Z,q)+d(Z,q+4)},G.readInt64LE=function A(Z,q){void 0===q&&(q=0);var ne=_(Z,q);return 4294967296*_(Z,q+4)+ne-4294967296*(ne>>31)},G.readUint64LE=function P(Z,q){void 0===q&&(q=0);var ne=I(Z,q);return 4294967296*I(Z,q+4)+ne},G.writeUint64BE=D,G.writeInt64BE=D,G.writeUint64LE=x,G.writeInt64LE=x,G.readUintBE=function M(Z,q,ne){if(void 0===ne&&(ne=0),Z%8!=0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(Z/8>q.length-ne)throw new Error("readUintBE: array is too short for the given bitLength");for(var oe=0,de=1,pe=Z/8+ne-1;pe>=ne;pe--)oe+=q[pe]*de,de*=256;return oe},G.readUintLE=function B(Z,q,ne){if(void 0===ne&&(ne=0),Z%8!=0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(Z/8>q.length-ne)throw new Error("readUintLE: array is too short for the given bitLength");for(var oe=0,de=1,pe=ne;pe=oe;pe--)ne[pe]=q/de&255,de*=256;return ne},G.writeUintLE=function z(Z,q,ne,oe){if(void 0===ne&&(ne=new Uint8Array(Z/8)),void 0===oe&&(oe=0),Z%8!=0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!h.isSafeInteger(q))throw new Error("writeUintLE value must be an integer");for(var de=1,pe=oe;pe{"use strict";Object.defineProperty(G,"__esModule",{value:!0});var h=N(4502),u=N(9815);function b(p,d,_){for(var I=1634760805,E=857760878,y=2036477234,f=1797285236,C=_[3]<<24|_[2]<<16|_[1]<<8|_[0],A=_[7]<<24|_[6]<<16|_[5]<<8|_[4],P=_[11]<<24|_[10]<<16|_[9]<<8|_[8],D=_[15]<<24|_[14]<<16|_[13]<<8|_[12],x=_[19]<<24|_[18]<<16|_[17]<<8|_[16],M=_[23]<<24|_[22]<<16|_[21]<<8|_[20],B=_[27]<<24|_[26]<<16|_[25]<<8|_[24],F=_[31]<<24|_[30]<<16|_[29]<<8|_[28],z=d[3]<<24|d[2]<<16|d[1]<<8|d[0],S=d[7]<<24|d[6]<<16|d[5]<<8|d[4],O=d[11]<<24|d[10]<<16|d[9]<<8|d[8],H=d[15]<<24|d[14]<<16|d[13]<<8|d[12],L=I,j=E,re=y,$=f,te=C,Z=A,q=P,ne=D,oe=x,de=M,pe=B,ke=F,Se=z,Pe=S,we=O,$e=H,K=0;K<20;K+=2)te=(te^=oe=oe+(Se=(Se^=L=L+te|0)>>>16|Se<<16)|0)>>>20|te<<12,Z=(Z^=de=de+(Pe=(Pe^=j=j+Z|0)>>>16|Pe<<16)|0)>>>20|Z<<12,q=(q^=pe=pe+(we=(we^=re=re+q|0)>>>16|we<<16)|0)>>>20|q<<12,ne=(ne^=ke=ke+($e=($e^=$=$+ne|0)>>>16|$e<<16)|0)>>>20|ne<<12,q=(q^=pe=pe+(we=(we^=re=re+q|0)>>>24|we<<8)|0)>>>25|q<<7,ne=(ne^=ke=ke+($e=($e^=$=$+ne|0)>>>24|$e<<8)|0)>>>25|ne<<7,Z=(Z^=de=de+(Pe=(Pe^=j=j+Z|0)>>>24|Pe<<8)|0)>>>25|Z<<7,te=(te^=oe=oe+(Se=(Se^=L=L+te|0)>>>24|Se<<8)|0)>>>25|te<<7,Z=(Z^=pe=pe+($e=($e^=L=L+Z|0)>>>16|$e<<16)|0)>>>20|Z<<12,q=(q^=ke=ke+(Se=(Se^=j=j+q|0)>>>16|Se<<16)|0)>>>20|q<<12,ne=(ne^=oe=oe+(Pe=(Pe^=re=re+ne|0)>>>16|Pe<<16)|0)>>>20|ne<<12,te=(te^=de=de+(we=(we^=$=$+te|0)>>>16|we<<16)|0)>>>20|te<<12,ne=(ne^=oe=oe+(Pe=(Pe^=re=re+ne|0)>>>24|Pe<<8)|0)>>>25|ne<<7,te=(te^=de=de+(we=(we^=$=$+te|0)>>>24|we<<8)|0)>>>25|te<<7,q=(q^=ke=ke+(Se=(Se^=j=j+q|0)>>>24|Se<<8)|0)>>>25|q<<7,Z=(Z^=pe=pe+($e=($e^=L=L+Z|0)>>>24|$e<<8)|0)>>>25|Z<<7;h.writeUint32LE(L+I|0,p,0),h.writeUint32LE(j+E|0,p,4),h.writeUint32LE(re+y|0,p,8),h.writeUint32LE($+f|0,p,12),h.writeUint32LE(te+C|0,p,16),h.writeUint32LE(Z+A|0,p,20),h.writeUint32LE(q+P|0,p,24),h.writeUint32LE(ne+D|0,p,28),h.writeUint32LE(oe+x|0,p,32),h.writeUint32LE(de+M|0,p,36),h.writeUint32LE(pe+B|0,p,40),h.writeUint32LE(ke+F|0,p,44),h.writeUint32LE(Se+z|0,p,48),h.writeUint32LE(Pe+S|0,p,52),h.writeUint32LE(we+O|0,p,56),h.writeUint32LE($e+H|0,p,60)}function w(p,d,_,I,E){if(void 0===E&&(E=0),32!==p.length)throw new Error("ChaCha: key size must be 32 bytes");if(I.length<_.length)throw new Error("ChaCha: destination is shorter than source");var y,f;if(0===E){if(8!==d.length&&12!==d.length)throw new Error("ChaCha nonce must be 8 or 12 bytes");(y=new Uint8Array(16)).set(d,f=y.length-d.length)}else{if(16!==d.length)throw new Error("ChaCha nonce with counter must be 16 bytes");y=d,f=E}for(var C=new Uint8Array(64),A=0;A<_.length;A+=64){b(C,y,p);for(var P=A;P>>=8,d++;if(I>0)throw new Error("ChaCha: counter overflow")}G.streamXOR=w,G.stream=function v(p,d,_,I){return void 0===I&&(I=0),u.wipe(_),w(p,d,_,_,I)}},5876:(J,G,N)=>{"use strict";var u=N(4484),g=N(314),b=N(9815),w=N(4502),v=N(9976);G.Cv=32,G.WH=12,G.pg=16;var l=new Uint8Array(16),p=function(){function d(_){if(this.nonceLength=G.WH,this.tagLength=G.pg,_.length!==G.Cv)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(_)}return d.prototype.seal=function(_,I,E,y){if(_.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var f=new Uint8Array(16);f.set(_,f.length-_.length);var C=new Uint8Array(32);u.stream(this._key,f,C,4);var P,A=I.length+this.tagLength;if(y){if(y.length!==A)throw new Error("ChaCha20Poly1305: incorrect destination length");P=y}else P=new Uint8Array(A);return u.streamXOR(this._key,f,I,P,4),this._authenticate(P.subarray(P.length-this.tagLength,P.length),C,P.subarray(0,P.length-this.tagLength),E),b.wipe(f),P},d.prototype.open=function(_,I,E,y){if(_.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(I.length0&&f.update(l.subarray(y.length%16))),f.update(E),E.length%16>0&&f.update(l.subarray(E.length%16));var C=new Uint8Array(8);y&&w.writeUint64LE(y.length,C),f.update(C),w.writeUint64LE(E.length,C),f.update(C);for(var A=f.digest(),P=0;P{"use strict";function u(b,w){if(b.length!==w.length)return 0;for(var v=0,l=0;l>>8}Object.defineProperty(G,"__esModule",{value:!0}),G.select=function N(b,w,v){return~(b-1)&w|b-1&v},G.lessOrEqual=function h(b,w){return(0|b)-(0|w)-1>>>31&1},G.compare=u,G.equal=function g(b,w){return 0!==b.length&&0!==w.length&&0!==u(b,w)}},5571:(J,G)=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0}),G.isSerializableHash=function N(h){return typeof h.saveState<"u"&&typeof h.restoreState<"u"&&typeof h.cleanSavedState<"u"}},5705:(J,G,N)=>{"use strict";var u=N(4193),g=N(9815),b=function(){function w(v,l,p,d){void 0===p&&(p=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=v,this._info=d;var _=u.hmac(this._hash,p,l);this._hmac=new u.HMAC(v,_),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return w.prototype._fillBuffer=function(){this._counter[0]++;var v=this._counter[0];if(0===v)throw new Error("hkdf: cannot expand more");this._hmac.reset(),v>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},w.prototype.expand=function(v){for(var l=new Uint8Array(v),p=0;p{"use strict";Object.defineProperty(G,"__esModule",{value:!0});var h=N(5571),u=N(9976),g=N(9815),b=function(){function v(l,p){this._finished=!1,this._inner=new l,this._outer=new l,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var d=new Uint8Array(this.blockSize);p.length>this.blockSize?this._inner.update(p).finish(d).clean():d.set(p);for(var _=0;_{"use strict";Object.defineProperty(G,"__esModule",{value:!0}),G.mul=Math.imul||function N(v,l){var d=65535&v,I=65535&l;return d*I+((v>>>16&65535)*I+d*(l>>>16&65535)<<16>>>0)|0},G.add=function h(v,l){return v+l|0},G.sub=function u(v,l){return v-l|0},G.rotl=function g(v,l){return v<>>32-l},G.rotr=function b(v,l){return v<<32-l|v>>>l},G.isInteger=Number.isInteger||function w(v){return"number"==typeof v&&isFinite(v)&&Math.floor(v)===v},G.MAX_SAFE_INTEGER=9007199254740991,G.isSafeInteger=function(v){return G.isInteger(v)&&v>=-G.MAX_SAFE_INTEGER&&v<=G.MAX_SAFE_INTEGER}},314:(J,G,N)=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});var h=N(9976),u=N(9815);G.DIGEST_LENGTH=16;var g=function(){function v(l){this.digestLength=G.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var p=l[0]|l[1]<<8;this._r[0]=8191&p;var d=l[2]|l[3]<<8;this._r[1]=8191&(p>>>13|d<<3);var _=l[4]|l[5]<<8;this._r[2]=7939&(d>>>10|_<<6);var I=l[6]|l[7]<<8;this._r[3]=8191&(_>>>7|I<<9);var E=l[8]|l[9]<<8;this._r[4]=255&(I>>>4|E<<12),this._r[5]=E>>>1&8190;var y=l[10]|l[11]<<8;this._r[6]=8191&(E>>>14|y<<2);var f=l[12]|l[13]<<8;this._r[7]=8065&(y>>>11|f<<5);var C=l[14]|l[15]<<8;this._r[8]=8191&(f>>>8|C<<8),this._r[9]=C>>>5&127,this._pad[0]=l[16]|l[17]<<8,this._pad[1]=l[18]|l[19]<<8,this._pad[2]=l[20]|l[21]<<8,this._pad[3]=l[22]|l[23]<<8,this._pad[4]=l[24]|l[25]<<8,this._pad[5]=l[26]|l[27]<<8,this._pad[6]=l[28]|l[29]<<8,this._pad[7]=l[30]|l[31]<<8}return v.prototype._blocks=function(l,p,d){for(var _=this._fin?0:2048,I=this._h[0],E=this._h[1],y=this._h[2],f=this._h[3],C=this._h[4],A=this._h[5],P=this._h[6],D=this._h[7],x=this._h[8],M=this._h[9],B=this._r[0],F=this._r[1],z=this._r[2],S=this._r[3],O=this._r[4],H=this._r[5],L=this._r[6],j=this._r[7],re=this._r[8],$=this._r[9];d>=16;){var te=l[p+0]|l[p+1]<<8,Z=l[p+2]|l[p+3]<<8,q=l[p+4]|l[p+5]<<8,ne=l[p+6]|l[p+7]<<8,oe=l[p+8]|l[p+9]<<8,de=l[p+10]|l[p+11]<<8,pe=l[p+12]|l[p+13]<<8,ke=l[p+14]|l[p+15]<<8,Se=0,Pe=Se;Pe+=(I+=8191&te)*B,Pe+=(E+=8191&(te>>>13|Z<<3))*(5*$),Pe+=(y+=8191&(Z>>>10|q<<6))*(5*re),Pe+=(f+=8191&(q>>>7|ne<<9))*(5*j),Se=(Pe+=(C+=8191&(ne>>>4|oe<<12))*(5*L))>>>13,Pe&=8191,Pe+=(A+=oe>>>1&8191)*(5*H),Pe+=(P+=8191&(oe>>>14|de<<2))*(5*O),Pe+=(D+=8191&(de>>>11|pe<<5))*(5*S),Pe+=(x+=8191&(pe>>>8|ke<<8))*(5*z);var we=Se+=(Pe+=(M+=ke>>>5|_)*(5*F))>>>13;we+=I*F,we+=E*B,we+=y*(5*$),we+=f*(5*re),Se=(we+=C*(5*j))>>>13,we&=8191,we+=A*(5*L),we+=P*(5*H),we+=D*(5*O),we+=x*(5*S),Se+=(we+=M*(5*z))>>>13,we&=8191;var $e=Se;$e+=I*z,$e+=E*F,$e+=y*B,$e+=f*(5*$),Se=($e+=C*(5*re))>>>13,$e&=8191,$e+=A*(5*j),$e+=P*(5*L),$e+=D*(5*H),$e+=x*(5*O);var K=Se+=($e+=M*(5*S))>>>13;K+=I*S,K+=E*z,K+=y*F,K+=f*B,Se=(K+=C*(5*$))>>>13,K&=8191,K+=A*(5*re),K+=P*(5*j),K+=D*(5*L),K+=x*(5*H);var Ee=Se+=(K+=M*(5*O))>>>13;Ee+=I*O,Ee+=E*S,Ee+=y*z,Ee+=f*F,Se=(Ee+=C*B)>>>13,Ee&=8191,Ee+=A*(5*$),Ee+=P*(5*re),Ee+=D*(5*j),Ee+=x*(5*L);var Ce=Se+=(Ee+=M*(5*H))>>>13;Ce+=I*H,Ce+=E*O,Ce+=y*S,Ce+=f*z,Se=(Ce+=C*F)>>>13,Ce&=8191,Ce+=A*B,Ce+=P*(5*$),Ce+=D*(5*re),Ce+=x*(5*j);var xe=Se+=(Ce+=M*(5*L))>>>13;xe+=I*L,xe+=E*H,xe+=y*O,xe+=f*S,Se=(xe+=C*z)>>>13,xe&=8191,xe+=A*F,xe+=P*B,xe+=D*(5*$),xe+=x*(5*re);var Ke=Se+=(xe+=M*(5*j))>>>13;Ke+=I*j,Ke+=E*L,Ke+=y*H,Ke+=f*O,Se=(Ke+=C*S)>>>13,Ke&=8191,Ke+=A*z,Ke+=P*F,Ke+=D*B,Ke+=x*(5*$);var We=Se+=(Ke+=M*(5*re))>>>13;We+=I*re,We+=E*j,We+=y*L,We+=f*H,Se=(We+=C*O)>>>13,We&=8191,We+=A*S,We+=P*z,We+=D*F,We+=x*B;var Je=Se+=(We+=M*(5*$))>>>13;Je+=I*$,Je+=E*re,Je+=y*j,Je+=f*L,Se=(Je+=C*H)>>>13,Je&=8191,Je+=A*O,Je+=P*S,Je+=D*z,Je+=x*F,I=Pe=8191&(Se=(Se=((Se+=(Je+=M*B)>>>13)<<2)+Se|0)+(Pe&=8191)|0),E=we+=Se>>>=13,y=$e&=8191,f=K&=8191,C=Ee&=8191,A=Ce&=8191,P=xe&=8191,D=Ke&=8191,x=We&=8191,M=Je&=8191,p+=16,d-=16}this._h[0]=I,this._h[1]=E,this._h[2]=y,this._h[3]=f,this._h[4]=C,this._h[5]=A,this._h[6]=P,this._h[7]=D,this._h[8]=x,this._h[9]=M},v.prototype.finish=function(l,p){void 0===p&&(p=0);var _,I,E,y,d=new Uint16Array(10);if(this._leftover){for(y=this._leftover,this._buffer[y++]=1;y<16;y++)this._buffer[y]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(_=this._h[1]>>>13,this._h[1]&=8191,y=2;y<10;y++)this._h[y]+=_,_=this._h[y]>>>13,this._h[y]&=8191;for(this._h[0]+=5*_,_=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=_,_=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=_,d[0]=this._h[0]+5,_=d[0]>>>13,d[0]&=8191,y=1;y<10;y++)d[y]=this._h[y]+_,_=d[y]>>>13,d[y]&=8191;for(d[9]-=8192,I=(1^_)-1,y=0;y<10;y++)d[y]&=I;for(I=~I,y=0;y<10;y++)this._h[y]=this._h[y]&I|d[y];for(this._h[0]=65535&(this._h[0]|this._h[1]<<13),this._h[1]=65535&(this._h[1]>>>3|this._h[2]<<10),this._h[2]=65535&(this._h[2]>>>6|this._h[3]<<7),this._h[3]=65535&(this._h[3]>>>9|this._h[4]<<4),this._h[4]=65535&(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14),this._h[5]=65535&(this._h[6]>>>2|this._h[7]<<11),this._h[6]=65535&(this._h[7]>>>5|this._h[8]<<8),this._h[7]=65535&(this._h[8]>>>8|this._h[9]<<5),this._h[0]=65535&(E=this._h[0]+this._pad[0]),y=1;y<8;y++)this._h[y]=65535&(E=(this._h[y]+this._pad[y]|0)+(E>>>16)|0);return l[p+0]=this._h[0]>>>0,l[p+1]=this._h[0]>>>8,l[p+2]=this._h[1]>>>0,l[p+3]=this._h[1]>>>8,l[p+4]=this._h[2]>>>0,l[p+5]=this._h[2]>>>8,l[p+6]=this._h[3]>>>0,l[p+7]=this._h[3]>>>8,l[p+8]=this._h[4]>>>0,l[p+9]=this._h[4]>>>8,l[p+10]=this._h[5]>>>0,l[p+11]=this._h[5]>>>8,l[p+12]=this._h[6]>>>0,l[p+13]=this._h[6]>>>8,l[p+14]=this._h[7]>>>0,l[p+15]=this._h[7]>>>8,this._finished=!0,this},v.prototype.update=function(l){var _,p=0,d=l.length;if(this._leftover){(_=16-this._leftover)>d&&(_=d);for(var I=0;I<_;I++)this._buffer[this._leftover+I]=l[p+I];if(d-=_,p+=_,this._leftover+=_,this._leftover<16)return this;this._blocks(this._buffer,0,16),this._leftover=0}if(d>=16&&(this._blocks(l,p,_=d-d%16),p+=_,d-=_),d){for(I=0;I{"use strict";Object.defineProperty(G,"__esModule",{value:!0}),G.randomStringForEntropy=G.randomString=G.randomUint32=G.randomBytes=G.defaultRandomSource=void 0;const h=N(9753),u=N(4502),g=N(9815);function b(d,_=G.defaultRandomSource){return _.randomBytes(d)}G.defaultRandomSource=new h.SystemRandomSource,G.randomBytes=b,G.randomUint32=function w(d=G.defaultRandomSource){const _=b(4,d),I=(0,u.readUint32LE)(_);return(0,g.wipe)(_),I};const v="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function l(d,_=v,I=G.defaultRandomSource){if(_.length<2)throw new Error("randomString charset is too short");if(_.length>256)throw new Error("randomString charset is too long");let E="";const y=_.length,f=256-256%y;for(;d>0;){const C=b(Math.ceil(256*d/f),I);for(let A=0;A0;A++){const P=C[A];P{"use strict";Object.defineProperty(G,"__esModule",{value:!0}),G.BrowserRandomSource=void 0,G.BrowserRandomSource=class h{constructor(){this.isAvailable=!1,this.isInstantiated=!1;const g=typeof self<"u"?self.crypto||self.msCrypto:null;g&&void 0!==g.getRandomValues&&(this._crypto=g,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(g){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");const b=new Uint8Array(g);for(let w=0;w{"use strict";Object.defineProperty(G,"__esModule",{value:!0}),G.NodeRandomSource=void 0;const h=N(9815);G.NodeRandomSource=class u{constructor(){this.isAvailable=!1,this.isInstantiated=!1;{const b=N(5883);b&&b.randomBytes&&(this._crypto=b,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(b){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let w=this._crypto.randomBytes(b);if(w.length!==b)throw new Error("NodeRandomSource: got fewer bytes than requested");const v=new Uint8Array(b);for(let l=0;l{"use strict";Object.defineProperty(G,"__esModule",{value:!0}),G.SystemRandomSource=void 0;const h=N(7170),u=N(1382);G.SystemRandomSource=class g{constructor(){return this.isAvailable=!1,this.name="",this._source=new h.BrowserRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Browser")):(this._source=new u.NodeRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Node")):void 0)}randomBytes(w){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(w)}}},893:(J,G,N)=>{"use strict";var u=N(4502),g=N(9815);G.k=32,G.cn=64;var b=function(){function p(){this.digestLength=G.k,this.blockSize=G.cn,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return p.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},p.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},p.prototype.clean=function(){g.wipe(this._buffer),g.wipe(this._temp),this.reset()},p.prototype.update=function(d,_){if(void 0===_&&(_=d.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var I=0;if(this._bytesHashed+=_,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=d[I++],_--;this._bufferLength===this.blockSize&&(v(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(_>=this.blockSize&&(I=v(this._temp,this._state,d,I,_),_%=this.blockSize);_>0;)this._buffer[this._bufferLength++]=d[I++],_--;return this},p.prototype.finish=function(d){if(!this._finished){var _=this._bytesHashed,I=this._bufferLength,E=_/536870912|0,y=_<<3,f=_%64<56?64:128;this._buffer[I]=128;for(var C=I+1;C0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},p.prototype.restoreState=function(d){return this._state.set(d.state),this._bufferLength=d.bufferLength,d.buffer&&this._buffer.set(d.buffer),this._bytesHashed=d.bytesHashed,this._finished=!1,this},p.prototype.cleanSavedState=function(d){g.wipe(d.state),d.buffer&&g.wipe(d.buffer),d.bufferLength=0,d.bytesHashed=0},p}();G.mE=b;var w=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function v(p,d,_,I,E){for(;E>=64;){for(var y=d[0],f=d[1],C=d[2],A=d[3],P=d[4],D=d[5],x=d[6],M=d[7],B=0;B<16;B++)p[B]=u.readUint32BE(_,I+4*B);for(B=16;B<64;B++){var z=p[B-2];p[B]=((S=(z>>>17|z<<15)^(z>>>19|z<<13)^z>>>10)+p[B-7]|0)+((O=((z=p[B-15])>>>7|z<<25)^(z>>>18|z<<14)^z>>>3)+p[B-16]|0)}for(B=0;B<64;B++){var S=(((P>>>6|P<<26)^(P>>>11|P<<21)^(P>>>25|P<<7))+(P&D^~P&x)|0)+(M+(w[B]+p[B]|0)|0)|0,O=((y>>>2|y<<30)^(y>>>13|y<<19)^(y>>>22|y<<10))+(y&f^y&C^f&C)|0;M=x,x=D,D=P,P=A+S|0,A=C,C=f,f=y,y=S+O|0}d[0]+=y,d[1]+=f,d[2]+=C,d[3]+=A,d[4]+=P,d[5]+=D,d[6]+=x,d[7]+=M,I+=64,E-=64}return I}G.vp=function l(p){var d=new b;d.update(p);var _=d.digest();return d.clean(),_}},9815:(J,G)=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0}),G.wipe=function N(h){for(var u=0;u{"use strict";G.gi=G.Au=G._w=G.KS=G.kz=void 0;const u=N(5784),g=N(9815);function b(B){const F=new Float64Array(16);if(B)for(let z=0;z=0;--ne){const oe=z[ne>>>3]>>>(7&ne)&1;p(O,H,oe),p(L,j,oe),I(re,O,L),E(O,O,L),I(L,H,j),E(H,H,j),f(j,re),f($,O),y(O,L,O),y(L,H,re),I(re,O,L),E(O,O,L),f(H,O),E(L,j,$),y(O,L,v),I(O,O,j),y(L,L,O),y(O,j,$),y(j,H,S),f(H,re),p(O,H,oe),p(L,j,oe)}for(let ne=0;ne<16;ne++)S[ne+16]=O[ne],S[ne+32]=L[ne],S[ne+48]=H[ne],S[ne+64]=j[ne];const te=S.subarray(32),Z=S.subarray(16);(function C(B,F){const z=b();for(let S=0;S<16;S++)z[S]=F[S];for(let S=253;S>=0;S--)f(z,z),2!==S&&4!==S&&y(z,z,F);for(let S=0;S<16;S++)B[S]=z[S]})(te,te),y(Z,Z,te);const q=new Uint8Array(32);return function d(B,F){const z=b(),S=b();for(let O=0;O<16;O++)S[O]=F[O];l(S),l(S),l(S);for(let O=0;O<2;O++){z[0]=S[0]-65517;for(let L=1;L<15;L++)z[L]=S[L]-65535-(z[L-1]>>16&1),z[L-1]&=65535;z[15]=S[15]-32767-(z[14]>>16&1);const H=z[15]>>16&1;z[14]&=65535,p(S,z,1-H)}for(let O=0;O<16;O++)B[2*O]=255&S[O],B[2*O+1]=S[O]>>8}(q,Z),q}function P(B){return A(B,w)}function D(B){if(B.length!==G.KS)throw new Error(`x25519: seed must be ${G.KS} bytes`);const F=new Uint8Array(B);return{publicKey:P(F),secretKey:F}}G._w=D,G.Au=function x(B){const F=(0,u.randomBytes)(32,B),z=D(F);return(0,g.wipe)(F),z},G.gi=function M(B,F,z=!1){if(B.length!==G.kz)throw new Error("X25519: incorrect secret key length");if(F.length!==G.kz)throw new Error("X25519: incorrect public key length");const S=A(B,F);if(z){let O=0;for(let H=0;H{function G(N){const h=new globalThis.AbortController;function u(){h.abort();for(const g of N)!g||!g.removeEventListener||g.removeEventListener("abort",u)}for(const g of N)if(g&&g.addEventListener){if(g.aborted){u();break}g.addEventListener("abort",u)}return h.signal}J.exports=G,J.exports.anySignal=G},3210:J=>{var G=1e3,N=60*G,h=60*N,u=24*h;function p(d,_,I,E){var y=_>=1.5*I;return Math.round(d/I)+" "+E+(y?"s":"")}J.exports=function(d,_){_=_||{};var I=typeof d;if("string"===I&&d.length>0)return function w(d){if(!((d=String(d)).length>100)){var _=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(_){var I=parseFloat(_[1]);switch((_[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*I;case"weeks":case"week":case"w":return 6048e5*I;case"days":case"day":case"d":return I*u;case"hours":case"hour":case"hrs":case"hr":case"h":return I*h;case"minutes":case"minute":case"mins":case"min":case"m":return I*N;case"seconds":case"second":case"secs":case"sec":case"s":return I*G;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return I;default:return}}}}(d);if("number"===I&&isFinite(d))return _.long?function l(d){var _=Math.abs(d);return _>=u?p(d,_,u,"day"):_>=h?p(d,_,h,"hour"):_>=N?p(d,_,N,"minute"):_>=G?p(d,_,G,"second"):d+" ms"}(d):function v(d){var _=Math.abs(d);return _>=u?Math.round(d/u)+"d":_>=h?Math.round(d/h)+"h":_>=N?Math.round(d/N)+"m":_>=G?Math.round(d/G)+"s":d+"ms"}(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))}},1455:(J,G,N)=>{G.formatArgs=function u(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+J.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;l.splice(1,0,p,"color: inherit");let d=0,_=0;l[0].replace(/%[a-zA-Z%]/g,I=>{"%%"!==I&&(d++,"%c"===I&&(_=d))}),l.splice(_,0,p)},G.save=function g(l){try{l?G.storage.setItem("debug",l):G.storage.removeItem("debug")}catch{}},G.load=function b(){let l;try{l=G.storage.getItem("debug")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l=process.env.DEBUG),l},G.useColors=function h(){return!(!(typeof window<"u"&&window.process)||"renderer"!==window.process.type&&!window.process.__nwjs)||!(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},G.storage=function w(){try{return localStorage}catch{}}(),G.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),G.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],G.log=console.debug||console.log||(()=>{}),J.exports=N(3283)(G);const{formatters:v}=J.exports;v.j=function(l){try{return JSON.stringify(l)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}},3283:(J,G,N)=>{J.exports=function h(u){function b(E){let y,C,A,f=null;function P(...D){if(!P.enabled)return;const x=P,M=Number(new Date);x.diff=M-(y||M),x.prev=y,x.curr=M,y=M,D[0]=b.coerce(D[0]),"string"!=typeof D[0]&&D.unshift("%O");let F=0;D[0]=D[0].replace(/%([a-zA-Z%])/g,(S,O)=>{if("%%"===S)return"%";F++;const H=b.formatters[O];return"function"==typeof H&&(S=H.call(x,D[F]),D.splice(F,1),F--),S}),b.formatArgs.call(x,D),(x.log||b.log).apply(x,D)}return P.namespace=E,P.useColors=b.useColors(),P.color=b.selectColor(E),P.extend=w,P.destroy=b.destroy,Object.defineProperty(P,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==f?f:(C!==b.namespaces&&(C=b.namespaces,A=b.enabled(E)),A),set:D=>{f=D}}),"function"==typeof b.init&&b.init(P),P}function w(E,y){const f=b(this.namespace+(typeof y>"u"?":":y)+E);return f.log=this.log,f}function d(E){return E.toString().substring(2,E.toString().length-2).replace(/\.\*\?$/,"*")}return b.debug=b,b.default=b,b.coerce=function _(E){return E instanceof Error?E.stack||E.message:E},b.disable=function l(){const E=[...b.names.map(d),...b.skips.map(d).map(y=>"-"+y)].join(",");return b.enable(""),E},b.enable=function v(E){let y;b.save(E),b.namespaces=E,b.names=[],b.skips=[];const f=("string"==typeof E?E:"").split(/[\s,]+/),C=f.length;for(y=0;y{b[E]=u[E]}),b.names=[],b.skips=[],b.formatters={},b.selectColor=function g(E){let y=0;for(let f=0;f{"use strict";function G(N,u){u=u||{},this._head=0,this._tail=0,this._capacity=u.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(N)&&this._fromArray(N)}G.prototype.peekAt=function(h){var u=h;if(u===(0|u)){var g=this.size();if(!(u>=g||u<-g))return u<0&&(u+=g),this._list[u=this._head+u&this._capacityMask]}},G.prototype.get=function(h){return this.peekAt(h)},G.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},G.prototype.peekFront=function(){return this.peek()},G.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(G.prototype,"length",{get:function(){return this.size()}}),G.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),u}},G.prototype.push=function(h){if(void 0===h)return this.size();var u=this._tail;return this._list[u]=h,this._tail=u+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&h<=u>>>2&&this._shrinkArray(),g}},G.prototype.removeOne=function(h){var u=h;if(u===(0|u)&&this._head!==this._tail){var g=this.size(),b=this._list.length;if(!(u>=g||u<-g)){u<0&&(u+=g);var v,w=this._list[u=this._head+u&this._capacityMask];if(h0;v--)this._list[u]=this._list[u=u-1+b&this._capacityMask];this._list[u]=void 0,this._head=this._head+1+b&this._capacityMask}else{for(v=g-1-h;v>0;v--)this._list[u]=this._list[u=u+1+b&this._capacityMask];this._list[u]=void 0,this._tail=this._tail-1+b&this._capacityMask}return w}}},G.prototype.remove=function(h,u){var b,g=h,w=u;if(g===(0|g)&&this._head!==this._tail){var v=this.size(),l=this._list.length;if(!(g>=v||g<-v||u<1)){if(g<0&&(g+=v),1===u||!u)return(b=new Array(1))[0]=this.removeOne(g),b;if(0===g&&g+u>=v)return b=this.toArray(),this.clear(),b;var p;for(g+u>v&&(u=v-g),b=new Array(u),p=0;p0;p--)this._list[g=g+1+l&this._capacityMask]=void 0;return b}if(0===h){for(this._head=this._head+u+l&this._capacityMask,p=u-1;p>0;p--)this._list[g=g+1+l&this._capacityMask]=void 0;return b}if(g0;p--)this.unshift(this._list[g=g-1+l&this._capacityMask]);for(g=this._head-1+l&this._capacityMask;w>0;)this._list[g=g-1+l&this._capacityMask]=void 0,w--;h<0&&(this._tail=g)}else{for(this._tail=g,g=g+u+l&this._capacityMask,p=v-(u+h);p>0;p--)this.push(this._list[g++]);for(g=this._tail;w>0;)this._list[g=g+1+l&this._capacityMask]=void 0,w--}return this._head<2&&this._tail>1e4&&this._tail<=l>>>2&&this._shrinkArray(),b}}},G.prototype.splice=function(h,u){var g=h;if(g===(0|g)){var b=this.size();if(g<0&&(g+=b),!(g>b)){if(arguments.length>2){var w,v,l,p=arguments.length,d=this._list.length,_=2;if(!b||g0&&(this._head=this._head+g+d&this._capacityMask)):(l=this.remove(g,u),this._head=this._head+g+d&this._capacityMask);p>_;)this.unshift(arguments[--p]);for(w=g;w>0;w--)this.unshift(v[w-1])}else{var I=(v=new Array(b-(g+u))).length;for(w=0;wthis._tail){for(w=this._head;w>>=1,this._capacityMask>>>=1},J.exports=G},2535:J=>{"use strict";function G(h,u){for(const g in u)Object.defineProperty(h,g,{value:u[g],enumerable:!0,configurable:!0});return h}J.exports=function N(h,u,g){if(!h||"string"==typeof h)throw new TypeError("Please pass an Error to err-code");g||(g={}),"object"==typeof u&&(g=u,u=""),u&&(g.code=u);try{return G(h,g)}catch{g.message=h.message,g.stack=h.stack;const w=function(){};return w.prototype=Object.create(Object.getPrototypeOf(h)),G(new w,g)}}},3676:(J,G,N)=>{"use strict";const u=N(649);G.zN=u.EventIterator},649:(J,G)=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});class N{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(g){if(this.isStopped)return;const b={value:g,done:!1};if(this.pullQueue.length){const w=this.pullQueue.shift();w&&w.resolve(b)}else this.pushQueue.push(Promise.resolve(b)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const g of this.pullQueue)g.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(g){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const b of this.pullQueue)b.reject(g);this.pullQueue.length=0}else{const b=Promise.reject(g);b.catch(()=>{}),this.pushQueue.push(b)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:g=>{const b=this.pushQueue.shift();return b?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),b):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((w,v)=>{this.pullQueue.push({resolve:w,reject:v})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class h{constructor(g,{highWaterMark:b=100,lowWaterMark:w=1}={}){const v=new N;v.highWaterMark=b,v.lowWaterMark=w,v.removeCallback=g({push:l=>v.push(l),stop:()=>v.stop(),fail:l=>v.fail(l),on:(l,p)=>{v.eventHandlers[l]=p}})||(()=>{}),this[Symbol.asyncIterator]=()=>v[Symbol.asyncIterator](),Object.freeze(this)}}G.EventIterator=h,G.default=h},2005:J=>{"use strict";var G=Object.prototype.hasOwnProperty,N="~";function h(){}function u(v,l,p){this.fn=v,this.context=l,this.once=p||!1}function g(v,l,p,d,_){if("function"!=typeof p)throw new TypeError("The listener must be a function");var I=new u(p,d||v,_),E=N?N+l:l;return v._events[E]?v._events[E].fn?v._events[E]=[v._events[E],I]:v._events[E].push(I):(v._events[E]=I,v._eventsCount++),v}function b(v,l){0==--v._eventsCount?v._events=new h:delete v._events[l]}function w(){this._events=new h,this._eventsCount=0}Object.create&&(h.prototype=Object.create(null),(new h).__proto__||(N=!1)),w.prototype.eventNames=function(){var p,d,l=[];if(0===this._eventsCount)return l;for(d in p=this._events)G.call(p,d)&&l.push(N?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(p)):l},w.prototype.listeners=function(l){var d=this._events[N?N+l:l];if(!d)return[];if(d.fn)return[d.fn];for(var _=0,I=d.length,E=new Array(I);_{"use strict";var h,G="object"==typeof Reflect?Reflect:null,N=G&&"function"==typeof G.apply?G.apply:function(M,B,F){return Function.prototype.apply.call(M,B,F)};h=G&&"function"==typeof G.ownKeys?G.ownKeys:Object.getOwnPropertySymbols?function(M){return Object.getOwnPropertyNames(M).concat(Object.getOwnPropertySymbols(M))}:function(M){return Object.getOwnPropertyNames(M)};var g=Number.isNaN||function(M){return M!=M};function b(){b.init.call(this)}J.exports=b,J.exports.once=function A(x,M){return new Promise(function(B,F){function z(O){x.removeListener(M,S),F(O)}function S(){"function"==typeof x.removeListener&&x.removeListener("error",z),B([].slice.call(arguments))}D(x,M,S,{once:!0}),"error"!==M&&function P(x,M,B){"function"==typeof x.on&&D(x,"error",M,B)}(x,z,{once:!0})})},b.EventEmitter=b,b.prototype._events=void 0,b.prototype._eventsCount=0,b.prototype._maxListeners=void 0;var w=10;function v(x){if("function"!=typeof x)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof x)}function l(x){return void 0===x._maxListeners?b.defaultMaxListeners:x._maxListeners}function p(x,M,B,F){var z,S,O;if(v(B),void 0===(S=x._events)?(S=x._events=Object.create(null),x._eventsCount=0):(void 0!==S.newListener&&(x.emit("newListener",M,B.listener?B.listener:B),S=x._events),O=S[M]),void 0===O)O=S[M]=B,++x._eventsCount;else if("function"==typeof O?O=S[M]=F?[B,O]:[O,B]:F?O.unshift(B):O.push(B),(z=l(x))>0&&O.length>z&&!O.warned){O.warned=!0;var H=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(M)+" listeners added. Use emitter.setMaxListeners() to increase limit");H.name="MaxListenersExceededWarning",H.emitter=x,H.type=M,H.count=O.length,function u(x){console&&console.warn&&console.warn(x)}(H)}return x}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _(x,M,B){var F={fired:!1,wrapFn:void 0,target:x,type:M,listener:B},z=d.bind(F);return z.listener=B,F.wrapFn=z,z}function I(x,M,B){var F=x._events;if(void 0===F)return[];var z=F[M];return void 0===z?[]:"function"==typeof z?B?[z.listener||z]:[z]:B?function C(x){for(var M=new Array(x.length),B=0;B0&&(O=B[0]),O instanceof Error)throw O;var H=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw H.context=O,H}var L=S[M];if(void 0===L)return!1;if("function"==typeof L)N(L,this,B);else{var j=L.length,re=y(L,j);for(F=0;F=0;O--)if(F[O]===B||F[O].listener===B){H=F[O].listener,S=O;break}if(S<0)return this;0===S?F.shift():function f(x,M){for(;M+1=0;z--)this.removeListener(M,B[z]);return this},b.prototype.listeners=function(M){return I(this,M,!0)},b.prototype.rawListeners=function(M){return I(this,M,!1)},b.listenerCount=function(x,M){return"function"==typeof x.listenerCount?x.listenerCount(M):E.call(x,M)},b.prototype.listenerCount=E,b.prototype.eventNames=function(){return this._eventsCount>0?h(this._events):[]}},3111:J=>{J.exports=class{constructor(N){if(!(N>0)||0!=(N-1&N))throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(N),this.mask=N-1,this.top=0,this.btm=0,this.next=null}push(N){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=N,this.top=this.top+1&this.mask,!0)}shift(){const N=this.buffer[this.btm];if(void 0!==N)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,N}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}}},1159:(J,G,N)=>{const h=N(3111);J.exports=class{constructor(g){this.hwm=g||16,this.head=new h(this.hwm),this.tail=this.head}push(g){this.head.push(g)||(this.head=this.head.next=new h(2*this.head.buffer.length),this.head.push(g))}shift(){const g=this.tail.shift();if(void 0===g&&this.tail.next){const b=this.tail.next;return this.tail.next=null,this.tail=b,this.tail.shift()}return g}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}},5550:J=>{J.exports=function(G){if(!G)throw Error("hashlru must have a max value, of type number, greater than 0");var N=0,h=Object.create(null),u=Object.create(null);function g(b,w){h[b]=w,++N>=G&&(N=0,u=h,h=Object.create(null))}return{has:function(b){return void 0!==h[b]||void 0!==u[b]},remove:function(b){void 0!==h[b]&&(h[b]=void 0),void 0!==u[b]&&(u[b]=void 0)},get:function(b){var w=h[b];return void 0!==w?w:void 0!==(w=u[b])?(g(b,w),w):void 0},set:function(b,w){void 0!==h[b]?h[b]=w:g(b,w)},clear:function(){h=Object.create(null),u=Object.create(null)}}}},4066:J=>{"use strict";const G="[a-fA-F\\d:]",N=p=>p&&p.includeBoundaries?`(?:(?<=\\s|^)(?=${G})|(?<=${G})(?=\\s|$))`:"",h="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",u="[a-fA-F\\d]{1,4}",g=`\n(?:\n(?:${u}:){7}(?:${u}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${u}:){6}(?:${h}|:${u}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${u}:){5}(?::${h}|(?::${u}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${u}:){4}(?:(?::${u}){0,1}:${h}|(?::${u}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${u}:){3}(?:(?::${u}){0,2}:${h}|(?::${u}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${u}:){2}(?:(?::${u}){0,3}:${h}|(?::${u}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${u}:){1}(?:(?::${u}){0,4}:${h}|(?::${u}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${u}){0,5}:${h}|(?::${u}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),b=new RegExp(`(?:^${h}$)|(?:^${g}$)`),w=new RegExp(`^${h}$`),v=new RegExp(`^${g}$`),l=p=>p&&p.exact?b:new RegExp(`(?:${N(p)}${h}${N(p)})|(?:${N(p)}${g}${N(p)})`,"g");l.v4=p=>p&&p.exact?w:new RegExp(`${N(p)}${h}${N(p)}`,"g"),l.v6=p=>p&&p.exact?v:new RegExp(`${N(p)}${g}${N(p)}`,"g"),J.exports=l},1396:function(J){!function(G){"use strict";const N="(0?\\d+|0x[a-f0-9]+)",h={fourOctet:new RegExp(`^${N}\\.${N}\\.${N}\\.${N}$`,"i"),threeOctet:new RegExp(`^${N}\\.${N}\\.${N}$`,"i"),twoOctet:new RegExp(`^${N}\\.${N}$`,"i"),longValue:new RegExp(`^${N}$`,"i")},u=new RegExp("^0[0-7]+$","i"),g=new RegExp("^0x[a-f0-9]+$","i"),b="%[0-9a-z]{1,}",w="(?:[0-9a-f]+::?)+",v={zoneIndex:new RegExp(b,"i"),native:new RegExp(`^(::)?(${w})?([0-9a-f]+)?(::)?(${b})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${N}\\.${N}\\.${N}\\.${N}(${b})?)$`,"i"),transitional:new RegExp(`^((?:${w})|(?:::)(?:${w})?)${N}\\.${N}\\.${N}\\.${N}(${b})?$`,"i")};function l(E,y){if(E.indexOf("::")!==E.lastIndexOf("::"))return null;let P,D,f=0,C=-1,A=(E.match(v.zoneIndex)||[])[0];for(A&&(A=A.substring(1),E=E.replace(/%.+$/,""));(C=E.indexOf(":",C+1))>=0;)f++;if("::"===E.substr(0,2)&&f--,"::"===E.substr(-2,2)&&f--,f>y)return null;for(D=y-f,P=":";D--;)P+="0:";return":"===(E=E.replace("::",P))[0]&&(E=E.slice(1)),":"===E[E.length-1]&&(E=E.slice(0,-1)),{parts:y=function(){const x=E.split(":"),M=[];for(let B=0;B0;){if(P=f-C,P<0&&(P=0),E[A]>>P!=y[A]>>P)return!1;C-=f,A+=1}return!0}function d(E){if(g.test(E))return parseInt(E,16);if("0"===E[0]&&!isNaN(parseInt(E[1],10))){if(u.test(E))return parseInt(E,8);throw new Error(`ipaddr: cannot parse ${E} as octal`)}return parseInt(E,10)}function _(E,y){for(;E.length=0;A-=1){if(P=this.octets[A],!(P in C))return null;if(D=C[P],f&&0!==D)return null;8!==D&&(f=!0),y+=D}return 32-y},E.prototype.range=function(){return I.subnetMatch(this,this.SpecialRanges)},E.prototype.toByteArray=function(){return this.octets.slice(0)},E.prototype.toIPv4MappedAddress=function(){return I.IPv6.parse(`::ffff:${this.toString()}`)},E.prototype.toNormalizedString=function(){return this.toString()},E.prototype.toString=function(){return this.octets.join(".")},E}(),I.IPv4.broadcastAddressFromCIDR=function(E){try{const y=this.parseCIDR(E),f=y[0].toByteArray(),C=this.subnetMaskFromPrefixLength(y[1]).toByteArray(),A=[];let P=0;for(;P<4;)A.push(parseInt(f[P],10)|255^parseInt(C[P],10)),P++;return new this(A)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},I.IPv4.isIPv4=function(E){return null!==this.parser(E)},I.IPv4.isValid=function(E){try{return new this(this.parser(E)),!0}catch{return!1}},I.IPv4.isValidFourPartDecimal=function(E){return!(!I.IPv4.isValid(E)||!E.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},I.IPv4.networkAddressFromCIDR=function(E){let y,f,C,A,P;try{for(y=this.parseCIDR(E),C=y[0].toByteArray(),P=this.subnetMaskFromPrefixLength(y[1]).toByteArray(),A=[],f=0;f<4;)A.push(parseInt(C[f],10)&parseInt(P[f],10)),f++;return new this(A)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},I.IPv4.parse=function(E){const y=this.parser(E);if(null===y)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(y)},I.IPv4.parseCIDR=function(E){let y;if(y=E.match(/^(.+)\/(\d+)$/)){const f=parseInt(y[2]);if(f>=0&&f<=32){const C=[this.parse(y[1]),f];return Object.defineProperty(C,"toString",{value:function(){return this.join("/")}}),C}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},I.IPv4.parser=function(E){let y,f,C;if(y=E.match(h.fourOctet))return function(){const A=y.slice(1,6),P=[];for(let D=0;D4294967295||C<0)throw new Error("ipaddr: address outside defined range");return function(){const A=[];let P;for(P=0;P<=24;P+=8)A.push(C>>P&255);return A}().reverse()}return(y=E.match(h.twoOctet))?function(){const A=y.slice(1,4),P=[];if(C=d(A[1]),C>16777215||C<0)throw new Error("ipaddr: address outside defined range");return P.push(d(A[0])),P.push(C>>16&255),P.push(C>>8&255),P.push(255&C),P}():(y=E.match(h.threeOctet))?function(){const A=y.slice(1,5),P=[];if(C=d(A[2]),C>65535||C<0)throw new Error("ipaddr: address outside defined range");return P.push(d(A[0])),P.push(d(A[1])),P.push(C>>8&255),P.push(255&C),P}():null},I.IPv4.subnetMaskFromPrefixLength=function(E){if((E=parseInt(E))<0||E>32)throw new Error("ipaddr: invalid IPv4 prefix length");const y=[0,0,0,0];let f=0;const C=Math.floor(E/8);for(;f=0;D-=1){if(A=this.parts[D],!(A in C))return null;if(P=C[A],f&&0!==P)return null;16!==P&&(f=!0),y+=P}return 128-y},E.prototype.range=function(){return I.subnetMatch(this,this.SpecialRanges)},E.prototype.toByteArray=function(){let y;const f=[],C=this.parts;for(let A=0;A>8),f.push(255&y);return f},E.prototype.toFixedLengthString=function(){const y=function(){const C=[];for(let A=0;A>8,255&f,C>>8,255&C])},E.prototype.toNormalizedString=function(){const y=function(){const C=[];for(let A=0;AA&&(C=P.index,A=P[0].length);return A<0?f:`${f.substring(0,C)}::${f.substring(C+A)}`},E.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},E}(),I.IPv6.broadcastAddressFromCIDR=function(E){try{const y=this.parseCIDR(E),f=y[0].toByteArray(),C=this.subnetMaskFromPrefixLength(y[1]).toByteArray(),A=[];let P=0;for(;P<16;)A.push(parseInt(f[P],10)|255^parseInt(C[P],10)),P++;return new this(A)}catch(y){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${y})`)}},I.IPv6.isIPv6=function(E){return null!==this.parser(E)},I.IPv6.isValid=function(E){if("string"==typeof E&&-1===E.indexOf(":"))return!1;try{const y=this.parser(E);return new this(y.parts,y.zoneId),!0}catch{return!1}},I.IPv6.networkAddressFromCIDR=function(E){let y,f,C,A,P;try{for(y=this.parseCIDR(E),C=y[0].toByteArray(),P=this.subnetMaskFromPrefixLength(y[1]).toByteArray(),A=[],f=0;f<16;)A.push(parseInt(C[f],10)&parseInt(P[f],10)),f++;return new this(A)}catch(D){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${D})`)}},I.IPv6.parse=function(E){const y=this.parser(E);if(null===y.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(y.parts,y.zoneId)},I.IPv6.parseCIDR=function(E){let y,f,C;if((f=E.match(/^(.+)\/(\d+)$/))&&(y=parseInt(f[2]),y>=0&&y<=128))return C=[this.parse(f[1]),y],Object.defineProperty(C,"toString",{value:function(){return this.join("/")}}),C;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},I.IPv6.parser=function(E){let y,f,C,A,P,D;if(C=E.match(v.deprecatedTransitional))return this.parser(`::ffff:${C[1]}`);if(v.native.test(E))return l(E,8);if((C=E.match(v.transitional))&&(D=C[6]||"",y=l(C[1].slice(0,-1)+D,6),y.parts)){for(P=[parseInt(C[2]),parseInt(C[3]),parseInt(C[4]),parseInt(C[5])],f=0;f128)throw new Error("ipaddr: invalid IPv6 prefix length");const y=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let f=0;const C=Math.floor(E/8);for(;f{J.exports=function G(){return typeof window<"u"&&"object"==typeof window.process&&"renderer"===window.process.type||typeof process<"u"&&"object"==typeof process.versions&&!!process.versions.electron||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0}},6599:(J,G,N)=>{"use strict";const h=N(4066),u=g=>h({exact:!0}).test(g);u.v4=g=>h.v4({exact:!0}).test(g),u.v6=g=>h.v6({exact:!0}).test(g),u.version=g=>u(g)?u.v4(g)?4:6:void 0,J.exports=u},7494:J=>{"use strict";J.exports=G=>{if("[object Object]"!==Object.prototype.toString.call(G))return!1;const N=Object.getPrototypeOf(G);return null===N||N===Object.prototype}},8596:(J,G,N)=>{"use strict";const{URLWithLegacySupport:h,format:u,URLSearchParams:g,defaultBase:b}=N(5695),w=N(340);J.exports={URL:h,URLSearchParams:g,format:u,relative:w,defaultBase:b}},340:(J,G,N)=>{"use strict";const{URLWithLegacySupport:h,format:u}=N(5695);J.exports=(g,b={},w={},v)=>{let p,l=b.protocol?b.protocol.replace(":",""):"http";l=(w[l]||v||l)+":";try{p=new h(g)}catch{p={}}const d=Object.assign({},b,{protocol:l||p.protocol,host:b.host||p.host});return new h(g,u(d)).toString()}},5695:J=>{"use strict";const G=typeof navigator<"u"&&"ReactNative"===navigator.product,h=self.URL,u=function N(){return G?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:""}();J.exports={URLWithLegacySupport:class g{constructor(v="",l=u){this.super=new h(v,l),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(v){this.super.hash=v}set host(v){this.super.host=v}set hostname(v){this.super.hostname=v}set href(v){this.super.href=v}set password(v){this.super.password=v}set pathname(v){this.super.pathname=v}set port(v){this.super.port=v}set protocol(v){this.super.protocol=v}set search(v){this.super.search=v}set username(v){this.super.username=v}static createObjectURL(v){return h.createObjectURL(v)}static revokeObjectURL(v){h.revokeObjectURL(v)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}},URLSearchParams:self.URLSearchParams,defaultBase:u,format:function b(w){if("string"==typeof w)return new h(w).toString();if(!(w instanceof h)){const l=w.auth?w.auth+"@":"",p=w.port?":"+w.port:"",I=w.hostname||"",E=w.search||(w.query?"?"+w.query:""),f=w.pathname||"";return`${w.protocol?w.protocol+"//":""}${(w.username&&w.password?`${w.username}:${w.password}@`:"")||l}${w.host||I+p}${w.path||f+E}${w.hash||""}`}}}},5357:(J,G,N)=>{"use strict";var h=N(7156).default,u=N(8237).default;J.exports=function(){var b=h(function*(w){const v=[];var d,l=!1,p=!1;try{for(var I,_=u(w);l=!(I=yield _.next()).done;l=!1)v.push(I.value)}catch(E){p=!0,d=E}finally{try{l&&null!=_.return&&(yield _.return())}finally{if(p)throw d}}return v});return function(v){return b.apply(this,arguments)}}()},7414:(J,G,N)=>{"use strict";var h=N(7156).default,u=N(8237).default;J.exports=function(){var b=h(function*(w){var p,v=!1,l=!1;try{for(var d=u(w);v=!(yield d.next()).done;v=!1);}catch(I){l=!0,p=I}finally{try{v&&null!=d.return&&(yield d.return())}finally{if(l)throw p}}});return function(v){return b.apply(this,arguments)}}()},6225:(J,G,N)=>{"use strict";var h=N(6737).default,u=N(8186).default,g=N(8237).default;J.exports=function(){var w=u(function*(v,l){var _,p=!1,d=!1;try{for(var E,I=g(v);p=!(E=yield h(I.next())).done;p=!1){const y=E.value;(yield h(l(y)))&&(yield y)}}catch(y){d=!0,_=y}finally{try{p&&null!=I.return&&(yield h(I.return()))}finally{if(d)throw _}}});return function(l,p){return w.apply(this,arguments)}}()},4943:(J,G,N)=>{"use strict";var h=N(7156).default,u=N(8237).default;J.exports=function(){var b=h(function*(w){var p,v=!1,l=!1;try{for(var _,d=u(w);v=!(_=yield d.next()).done;v=!1)return _.value}catch(I){l=!0,p=I}finally{try{v&&null!=d.return&&(yield d.return())}finally{if(l)throw p}}});return function(v){return b.apply(this,arguments)}}()},1349:(J,G,N)=>{"use strict";var h=N(6737).default,u=N(8186).default,g=N(8237).default;J.exports=function(){var w=u(function*(v,l){var _,p=!1,d=!1;try{for(var E,I=g(v);p=!(E=yield h(I.next())).done;p=!1){const y=E.value;yield h(l(y)),yield y}}catch(y){d=!0,_=y}finally{try{p&&null!=I.return&&(yield h(I.return()))}finally{if(d)throw _}}});return function(l,p){return w.apply(this,arguments)}}()},6930:(J,G,N)=>{"use strict";var h=N(6737).default,u=N(8186).default,g=N(8237).default;J.exports=function(){var w=u(function*(v,l){var _,p=!1,d=!1;try{for(var E,I=g(v);p=!(E=yield h(I.next())).done;p=!1){const y=E.value;yield l(y)}}catch(y){d=!0,_=y}finally{try{p&&null!=I.return&&(yield h(I.return()))}finally{if(d)throw _}}});return function(l,p){return w.apply(this,arguments)}}()},5061:(J,G,N)=>{"use strict";var h=N(7156).default,u=N(8186).default,g=N(6737).default,b=N(8237).default,w=N(8131).default;const v=N(6343);J.exports=function(){var p=u(function*(...d){const _=v();setTimeout(h(function*(){try{yield Promise.all(d.map(function(){var I=h(function*(E){var C,y=!1,f=!1;try{for(var P,A=b(E);y=!(P=yield A.next()).done;y=!1)_.push(P.value)}catch(D){f=!0,C=D}finally{try{y&&null!=A.return&&(yield A.return())}finally{if(f)throw C}}});return function(E){return I.apply(this,arguments)}}())),_.end()}catch(I){_.end(I)}}),0),yield*w(b(_),g)});return function(){return p.apply(this,arguments)}}()},6343:(J,G,N)=>{const h=N(1159);J.exports=u=>{let g;"function"==typeof(u=u||{})?(g=u,u={}):g=u.onEnd;let w,v,l,b=new h;const d=A=>v?v(A):(b.push(A),w),I=A=>l?w:d({done:!1,value:A}),E=A=>l?w:(l=!0,A?(A=>(b=new h,v?v({error:A}):(b.push({error:A}),w)))(A):d({done:!0}));if(w={[Symbol.asyncIterator](){return this},next:()=>{if(!b.isEmpty()){if(u.writev){let P;const D=[];for(;!b.isEmpty();){if(P=b.shift(),P.error)throw P.error;D.push(P.value)}return{done:P.done,value:D}}const A=b.shift();if(A.error)throw A.error;return A}return l?{done:!0}:new Promise((A,P)=>{v=D=>(v=null,D.error?P(D.error):A(u.writev&&!D.done?{done:D.done,value:[D.value]}:D),w)})},return:()=>(b=new h,E(),{done:!0}),throw:A=>(E(A),{done:!0}),push:I,end:E},!g)return w;const C=w;return w={[Symbol.asyncIterator](){return this},next:()=>C.next(),throw:A=>(C.throw(A),g&&(g(A),g=null),{done:!0}),return:()=>(C.return(),g&&(g(),g=null),{done:!0}),push:I,end:A=>(C.end(A),g&&(g(A),g=null),w)},w}},4297:(J,G,N)=>{"use strict";var h=N(8186).default,u=N(6737).default,g=N(8237).default,b=N(8131).default;const w=N(5357);J.exports=function(){var l=h(function*(p,d){const _=yield u(w(p));yield*b(g(_.sort(d)),u)});return function(d,_){return l.apply(this,arguments)}}()},0:(J,G,N)=>{"use strict";var h=N(6737).default,u=N(8186).default,g=N(8237).default;J.exports=function(){var w=u(function*(v,l){let p=0;if(!(l<1)){var I,d=!1,_=!1;try{for(var y,E=g(v);d=!(y=yield h(E.next())).done;d=!1)if(yield y.value,p++,p===l)return}catch(f){_=!0,I=f}finally{try{d&&null!=E.return&&(yield h(E.return()))}finally{if(_)throw I}}}});return function(l,p){return w.apply(this,arguments)}}()},4237:(J,G,N)=>{var h;!function(){"use strict";var u="input is invalid type",b="object"==typeof window,w=b?window:{};w.JS_SHA3_NO_WINDOW&&(b=!1);var v=!b&&"object"==typeof self;!w.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?w=global:v&&(w=self);var p=!w.JS_SHA3_NO_COMMON_JS&&J.exports,d=N.amdO,_=!w.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",I="0123456789abcdef".split(""),y=[4,1024,262144,67108864],A=[0,8,16,24],P=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],D=[224,256,384,512],x=[128,256],M=["hex","buffer","arrayBuffer","array","digest"],B={128:168,256:136};(w.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(K){return"[object Array]"===Object.prototype.toString.call(K)}),_&&(w.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(K){return"object"==typeof K&&K.buffer&&K.buffer.constructor===ArrayBuffer});for(var F=function(K,Ee,Ce){return function(xe){return new Pe(K,Ee,K).update(xe)[Ce]()}},z=function(K,Ee,Ce){return function(xe,Ke){return new Pe(K,Ee,Ke).update(xe)[Ce]()}},S=function(K,Ee,Ce){return function(xe,Ke,We,Je){return Z["cshake"+K].update(xe,Ke,We,Je)[Ce]()}},O=function(K,Ee,Ce){return function(xe,Ke,We,Je){return Z["kmac"+K].update(xe,Ke,We,Je)[Ce]()}},H=function(K,Ee,Ce,xe){for(var Ke=0;Ke>5,this.byteCount=this.blockCount<<2,this.outputBlocks=Ce>>5,this.extraBytes=(31&Ce)>>3;for(var xe=0;xe<50;++xe)this.s[xe]=0}function we(K,Ee,Ce){Pe.call(this,K,Ee,Ce)}Pe.prototype.update=function(K){if(this.finalized)throw new Error("finalize already called");var Ee,Ce=typeof K;if("string"!==Ce){if("object"!==Ce)throw new Error(u);if(null===K)throw new Error(u);if(_&&K.constructor===ArrayBuffer)K=new Uint8Array(K);else if(!(Array.isArray(K)||_&&ArrayBuffer.isView(K)))throw new Error(u);Ee=!0}for(var pt,Dt,xe=this.blocks,Ke=this.byteCount,We=K.length,Je=this.blockCount,Xe=0,Ot=this.s;Xe>2]|=K[Xe]<>2]|=Dt<>2]|=(192|Dt>>6)<>2]|=(128|63&Dt)<=57344?(xe[pt>>2]|=(224|Dt>>12)<>2]|=(128|Dt>>6&63)<>2]|=(128|63&Dt)<>2]|=(240|Dt>>18)<>2]|=(128|Dt>>12&63)<>2]|=(128|Dt>>6&63)<>2]|=(128|63&Dt)<=Ke){for(this.start=pt-Ke,this.block=xe[Je],pt=0;pt>=8);Ce>0;)Ke.unshift(Ce),Ce=255&(K>>=8),++xe;return Ee?Ke.push(xe):Ke.unshift(xe),this.update(Ke),Ke.length},Pe.prototype.encodeString=function(K){var Ee,Ce=typeof K;if("string"!==Ce){if("object"!==Ce)throw new Error(u);if(null===K)throw new Error(u);if(_&&K.constructor===ArrayBuffer)K=new Uint8Array(K);else if(!(Array.isArray(K)||_&&ArrayBuffer.isView(K)))throw new Error(u);Ee=!0}var xe=0;if(Ee)xe=K.length;else for(var We=0;We=57344?xe+=3:(Je=65536+((1023&Je)<<10|1023&K.charCodeAt(++We)),xe+=4)}return xe+=this.encode(8*xe),this.update(K),xe},Pe.prototype.bytepad=function(K,Ee){for(var Ce=this.encode(Ee),xe=0;xe>2]|=this.padding[3&Ee],this.lastByteIndex===this.byteCount)for(K[0]=K[Ce],Ee=1;Ee>4&15]+I[15&Xe]+I[Xe>>12&15]+I[Xe>>8&15]+I[Xe>>20&15]+I[Xe>>16&15]+I[Xe>>28&15]+I[Xe>>24&15];We%K==0&&($e(Ee),Ke=0)}return xe&&(Je+=I[(Xe=Ee[Ke])>>4&15]+I[15&Xe],xe>1&&(Je+=I[Xe>>12&15]+I[Xe>>8&15]),xe>2&&(Je+=I[Xe>>20&15]+I[Xe>>16&15])),Je},Pe.prototype.buffer=Pe.prototype.arrayBuffer=function(){this.finalize();var Xe,K=this.blockCount,Ee=this.s,Ce=this.outputBlocks,xe=this.extraBytes,Ke=0,We=0,Je=this.outputBits>>3;Xe=xe?new ArrayBuffer(Ce+1<<2):new ArrayBuffer(Je);for(var Ot=new Uint32Array(Xe);We>8&255,Je[Xe+2]=Ot>>16&255,Je[Xe+3]=Ot>>24&255;We%K==0&&$e(Ee)}return xe&&(Je[Xe=We<<2]=255&(Ot=Ee[Ke]),xe>1&&(Je[Xe+1]=Ot>>8&255),xe>2&&(Je[Xe+2]=Ot>>16&255)),Je},(we.prototype=new Pe).finalize=function(){return this.encode(this.outputBits,!0),Pe.prototype.finalize.call(this)};var $e=function(K){var Ee,Ce,xe,Ke,We,Je,Xe,Ot,pt,Dt,Wr,Sr,ni,ie,fe,ye,me,_e,Ne,Ye,qe,st,nt,je,be,ge,De,Ue,Be,dt,Pt,vt,et,Pn,Bt,yn,tn,ft,hn,ot,Kt,bt,lr,Hr,Fn,bn,vr,rr,_n,Ft,ut,ce,ve,yt,St,mn,Ge,Qe,Te,ze,ht,Et,lt;for(xe=0;xe<48;xe+=2)Ke=K[0]^K[10]^K[20]^K[30]^K[40],We=K[1]^K[11]^K[21]^K[31]^K[41],Ot=K[4]^K[14]^K[24]^K[34]^K[44],pt=K[5]^K[15]^K[25]^K[35]^K[45],Dt=K[6]^K[16]^K[26]^K[36]^K[46],Wr=K[7]^K[17]^K[27]^K[37]^K[47],Ce=(ni=K[9]^K[19]^K[29]^K[39]^K[49])^((Xe=K[3]^K[13]^K[23]^K[33]^K[43])<<1|(Je=K[2]^K[12]^K[22]^K[32]^K[42])>>>31),K[0]^=Ee=(Sr=K[8]^K[18]^K[28]^K[38]^K[48])^(Je<<1|Xe>>>31),K[1]^=Ce,K[10]^=Ee,K[11]^=Ce,K[20]^=Ee,K[21]^=Ce,K[30]^=Ee,K[31]^=Ce,K[40]^=Ee,K[41]^=Ce,Ce=We^(pt<<1|Ot>>>31),K[2]^=Ee=Ke^(Ot<<1|pt>>>31),K[3]^=Ce,K[12]^=Ee,K[13]^=Ce,K[22]^=Ee,K[23]^=Ce,K[32]^=Ee,K[33]^=Ce,K[42]^=Ee,K[43]^=Ce,Ce=Xe^(Wr<<1|Dt>>>31),K[4]^=Ee=Je^(Dt<<1|Wr>>>31),K[5]^=Ce,K[14]^=Ee,K[15]^=Ce,K[24]^=Ee,K[25]^=Ce,K[34]^=Ee,K[35]^=Ce,K[44]^=Ee,K[45]^=Ce,Ce=pt^(ni<<1|Sr>>>31),K[6]^=Ee=Ot^(Sr<<1|ni>>>31),K[7]^=Ce,K[16]^=Ee,K[17]^=Ce,K[26]^=Ee,K[27]^=Ce,K[36]^=Ee,K[37]^=Ce,K[46]^=Ee,K[47]^=Ce,Ce=Wr^(We<<1|Ke>>>31),K[8]^=Ee=Dt^(Ke<<1|We>>>31),K[9]^=Ce,K[18]^=Ee,K[19]^=Ce,K[28]^=Ee,K[29]^=Ce,K[38]^=Ee,K[39]^=Ce,K[48]^=Ee,K[49]^=Ce,fe=K[1],bn=K[11]<<4|K[10]>>>28,vr=K[10]<<4|K[11]>>>28,Ue=K[20]<<3|K[21]>>>29,Be=K[21]<<3|K[20]>>>29,ze=K[31]<<9|K[30]>>>23,ht=K[30]<<9|K[31]>>>23,bt=K[40]<<18|K[41]>>>14,lr=K[41]<<18|K[40]>>>14,Pn=K[2]<<1|K[3]>>>31,Bt=K[3]<<1|K[2]>>>31,me=K[12]<<12|K[13]>>>20,rr=K[22]<<10|K[23]>>>22,_n=K[23]<<10|K[22]>>>22,dt=K[33]<<13|K[32]>>>19,Pt=K[32]<<13|K[33]>>>19,Et=K[42]<<2|K[43]>>>30,lt=K[43]<<2|K[42]>>>30,yt=K[5]<<30|K[4]>>>2,St=K[4]<<30|K[5]>>>2,yn=K[14]<<6|K[15]>>>26,tn=K[15]<<6|K[14]>>>26,Ne=K[24]<<11|K[25]>>>21,Ft=K[34]<<15|K[35]>>>17,ut=K[35]<<15|K[34]>>>17,vt=K[45]<<29|K[44]>>>3,et=K[44]<<29|K[45]>>>3,je=K[6]<<28|K[7]>>>4,be=K[7]<<28|K[6]>>>4,mn=K[17]<<23|K[16]>>>9,Ge=K[16]<<23|K[17]>>>9,ft=K[26]<<25|K[27]>>>7,hn=K[27]<<25|K[26]>>>7,Ye=K[36]<<21|K[37]>>>11,qe=K[37]<<21|K[36]>>>11,ce=K[47]<<24|K[46]>>>8,ve=K[46]<<24|K[47]>>>8,Hr=K[8]<<27|K[9]>>>5,Fn=K[9]<<27|K[8]>>>5,ge=K[18]<<20|K[19]>>>12,De=K[19]<<20|K[18]>>>12,Qe=K[29]<<7|K[28]>>>25,Te=K[28]<<7|K[29]>>>25,ot=K[38]<<8|K[39]>>>24,Kt=K[39]<<8|K[38]>>>24,st=K[48]<<14|K[49]>>>18,nt=K[49]<<14|K[48]>>>18,K[0]=(ie=K[0])^~(ye=K[13]<<12|K[12]>>>20)&(_e=K[25]<<11|K[24]>>>21),K[1]=fe^~me&Ne,K[10]=je^~ge&Ue,K[11]=be^~De&Be,K[20]=Pn^~yn&ft,K[21]=Bt^~tn&hn,K[30]=Hr^~bn&rr,K[31]=Fn^~vr&_n,K[40]=yt^~mn&Qe,K[41]=St^~Ge&Te,K[2]=ye^~_e&Ye,K[3]=me^~Ne&qe,K[12]=ge^~Ue&dt,K[13]=De^~Be&Pt,K[22]=yn^~ft&ot,K[23]=tn^~hn&Kt,K[32]=bn^~rr&Ft,K[33]=vr^~_n&ut,K[42]=mn^~Qe&ze,K[43]=Ge^~Te&ht,K[4]=_e^~Ye&st,K[5]=Ne^~qe&nt,K[14]=Ue^~dt&vt,K[15]=Be^~Pt&et,K[24]=ft^~ot&bt,K[25]=hn^~Kt&lr,K[34]=rr^~Ft&ce,K[35]=_n^~ut&ve,K[44]=Qe^~ze&Et,K[45]=Te^~ht<,K[6]=Ye^~st&ie,K[7]=qe^~nt&fe,K[16]=dt^~vt&je,K[17]=Pt^~et&be,K[26]=ot^~bt&Pn,K[27]=Kt^~lr&Bt,K[36]=Ft^~ce&Hr,K[37]=ut^~ve&Fn,K[46]=ze^~Et&yt,K[47]=ht^~lt&St,K[8]=st^~ie&ye,K[9]=nt^~fe&me,K[18]=vt^~je&ge,K[19]=et^~be&De,K[28]=bt^~Pn&yn,K[29]=lr^~Bt&tn,K[38]=ce^~Hr&bn,K[39]=ve^~Fn&vr,K[48]=Et^~yt&mn,K[49]=lt^~St&Ge,K[0]^=P[xe],K[1]^=P[xe+1]};if(p)J.exports=Z;else{for(ne=0;neObject.defineProperty(f,C,{value:A,writable:!0,enumerable:!0,configurable:!0}),w=this,v={concatArrays:!1,ignoreUndefined:!1},l=f=>{const C=[];for(const A in f)u.call(f,A)&&C.push(A);if(Object.getOwnPropertySymbols){const A=Object.getOwnPropertySymbols(f);for(const P of A)g.call(f,P)&&C.push(P)}return C};function p(f){return Array.isArray(f)?function d(f){const C=f.slice(0,0);return l(f).forEach(A=>{b(C,A,p(f[A]))}),C}(f):h(f)?function _(f){const C=null===Object.getPrototypeOf(f)?Object.create(null):{};return l(f).forEach(A=>{b(C,A,p(f[A]))}),C}(f):f}const I=(f,C,A,P)=>(A.forEach(D=>{typeof C[D]>"u"&&P.ignoreUndefined||(D in f&&f[D]!==Object.getPrototypeOf(f)?b(f,D,y(f[D],C[D],P)):b(f,D,p(C[D])))}),f);function y(f,C,A){return A.concatArrays&&Array.isArray(f)&&Array.isArray(C)?((f,C,A)=>{let P=f.slice(0,0),D=0;return[f,C].forEach(x=>{const M=[];for(let B=0;B!M.includes(B)),A)}),P})(f,C,A):h(C)&&h(f)?I(f,C,l(C),A):p(C)}J.exports=function(...f){const C=y(p(v),this!==w&&this||{},v);let A={_:{}};for(const P of f)if(void 0!==P){if(!h(P))throw new TypeError("`"+P+"` is not an Option Object");A=y(A,{_:P},C)}return A._}},4366:J=>{var G=1e3,N=60*G,h=60*N,u=24*h;function p(d,_,I,E){var y=_>=1.5*I;return Math.round(d/I)+" "+E+(y?"s":"")}J.exports=function(d,_){_=_||{};var I=typeof d;if("string"===I&&d.length>0)return function w(d){if(!((d=String(d)).length>100)){var _=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(_){var I=parseFloat(_[1]);switch((_[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*I;case"weeks":case"week":case"w":return 6048e5*I;case"days":case"day":case"d":return I*u;case"hours":case"hour":case"hrs":case"hr":case"h":return I*h;case"minutes":case"minute":case"mins":case"min":case"m":return I*N;case"seconds":case"second":case"secs":case"sec":case"s":return I*G;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return I;default:return}}}}(d);if("number"===I&&isFinite(d))return _.long?function l(d){var _=Math.abs(d);return _>=u?p(d,_,u,"day"):_>=h?p(d,_,h,"hour"):_>=N?p(d,_,N,"minute"):_>=G?p(d,_,G,"second"):d+" ms"}(d):function v(d){var _=Math.abs(d);return _>=u?Math.round(d/u)+"d":_>=h?Math.round(d/h)+"h":_>=N?Math.round(d/N)+"m":_>=G?Math.round(d/G)+"s":d+"ms"}(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))}},344:J=>{"use strict";function G(N){if(Array.isArray(N)){for(var h=0,u=Array(N.length);h>>24,(p&255<<16)>>>16,(65280&p)>>>8,255&p].join(".")},v=function(p){var d,I,E,y,f;for(d=[],I=E=0;E<=3&&0!==p.length;I=++E){if(I>0){if("."!==p[0])throw new Error("Invalid IP");p=p.substring(1)}y=(f=h(p))[0],p=p.substring(f[1]),d.push(y)}if(0!==p.length)throw new Error("Invalid IP");switch(d.length){case 1:if(d[0]>4294967295)throw new Error("Invalid IP");return d[0]>>>0;case 2:if(d[0]>255||d[1]>16777215)throw new Error("Invalid IP");return(d[0]<<24|d[1])>>>0;case 3:if(d[0]>255||d[1]>255||d[2]>65535)throw new Error("Invalid IP");return(d[0]<<24|d[1]<<16|d[2])>>>0;case 4:if(d[0]>255||d[1]>255||d[2]>255||d[3]>255)throw new Error("Invalid IP");return(d[0]<<24|d[1]<<16|d[2]<<8|d[3])>>>0;default:throw new Error("Invalid IP")}},g=(u=function(p){return p.charCodeAt(0)})("0"),w=u("a"),b=u("A"),h=function(p){var d,_,I,E,y;for(E=0,d=10,_="9",I=0,p.length>1&&"0"===p[I]&&("x"===p[I+1]||"X"===p[I+1]?(I+=2,d=16):"0"<=p[I+1]&&p[I+1]<="9"&&(I++,d=8,_="7")),y=I;I>>0;else{if(16!==d)break;if("a"<=p[I]&&p[I]<="f")E=E*d+(10+u(p[I])-w)>>>0;else{if(!("A"<=p[I]&&p[I]<="F"))break;E=E*d+(10+u(p[I])-b)>>>0}}if(E>4294967295)throw new Error("too large");I++}if(I===y)throw new Error("empty octet");return[E,I]},N=function(){function p(d,_){var E,y,f;if("string"!=typeof d)throw new Error("Missing `net' parameter");if(_||(f=d.split("/",2),d=f[0],_=f[1]),_||(_=32),"string"==typeof _&&_.indexOf(".")>-1){try{this.maskLong=v(_)}catch(C){throw new Error("Invalid mask: "+_)}for(E=y=32;y>=0;E=--y)if(this.maskLong===4294967295<<32-E>>>0){this.bitmask=E;break}}else{if(!_&&0!==_)throw new Error("Invalid mask: empty");this.bitmask=parseInt(_,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(v(d)&this.maskLong)>>>0}catch(C){throw new Error("Invalid net address: "+d)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+_);this.size=Math.pow(2,32-this.bitmask),this.base=l(this.netLong),this.mask=l(this.maskLong),this.hostmask=l(~this.maskLong),this.first=this.bitmask<=30?l(this.netLong+1):this.base,this.last=l(this.bitmask<=30?this.netLong+this.size-2:this.netLong+this.size-1),this.broadcast=this.bitmask<=30?l(this.netLong+this.size-1):void 0}return p.prototype.contains=function(d){return"string"==typeof d&&(d.indexOf("/")>0||4!==d.split(".").length)&&(d=new p(d)),d instanceof p?this.contains(d.base)&&this.contains(d.broadcast||d.last):(v(d)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},p.prototype.next=function(d){return null==d&&(d=1),new p(l(this.netLong+this.size*d),this.mask)},p.prototype.forEach=function(d){var _,I,E;for(E=v(this.first),I=v(this.last),_=0;E<=I;)d(l(E),E,_),_++,E++},p.prototype.toString=function(){return this.base+"/"+this.bitmask},p}(),G.ip2long=v,G.long2ip=l,G.Netmask=N}).call(this)},1298:(J,G,N)=>{var h=N(8659);function u(f,C){h.cipher.registerAlgorithm(f,function(){return new h.aes.Algorithm(f,C)})}N(3311),N(3481),N(4747),J.exports=h.aes=h.aes||{},h.aes.startEncrypting=function(f,C,A,P){var D=y({key:f,output:A,decrypt:!1,mode:P});return D.start(C),D},h.aes.createEncryptionCipher=function(f,C){return y({key:f,output:null,decrypt:!1,mode:C})},h.aes.startDecrypting=function(f,C,A,P){var D=y({key:f,output:A,decrypt:!0,mode:P});return D.start(C),D},h.aes.createDecryptionCipher=function(f,C){return y({key:f,output:null,decrypt:!0,mode:C})},h.aes.Algorithm=function(f,C){g||_();var A=this;A.name=f,A.mode=new C({blockSize:16,cipher:{encrypt:function(P,D){return E(A._w,P,D,!1)},decrypt:function(P,D){return E(A._w,P,D,!0)}}}),A._init=!1},h.aes.Algorithm.prototype.initialize=function(f){if(!this._init){var A,C=f.key;if("string"!=typeof C||16!==C.length&&24!==C.length&&32!==C.length){if(h.util.isArray(C)&&(16===C.length||24===C.length||32===C.length)){A=C,C=h.util.createBuffer();for(var P=0;P>>=2,P=0;P>8^255&B^99,v[B]=A,z=(F=f[B])<<24^B<<16^B<<8^B^F,S=((D=f[A])^(x=f[D])^(M=f[x]))<<24^(A^M)<<16^(A^x^M)<<8^A^D^M;for(var O=0;O<4;++O)p[O][A]=z,d[O][B]=S,z=z<<24|z>>>8,S=S<<24|S>>>8;0===A?A=P=1:(A=D^f[f[f[D^M]]],P^=f[f[P]])}}function I(f,C){for(var P,A=f.slice(0),D=1,x=A.length,B=4*(x+6+1),F=x;F>>16&255]<<24^w[P>>>8&255]<<16^w[255&P]<<8^w[P>>>24]^l[D]<<24,D++):x>6&&F%x==4&&(P=w[P>>>24]<<24^w[P>>>16&255]<<16^w[P>>>8&255]<<8^w[255&P]),A[F]=A[F-x]^P;if(C){for(var z,S=d[0],O=d[1],H=d[2],L=d[3],j=A.slice(0),re=(F=0,(B=A.length)-4);F>>24]]^O[w[z>>>16&255]]^H[w[z>>>8&255]]^L[w[255&z]];A=j}return A}function E(f,C,A,P){var x,M,B,F,z,S,O,H,L,j,re,$,D=f.length/4-1;P?(x=d[0],M=d[1],B=d[2],F=d[3],z=v):(x=p[0],M=p[1],B=p[2],F=p[3],z=w),S=C[0]^f[0],O=C[P?3:1]^f[1],H=C[2]^f[2],L=C[P?1:3]^f[3];for(var te=3,Z=1;Z>>24]^M[O>>>16&255]^B[H>>>8&255]^F[255&L]^f[++te],re=x[O>>>24]^M[H>>>16&255]^B[L>>>8&255]^F[255&S]^f[++te],$=x[H>>>24]^M[L>>>16&255]^B[S>>>8&255]^F[255&O]^f[++te],L=x[L>>>24]^M[S>>>16&255]^B[O>>>8&255]^F[255&H]^f[++te],S=j,O=re,H=$;A[0]=z[S>>>24]<<24^z[O>>>16&255]<<16^z[H>>>8&255]<<8^z[255&L]^f[++te],A[P?3:1]=z[O>>>24]<<24^z[H>>>16&255]<<16^z[L>>>8&255]<<8^z[255&S]^f[++te],A[2]=z[H>>>24]<<24^z[L>>>16&255]<<16^z[S>>>8&255]<<8^z[255&O]^f[++te],A[P?1:3]=z[L>>>24]<<24^z[S>>>16&255]<<16^z[O>>>8&255]<<8^z[255&H]^f[++te]}function y(f){var P,A="AES-"+((f=f||{}).mode||"CBC").toUpperCase(),D=(P=f.decrypt?h.cipher.createDecipher(A,f.key):h.cipher.createCipher(A,f.key)).start;return P.start=function(x,M){var B=null;M instanceof h.util.ByteBuffer&&(B=M,M={}),(M=M||{}).output=B,M.iv=x,D.call(P,M)},P}},7791:(J,G,N)=>{var h=N(8659);N(4747),N(6078);var u=J.exports=h.asn1=h.asn1||{};function g(l,p,d){if(d>p){var _=new Error("Too few bytes to parse DER.");throw _.available=l.length(),_.remaining=p,_.requested=d,_}}function w(l,p,d,_){var I;g(l,p,2);var E=l.getByte();p--;var y=192&E,f=31&E;I=l.length();var C=function(l,p){var d=l.getByte();if(p--,128!==d){var _;if(128&d){var E=127&d;g(l,p,E),_=l.getInt(E<<3)}else _=d;if(_<0)throw new Error("Negative length: "+_);return _}}(l,p);if(p-=I-l.length(),void 0!==C&&C>p){if(_.strict){var A=new Error("Too few bytes to read ASN.1 value.");throw A.available=l.length(),A.remaining=p,A.requested=C,A}C=p}var P,D,x=32==(32&E);if(x)if(P=[],void 0===C)for(;;){if(g(l,p,2),l.bytes(2)===String.fromCharCode(0,0)){l.getBytes(2),p-=2;break}I=l.length(),P.push(w(l,p,d+1,_)),p-=I-l.length()}else for(;C>0;)I=l.length(),P.push(w(l,C,d+1,_)),p-=I-l.length(),C-=I-l.length();if(void 0===P&&y===u.Class.UNIVERSAL&&f===u.Type.BITSTRING&&(D=l.bytes(C)),void 0===P&&_.decodeBitStrings&&y===u.Class.UNIVERSAL&&f===u.Type.BITSTRING&&C>1){var M=l.read,B=p,F=0;if(f===u.Type.BITSTRING&&(g(l,p,1),F=l.getByte(),p--),0===F)try{I=l.length();var S=w(l,p,d+1,{strict:!0,decodeBitStrings:!0}),O=I-l.length();p-=O,f==u.Type.BITSTRING&&O++;var H=S.tagClass;O===C&&(H===u.Class.UNIVERSAL||H===u.Class.CONTEXT_SPECIFIC)&&(P=[S])}catch{}void 0===P&&(l.read=M,p=B)}if(void 0===P){if(void 0===C){if(_.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");C=p}if(f===u.Type.BMPSTRING)for(P="";C>0;C-=2)g(l,p,2),P+=String.fromCharCode(l.getInt16()),p-=2;else P=l.getBytes(C),p-=C}return u.create(y,f,x,P,void 0===D?null:{bitStringContents:D})}u.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},u.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},u.create=function(l,p,d,_,I){if(h.util.isArray(_)){for(var E=[],y=0;y<_.length;++y)void 0!==_[y]&&E.push(_[y]);_=E}var f={tagClass:l,type:p,constructed:d,composed:d||h.util.isArray(_),value:_};return I&&"bitStringContents"in I&&(f.bitStringContents=I.bitStringContents,f.original=u.copy(f)),f},u.copy=function(l,p){var d;if(h.util.isArray(l)){d=[];for(var _=0;_1&&(0===l.value.charCodeAt(0)&&0==(128&l.value.charCodeAt(1))||255===l.value.charCodeAt(0)&&128==(128&l.value.charCodeAt(1)))?_.putBytes(l.value.substr(1)):_.putBytes(l.value);if(p.putByte(d),_.length()<=127)p.putByte(127&_.length());else{var y=_.length(),f="";do{f+=String.fromCharCode(255&y),y>>>=8}while(y>0);for(p.putByte(128|f.length),E=f.length-1;E>=0;--E)p.putByte(f.charCodeAt(E))}return p.putBuffer(_),p},u.oidToDer=function(l){var p=l.split("."),d=h.util.createBuffer();d.putByte(40*parseInt(p[0],10)+parseInt(p[1],10));for(var _,I,E,y,f=2;f>>=7,_||(y|=128),I.push(y),_=!1}while(E>0);for(var C=I.length-1;C>=0;--C)d.putByte(I[C])}return d},u.derToOid=function(l){var p;"string"==typeof l&&(l=h.util.createBuffer(l));var d=l.getByte();p=Math.floor(d/40)+"."+d%40;for(var _=0;l.length()>0;)_<<=7,128&(d=l.getByte())?_+=127&d:(p+="."+(_+d),_=0);return p},u.utcTimeToDate=function(l){var p=new Date,d=parseInt(l.substr(0,2),10);d=d>=50?1900+d:2e3+d;var _=parseInt(l.substr(2,2),10)-1,I=parseInt(l.substr(4,2),10),E=parseInt(l.substr(6,2),10),y=parseInt(l.substr(8,2),10),f=0;if(l.length>11){var C=l.charAt(10),A=10;"+"!==C&&"-"!==C&&(f=parseInt(l.substr(10,2),10),A+=2)}if(p.setUTCFullYear(d,_,I),p.setUTCHours(E,y,f,0),A&&("+"===(C=l.charAt(A))||"-"===C)){var x=60*parseInt(l.substr(A+1,2),10)+parseInt(l.substr(A+4,2),10);x*=6e4,p.setTime("+"===C?+p-x:+p+x)}return p},u.generalizedTimeToDate=function(l){var p=new Date,d=parseInt(l.substr(0,4),10),_=parseInt(l.substr(4,2),10)-1,I=parseInt(l.substr(6,2),10),E=parseInt(l.substr(8,2),10),y=parseInt(l.substr(10,2),10),f=parseInt(l.substr(12,2),10),C=0,A=0,P=!1;"Z"===l.charAt(l.length-1)&&(P=!0);var D=l.length-5,x=l.charAt(D);return"+"!==x&&"-"!==x||(A=60*parseInt(l.substr(D+1,2),10)+parseInt(l.substr(D+4,2),10),A*=6e4,"+"===x&&(A*=-1),P=!0),"."===l.charAt(14)&&(C=1e3*parseFloat(l.substr(14),10)),P?(p.setUTCFullYear(d,_,I),p.setUTCHours(E,y,f,C),p.setTime(+p+A)):(p.setFullYear(d,_,I),p.setHours(E,y,f,C)),p},u.dateToUtcTime=function(l){if("string"==typeof l)return l;var p="",d=[];d.push((""+l.getUTCFullYear()).substr(2)),d.push(""+(l.getUTCMonth()+1)),d.push(""+l.getUTCDate()),d.push(""+l.getUTCHours()),d.push(""+l.getUTCMinutes()),d.push(""+l.getUTCSeconds());for(var _=0;_=-128&&l<128)return p.putSignedInt(l,8);if(l>=-32768&&l<32768)return p.putSignedInt(l,16);if(l>=-8388608&&l<8388608)return p.putSignedInt(l,24);if(l>=-2147483648&&l<2147483648)return p.putSignedInt(l,32);var d=new Error("Integer too large; max is 32-bits.");throw d.integer=l,d},u.derToInteger=function(l){"string"==typeof l&&(l=h.util.createBuffer(l));var p=8*l.length();if(p>32)throw new Error("Integer too large; max is 32-bits.");return l.getSignedInt(p)},u.validate=function(l,p,d,_){var I=!1;if((l.tagClass===p.tagClass||typeof p.tagClass>"u")&&(l.type===p.type||typeof p.type>"u"))if(l.constructed===p.constructed||typeof p.constructed>"u"){if(I=!0,p.value&&h.util.isArray(p.value))for(var E=0,y=0;I&&y0&&(_+="\n");for(var I="",E=0;E1?"0x"+h.util.bytesToHex(l.value.slice(1)):"(none)",l.value.length>0){var A=l.value.charCodeAt(0);1==A?_+=" (1 unused bit shown)":A>1&&(_+=" ("+A+" unused bits shown)")}}else if(l.type===u.Type.OCTETSTRING)v.test(l.value)||(_+="("+l.value+") "),_+="0x"+h.util.bytesToHex(l.value);else if(l.type===u.Type.UTF8)try{_+=h.util.decodeUtf8(l.value)}catch(P){if("URI malformed"!==P.message)throw P;_+="0x"+h.util.bytesToHex(l.value)+" (malformed UTF8)"}else l.type===u.Type.PRINTABLESTRING||l.type===u.Type.IA5String?_+=l.value:v.test(l.value)?_+="0x"+h.util.bytesToHex(l.value):_+=0===l.value.length?"[null]":l.value}return _}},2020:J=>{var G={};J.exports=G;var N={};G.encode=function(u,g,b){if("string"!=typeof g)throw new TypeError('"alphabet" must be a string.');if(void 0!==b&&"number"!=typeof b)throw new TypeError('"maxline" must be a number.');var w="";if(u instanceof Uint8Array){var v=0,l=g.length,p=g.charAt(0),d=[0];for(v=0;v0;)d.push(I%l),I=I/l|0}for(v=0;0===u[v]&&v=0;--v)w+=g[d[v]]}else w=function h(u,g){var b=0,w=g.length,v=g.charAt(0),l=[0];for(b=0;b0;)l.push(d%w),d=d/w|0}var _="";for(b=0;0===u.at(b)&&b=0;--b)_+=g[l[b]];return _}(u,g);if(b){var E=new RegExp(".{1,"+b+"}","g");w=w.match(E).join("\r\n")}return w},G.decode=function(u,g){if("string"!=typeof u)throw new TypeError('"input" must be a string.');if("string"!=typeof g)throw new TypeError('"alphabet" must be a string.');var b=N[g];if(!b){b=N[g]=[];for(var w=0;w>=8;for(;I>0;)p.push(255&I),I>>=8}for(var E=0;u[E]===l&&E{var h=N(8659);N(4747),J.exports=h.cipher=h.cipher||{},h.cipher.algorithms=h.cipher.algorithms||{},h.cipher.createCipher=function(g,b){var w=g;if("string"==typeof w&&(w=h.cipher.getAlgorithm(w))&&(w=w()),!w)throw new Error("Unsupported algorithm: "+g);return new h.cipher.BlockCipher({algorithm:w,key:b,decrypt:!1})},h.cipher.createDecipher=function(g,b){var w=g;if("string"==typeof w&&(w=h.cipher.getAlgorithm(w))&&(w=w()),!w)throw new Error("Unsupported algorithm: "+g);return new h.cipher.BlockCipher({algorithm:w,key:b,decrypt:!0})},h.cipher.registerAlgorithm=function(g,b){g=g.toUpperCase(),h.cipher.algorithms[g]=b},h.cipher.getAlgorithm=function(g){return(g=g.toUpperCase())in h.cipher.algorithms?h.cipher.algorithms[g]:null};var u=h.cipher.BlockCipher=function(g){this.algorithm=g.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=g.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=g.decrypt,this.algorithm.initialize(g)};u.prototype.start=function(g){g=g||{};var b={};for(var w in g)b[w]=g[w];b.decrypt=this._decrypt,this._finish=!1,this._input=h.util.createBuffer(),this.output=g.output||h.util.createBuffer(),this.mode.start(b)},u.prototype.update=function(g){for(g&&this._input.putBuffer(g);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},u.prototype.finish=function(g){g&&("ECB"===this.mode.name||"CBC"===this.mode.name)&&(this.mode.pad=function(w){return g(this.blockSize,w,!1)},this.mode.unpad=function(w){return g(this.blockSize,w,!0)});var b={};return b.decrypt=this._decrypt,b.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,b)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,b))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,b))}},3481:(J,G,N)=>{var h=N(8659);N(4747),h.cipher=h.cipher||{};var u=J.exports=h.cipher.modes=h.cipher.modes||{};function g(v,l){if("string"==typeof v&&(v=h.util.createBuffer(v)),h.util.isArray(v)&&v.length>4){var p=v;v=h.util.createBuffer();for(var d=0;d0))return!0;for(var d=0;d0))return!0;for(var d=0;d0)return!1;var p=v.length(),d=v.at(p-1);return!(d>this.blockSize<<2||(v.truncate(d),0))},u.cbc=function(v){v=v||{},this.name="CBC",this.cipher=v.cipher,this.blockSize=v.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},u.cbc.prototype.start=function(v){if(null===v.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in v))throw new Error("Invalid IV parameter.");this._iv=g(v.iv,this.blockSize),this._prev=this._iv.slice(0)}},u.cbc.prototype.encrypt=function(v,l,p){if(v.length()0))return!0;for(var d=0;d0))return!0;for(var d=0;d0)return!1;var p=v.length(),d=v.at(p-1);return!(d>this.blockSize<<2||(v.truncate(d),0))},u.cfb=function(v){v=v||{},this.name="CFB",this.cipher=v.cipher,this.blockSize=v.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=h.util.createBuffer(),this._partialBytes=0},u.cfb.prototype.start=function(v){if(!("iv"in v))throw new Error("Invalid IV parameter.");this._iv=g(v.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},u.cfb.prototype.encrypt=function(v,l,p){var d=v.length();if(0===d)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&d>=this.blockSize)for(var _=0;_0&&(I=this.blockSize-I),this._partialOutput.clear(),_=0;_0)v.read-=this.blockSize;else for(_=0;_0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!p)return l.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;l.putBytes(this._partialOutput.getBytes(d-this._partialBytes)),this._partialBytes=0}},u.cfb.prototype.decrypt=function(v,l,p){var d=v.length();if(0===d)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&d>=this.blockSize)for(var _=0;_0&&(I=this.blockSize-I),this._partialOutput.clear(),_=0;_0)v.read-=this.blockSize;else for(_=0;_0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!p)return l.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;l.putBytes(this._partialOutput.getBytes(d-this._partialBytes)),this._partialBytes=0}},u.ofb=function(v){v=v||{},this.name="OFB",this.cipher=v.cipher,this.blockSize=v.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=h.util.createBuffer(),this._partialBytes=0},u.ofb.prototype.start=function(v){if(!("iv"in v))throw new Error("Invalid IV parameter.");this._iv=g(v.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},u.ofb.prototype.encrypt=function(v,l,p){var d=v.length();if(0===v.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&d>=this.blockSize)for(var _=0;_0&&(I=this.blockSize-I),this._partialOutput.clear(),_=0;_0)v.read-=this.blockSize;else for(_=0;_0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!p)return l.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;l.putBytes(this._partialOutput.getBytes(d-this._partialBytes)),this._partialBytes=0}},u.ofb.prototype.decrypt=u.ofb.prototype.encrypt,u.ctr=function(v){v=v||{},this.name="CTR",this.cipher=v.cipher,this.blockSize=v.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=h.util.createBuffer(),this._partialBytes=0},u.ctr.prototype.start=function(v){if(!("iv"in v))throw new Error("Invalid IV parameter.");this._iv=g(v.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},u.ctr.prototype.encrypt=function(v,l,p){var d=v.length();if(0===d)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&d>=this.blockSize)for(var _=0;_0&&(I=this.blockSize-I),this._partialOutput.clear(),_=0;_0&&(v.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!p)return l.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;l.putBytes(this._partialOutput.getBytes(d-this._partialBytes)),this._partialBytes=0}b(this._inBlock)},u.ctr.prototype.decrypt=u.ctr.prototype.encrypt,u.gcm=function(v){v=v||{},this.name="GCM",this.cipher=v.cipher,this.blockSize=v.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=h.util.createBuffer(),this._partialBytes=0,this._R=3774873600},u.gcm.prototype.start=function(v){if(!("iv"in v))throw new Error("Invalid IV parameter.");var p,l=h.util.createBuffer(v.iv);if(this._cipherLength=0,p="additionalData"in v?h.util.createBuffer(v.additionalData):h.util.createBuffer(),this._tagLength="tagLength"in v?v.tagLength:128,this._tag=null,v.decrypt&&(this._tag=h.util.createBuffer(v.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var d=l.length();if(12===d)this._j0=[l.getInt32(),l.getInt32(),l.getInt32(),1];else{for(this._j0=[0,0,0,0];l.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[l.getInt32(),l.getInt32(),l.getInt32(),l.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(w(8*d)))}this._inBlock=this._j0.slice(0),b(this._inBlock),this._partialBytes=0,p=h.util.createBuffer(p),this._aDataLength=w(8*p.length());var _=p.length()%this.blockSize;for(_&&p.fillWithByte(0,this.blockSize-_),this._s=[0,0,0,0];p.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[p.getInt32(),p.getInt32(),p.getInt32(),p.getInt32()])},u.gcm.prototype.encrypt=function(v,l,p){var d=v.length();if(0===d)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&d>=this.blockSize){for(var _=0;_0&&(I=this.blockSize-I),this._partialOutput.clear(),_=0;_0&&this._partialOutput.getBytes(this._partialBytes),I>0&&!p)return v.read-=this.blockSize,l.putBytes(this._partialOutput.getBytes(I-this._partialBytes)),this._partialBytes=I,!0;l.putBytes(this._partialOutput.getBytes(d-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),b(this._inBlock)},u.gcm.prototype.decrypt=function(v,l,p){var d=v.length();if(d0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),b(this._inBlock),this._hashBlock[0]=v.getInt32(),this._hashBlock[1]=v.getInt32(),this._hashBlock[2]=v.getInt32(),this._hashBlock[3]=v.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var _=0;_0;--d)l[d]=v[d]>>>1|(1&v[d-1])<<31;l[0]=v[0]>>>1,p&&(l[0]^=this._R)},u.gcm.prototype.tableMultiply=function(v){for(var l=[0,0,0,0],p=0;p<32;++p){var I=this._m[p][v[p/8|0]>>>4*(7-p%8)&15];l[0]^=I[0],l[1]^=I[1],l[2]^=I[2],l[3]^=I[3]}return l},u.gcm.prototype.ghash=function(v,l,p){return l[0]^=p[0],l[1]^=p[1],l[2]^=p[2],l[3]^=p[3],this.tableMultiply(l)},u.gcm.prototype.generateHashTable=function(v,l){for(var p=8/l,d=4*p,_=16*p,I=new Array(_),E=0;E<_;++E){var y=[0,0,0,0];y[E/d|0]=1<>>1,_=new Array(p);_[d]=v.slice(0);for(var I=d>>>1;I>0;)this.pow(_[2*I],_[I]=[]),I>>=1;for(I=2;I{var h=N(8659);function u(f,C){h.cipher.registerAlgorithm(f,function(){return new h.des.Algorithm(f,C)})}N(3311),N(3481),N(4747),J.exports=h.des=h.des||{},h.des.startEncrypting=function(f,C,A,P){var D=y({key:f,output:A,decrypt:!1,mode:P||(null===C?"ECB":"CBC")});return D.start(C),D},h.des.createEncryptionCipher=function(f,C){return y({key:f,output:null,decrypt:!1,mode:C})},h.des.startDecrypting=function(f,C,A,P){var D=y({key:f,output:A,decrypt:!0,mode:P||(null===C?"ECB":"CBC")});return D.start(C),D},h.des.createDecryptionCipher=function(f,C){return y({key:f,output:null,decrypt:!0,mode:C})},h.des.Algorithm=function(f,C){var A=this;A.name=f,A.mode=new C({blockSize:8,cipher:{encrypt:function(P,D){return E(A._keys,P,D,!1)},decrypt:function(P,D){return E(A._keys,P,D,!0)}}}),A._init=!1},h.des.Algorithm.prototype.initialize=function(f){if(!this._init){var C=h.util.createBuffer(f.key);if(0===this.name.indexOf("3DES")&&24!==C.length())throw new Error("Invalid Triple-DES key size: "+8*C.length());this._keys=function I(f){for(var q,C=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],A=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],P=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],D=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],x=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],M=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],B=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],F=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],z=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],S=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],O=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],H=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],L=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],j=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],re=f.length()>8?3:1,$=[],te=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],Z=0,ne=0;ne>>4^de))<<4,oe^=q=65535&((de^=q)>>>-16^oe),oe^=(q=858993459&(oe>>>2^(de^=q<<-16)))<<2,oe^=q=65535&((de^=q)>>>-16^oe),oe^=(q=1431655765&(oe>>>1^(de^=q<<-16)))<<1,oe^=q=16711935&((de^=q)>>>8^oe),q=(oe^=(q=1431655765&(oe>>>1^(de^=q<<8)))<<1)<<8|(de^=q)>>>20&240,oe=de<<24|de<<8&16711680|de>>>8&65280|de>>>24&240,de=q;for(var pe=0;pe>>26,de=de<<2|de>>>26):(oe=oe<<1|oe>>>27,de=de<<1|de>>>27);var ke=C[(oe&=-15)>>>28]|A[oe>>>24&15]|P[oe>>>20&15]|D[oe>>>16&15]|x[oe>>>12&15]|M[oe>>>8&15]|B[oe>>>4&15],Se=F[(de&=-15)>>>28]|z[de>>>24&15]|S[de>>>20&15]|O[de>>>16&15]|H[de>>>12&15]|L[de>>>8&15]|j[de>>>4&15];$[Z++]=ke^(q=65535&(Se>>>16^ke)),$[Z++]=Se^q<<16}}return $}(C),this._init=!0}},u("DES-ECB",h.cipher.modes.ecb),u("DES-CBC",h.cipher.modes.cbc),u("DES-CFB",h.cipher.modes.cfb),u("DES-OFB",h.cipher.modes.ofb),u("DES-CTR",h.cipher.modes.ctr),u("3DES-ECB",h.cipher.modes.ecb),u("3DES-CBC",h.cipher.modes.cbc),u("3DES-CFB",h.cipher.modes.cfb),u("3DES-OFB",h.cipher.modes.ofb),u("3DES-CTR",h.cipher.modes.ctr);var g=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],b=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],w=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],v=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],l=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],p=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],d=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],_=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function E(f,C,A,P){var x,D=32===f.length?3:9;x=3===D?P?[30,-2,-2]:[0,32,2]:P?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var M,B=C[0],F=C[1];B^=(M=252645135&(B>>>4^F))<<4,B^=(M=65535&(B>>>16^(F^=M)))<<16,B^=M=858993459&((F^=M)>>>2^B),B^=M=16711935&((F^=M<<2)>>>8^B),B=(B^=(M=1431655765&(B>>>1^(F^=M<<8)))<<1)<<1|B>>>31,F=(F^=M)<<1|F>>>31;for(var z=0;z>>4|F<<28)^f[H+1];M=B,B=F,F=M^(b[L>>>24&63]|v[L>>>16&63]|p[L>>>8&63]|_[63&L]|g[j>>>24&63]|w[j>>>16&63]|l[j>>>8&63]|d[63&j])}M=B,B=F,F=M}F=F>>>1|F<<31,F^=M=1431655765&((B=B>>>1|B<<31)>>>1^F),F^=(M=16711935&(F>>>8^(B^=M<<1)))<<8,F^=(M=858993459&(F>>>2^(B^=M)))<<2,F^=M=65535&((B^=M)>>>16^F),F^=M=252645135&((B^=M<<16)>>>4^F),A[0]=B^=M<<4,A[1]=F}function y(f){var P,A="DES-"+((f=f||{}).mode||"CBC").toUpperCase(),D=(P=f.decrypt?h.cipher.createDecipher(A,f.key):h.cipher.createCipher(A,f.key)).start;return P.start=function(x,M){var B=null;M instanceof h.util.ByteBuffer&&(B=M,M={}),(M=M||{}).output=B,M.iv=x,D.call(P,M)},P}},8659:J=>{J.exports={options:{usePureJavaScript:!1}}},9032:(J,G,N)=>{var h=N(8659);N(979),N(4747),(J.exports=h.hmac=h.hmac||{}).create=function(){var g=null,b=null,w=null,v=null,l={start:function(p,d){if(null!==p)if("string"==typeof p){if(!((p=p.toLowerCase())in h.md.algorithms))throw new Error('Unknown hash algorithm "'+p+'"');b=h.md.algorithms[p].create()}else b=p;if(null===d)d=g;else{if("string"==typeof d)d=h.util.createBuffer(d);else if(h.util.isArray(d)){var _=d;d=h.util.createBuffer();for(var I=0;I<_.length;++I)d.putByte(_[I])}var E=d.length();for(E>b.blockLength&&(b.start(),b.update(d.bytes()),d=b.digest()),w=h.util.createBuffer(),v=h.util.createBuffer(),E=d.length(),I=0;I{var u,h=N(8659);function w(W,Y,ee){this.data=[],null!=W&&("number"==typeof W?this.fromNumber(W,Y,ee):this.fromString(W,null==Y&&"string"!=typeof W?256:Y))}function v(){return new w(null)}function d(W,Y,ee,le,Oe,He){for(var tt=16383&Y,Ze=Y>>14;--He>=0;){var on=16383&this.data[W],Ir=this.data[W++]>>14,Ri=Ze*on+Ir*tt;Oe=((on=tt*on+((16383&Ri)<<14)+ee.data[le]+Oe)>>28)+(Ri>>14)+Ze*Ir,ee.data[le++]=268435455&on}return Oe}J.exports=h.jsbn=h.jsbn||{},h.jsbn.BigInteger=w,typeof navigator>"u"?(w.prototype.am=d,u=28):"Microsoft Internet Explorer"==navigator.appName?(w.prototype.am=function p(W,Y,ee,le,Oe,He){for(var tt=32767&Y,Ze=Y>>15;--He>=0;){var on=32767&this.data[W],Ir=this.data[W++]>>15,Ri=Ze*on+Ir*tt;Oe=((on=tt*on+((32767&Ri)<<15)+ee.data[le]+(1073741823&Oe))>>>30)+(Ri>>>15)+Ze*Ir+(Oe>>>30),ee.data[le++]=1073741823&on}return Oe},u=30):"Netscape"!=navigator.appName?(w.prototype.am=function l(W,Y,ee,le,Oe,He){for(;--He>=0;){var tt=Y*this.data[W++]+ee.data[le]+Oe;Oe=Math.floor(tt/67108864),ee.data[le++]=67108863&tt}return Oe},u=26):(w.prototype.am=d,u=28),w.prototype.DB=u,w.prototype.DM=(1<>>16)&&(W=ee,Y+=16),0!=(ee=W>>8)&&(W=ee,Y+=8),0!=(ee=W>>4)&&(W=ee,Y+=4),0!=(ee=W>>2)&&(W=ee,Y+=2),0!=(ee=W>>1)&&(W=ee,Y+=1),Y}function pe(W){this.m=W}function Ee(W){this.m=W,this.mp=W.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,Y+=16),0==(255&W)&&(W>>=8,Y+=8),0==(15&W)&&(W>>=4,Y+=4),0==(3&W)&&(W>>=2,Y+=2),0==(1&W)&&++Y,Y}function tn(W){for(var Y=0;0!=W;)W&=W-1,++Y;return Y}function ve(){}function yt(W){return W}function ze(W){this.r2=v(),this.q3=v(),w.ONE.dlShiftTo(2*W.t,this.r2),this.mu=this.r2.divide(W),this.m=W}pe.prototype.convert=function ke(W){return W.s<0||W.compareTo(this.m)>=0?W.mod(this.m):W},pe.prototype.revert=function Se(W){return W},pe.prototype.reduce=function Pe(W){W.divRemTo(this.m,null,W)},pe.prototype.mulTo=function we(W,Y,ee){W.multiplyTo(Y,ee),this.reduce(ee)},pe.prototype.sqrTo=function $e(W,Y){W.squareTo(Y),this.reduce(Y)},Ee.prototype.convert=function Ce(W){var Y=v();return W.abs().dlShiftTo(this.m.t,Y),Y.divRemTo(this.m,null,Y),W.s<0&&Y.compareTo(w.ZERO)>0&&this.m.subTo(Y,Y),Y},Ee.prototype.revert=function xe(W){var Y=v();return W.copyTo(Y),this.reduce(Y),Y},Ee.prototype.reduce=function Ke(W){for(;W.t<=this.mt2;)W.data[W.t++]=0;for(var Y=0;Y>15)*this.mpl&this.um)<<15)&W.DM;for(W.data[ee=Y+this.m.t]+=this.m.am(0,le,W,Y,0,this.m.t);W.data[ee]>=W.DV;)W.data[ee]-=W.DV,W.data[++ee]++}W.clamp(),W.drShiftTo(this.m.t,W),W.compareTo(this.m)>=0&&W.subTo(this.m,W)},Ee.prototype.mulTo=function Je(W,Y,ee){W.multiplyTo(Y,ee),this.reduce(ee)},Ee.prototype.sqrTo=function We(W,Y){W.squareTo(Y),this.reduce(Y)},w.prototype.copyTo=function P(W){for(var Y=this.t-1;Y>=0;--Y)W.data[Y]=this.data[Y];W.t=this.t,W.s=this.s},w.prototype.fromInt=function D(W){this.t=1,this.s=W<0?-1:0,W>0?this.data[0]=W:W<-1?this.data[0]=W+this.DV:this.t=0},w.prototype.fromString=function M(W,Y){var ee;if(16==Y)ee=4;else if(8==Y)ee=3;else if(256==Y)ee=8;else if(2==Y)ee=1;else if(32==Y)ee=5;else{if(4!=Y)return void this.fromRadix(W,Y);ee=2}this.t=0,this.s=0;for(var le=W.length,Oe=!1,He=0;--le>=0;){var tt=8==ee?255&W[le]:A(W,le);tt<0?"-"==W.charAt(le)&&(Oe=!0):(Oe=!1,0==He?this.data[this.t++]=tt:He+ee>this.DB?(this.data[this.t-1]|=(tt&(1<>this.DB-He):this.data[this.t-1]|=tt<=this.DB&&(He-=this.DB))}8==ee&&0!=(128&W[0])&&(this.s=-1,He>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==W;)--this.t},w.prototype.dlShiftTo=function j(W,Y){var ee;for(ee=this.t-1;ee>=0;--ee)Y.data[ee+W]=this.data[ee];for(ee=W-1;ee>=0;--ee)Y.data[ee]=0;Y.t=this.t+W,Y.s=this.s},w.prototype.drShiftTo=function re(W,Y){for(var ee=W;ee=0;--Ze)Y.data[Ze+He+1]=this.data[Ze]>>le|tt,tt=(this.data[Ze]&Oe)<=0;--Ze)Y.data[Ze]=0;Y.data[He]=tt,Y.t=this.t+He+1,Y.s=this.s,Y.clamp()},w.prototype.rShiftTo=function te(W,Y){Y.s=this.s;var ee=Math.floor(W/this.DB);if(ee>=this.t)Y.t=0;else{var le=W%this.DB,Oe=this.DB-le,He=(1<>le;for(var tt=ee+1;tt>le;le>0&&(Y.data[this.t-ee-1]|=(this.s&He)<>=this.DB;if(W.t>=this.DB;le+=this.s}else{for(le+=this.s;ee>=this.DB;le-=W.s}Y.s=le<0?-1:0,le<-1?Y.data[ee++]=this.DV+le:le>0&&(Y.data[ee++]=le),Y.t=ee,Y.clamp()},w.prototype.multiplyTo=function q(W,Y){var ee=this.abs(),le=W.abs(),Oe=ee.t;for(Y.t=Oe+le.t;--Oe>=0;)Y.data[Oe]=0;for(Oe=0;Oe=0;)W.data[ee]=0;for(ee=0;ee=Y.DV&&(W.data[ee+Y.t]-=Y.DV,W.data[ee+Y.t+1]=1)}W.t>0&&(W.data[W.t-1]+=Y.am(ee,Y.data[ee],W,2*ee,0,1)),W.s=0,W.clamp()},w.prototype.divRemTo=function oe(W,Y,ee){var le=W.abs();if(!(le.t<=0)){var Oe=this.abs();if(Oe.t0?(le.lShiftTo(on,He),Oe.lShiftTo(on,ee)):(le.copyTo(He),Oe.copyTo(ee));var Ir=He.t,Ri=He.data[Ir-1];if(0!=Ri){var mi=Ri*(1<1?He.data[Ir-2]>>this.F2:0),bs=this.FV/mi,Xo=(1<=0&&(ee.data[ee.t++]=1,ee.subTo(ns,ee)),w.ONE.dlShiftTo(Ir,ns),ns.subTo(He,He);He.t=0;){var el=ee.data[--vi]==Ri?this.DM:Math.floor(ee.data[vi]*bs+(ee.data[vi-1]+Xt)*Xo);if((ee.data[vi]+=He.am(0,el,ee,Dn,0,Ir))0&&ee.rShiftTo(on,ee),tt<0&&w.ZERO.subTo(ee,ee)}}},w.prototype.invDigit=function K(){if(this.t<1)return 0;var W=this.data[0];if(0==(1&W))return 0;var Y=3&W;return(Y=(Y=(Y=(Y=Y*(2-(15&W)*Y)&15)*(2-(255&W)*Y)&255)*(2-((65535&W)*Y&65535))&65535)*(2-W*Y%this.DV)%this.DV)>0?this.DV-Y:-Y},w.prototype.isEven=function Xe(){return 0==(this.t>0?1&this.data[0]:this.s)},w.prototype.exp=function Ot(W,Y){if(W>4294967295||W<1)return w.ONE;var ee=v(),le=v(),Oe=Y.convert(this),He=H(W)-1;for(Oe.copyTo(ee);--He>=0;)if(Y.sqrTo(ee,le),(W&1<0)Y.mulTo(le,Oe,ee);else{var tt=ee;ee=le,le=tt}return Y.revert(ee)},w.prototype.toString=function F(W){if(this.s<0)return"-"+this.negate().toString(W);var Y;if(16==W)Y=4;else if(8==W)Y=3;else if(2==W)Y=1;else if(32==W)Y=5;else{if(4!=W)return this.toRadix(W);Y=2}var le,ee=(1<0)for(Ze>Ze)>0&&(Oe=!0,He=C(le));tt>=0;)Ze>(Ze+=this.DB-Y)):(le=this.data[tt]>>(Ze-=Y)&ee,Ze<=0&&(Ze+=this.DB,--tt)),le>0&&(Oe=!0),Oe&&(He+=C(le));return Oe?He:"0"},w.prototype.negate=function z(){var W=v();return w.ZERO.subTo(this,W),W},w.prototype.abs=function S(){return this.s<0?this.negate():this},w.prototype.compareTo=function O(W){var Y=this.s-W.s;if(0!=Y)return Y;var ee=this.t;if(0!=(Y=ee-W.t))return this.s<0?-Y:Y;for(;--ee>=0;)if(0!=(Y=this.data[ee]-W.data[ee]))return Y;return 0},w.prototype.bitLength=function L(){return this.t<=0?0:this.DB*(this.t-1)+H(this.data[this.t-1]^this.s&this.DM)},w.prototype.mod=function de(W){var Y=v();return this.abs().divRemTo(W,null,Y),this.s<0&&Y.compareTo(w.ZERO)>0&&W.subTo(Y,Y),Y},w.prototype.modPowInt=function pt(W,Y){var ee;return ee=W<256||Y.isEven()?new pe(Y):new Ee(Y),this.exp(W,ee)},w.ZERO=x(0),w.ONE=x(1),ve.prototype.convert=yt,ve.prototype.revert=yt,ve.prototype.mulTo=function St(W,Y,ee){W.multiplyTo(Y,ee)},ve.prototype.sqrTo=function mn(W,Y){W.squareTo(Y)},ze.prototype.convert=function ht(W){if(W.s<0||W.t>2*this.m.t)return W.mod(this.m);if(W.compareTo(this.m)<0)return W;var Y=v();return W.copyTo(Y),this.reduce(Y),Y},ze.prototype.revert=function Et(W){return W},ze.prototype.reduce=function lt(W){for(W.drShiftTo(this.m.t-1,this.r2),W.t>this.m.t+1&&(W.t=this.m.t+1,W.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);W.compareTo(this.r2)<0;)W.dAddOffset(1,this.m.t+1);for(W.subTo(this.r2,W);W.compareTo(this.m)>=0;)W.subTo(this.m,W)},ze.prototype.mulTo=function jt(W,Y,ee){W.multiplyTo(Y,ee),this.reduce(ee)},ze.prototype.sqrTo=function It(W,Y){W.squareTo(Y),this.reduce(Y)};var ir=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],La=(1<<26)/ir[ir.length-1];w.prototype.chunkSize=function ie(W){return Math.floor(Math.LN2*this.DB/Math.log(W))},w.prototype.toRadix=function ye(W){if(null==W&&(W=10),0==this.signum()||W<2||W>36)return"0";var Y=this.chunkSize(W),ee=Math.pow(W,Y),le=x(ee),Oe=v(),He=v(),tt="";for(this.divRemTo(le,Oe,He);Oe.signum()>0;)tt=(ee+He.intValue()).toString(W).substr(1)+tt,Oe.divRemTo(le,Oe,He);return He.intValue().toString(W)+tt},w.prototype.fromRadix=function me(W,Y){this.fromInt(0),null==Y&&(Y=10);for(var ee=this.chunkSize(Y),le=Math.pow(Y,ee),Oe=!1,He=0,tt=0,Ze=0;Ze=ee&&(this.dMultiply(le),this.dAddOffset(tt,0),He=0,tt=0))}He>0&&(this.dMultiply(Math.pow(Y,He)),this.dAddOffset(tt,0)),Oe&&w.ZERO.subTo(this,this)},w.prototype.fromNumber=function _e(W,Y,ee){if("number"==typeof Y)if(W<2)this.fromInt(1);else for(this.fromNumber(W,ee),this.testBit(W-1)||this.bitwiseTo(w.ONE.shiftLeft(W-1),ge,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(Y);)this.dAddOffset(2,0),this.bitLength()>W&&this.subTo(w.ONE.shiftLeft(W-1),this);else{var le=new Array,Oe=7&W;le.length=1+(W>>3),Y.nextBytes(le),Oe>0?le[0]&=(1<>=this.DB;if(W.t>=this.DB;le+=this.s}else{for(le+=this.s;ee>=this.DB;le+=W.s}Y.s=le<0?-1:0,le>0?Y.data[ee++]=le:le<-1&&(Y.data[ee++]=this.DV+le),Y.t=ee,Y.clamp()},w.prototype.dMultiply=function ut(W){this.data[this.t]=this.am(0,W-1,this,0,0,this.t),++this.t,this.clamp()},w.prototype.dAddOffset=function ce(W,Y){if(0!=W){for(;this.t<=Y;)this.data[this.t++]=0;for(this.data[Y]+=W;this.data[Y]>=this.DV;)this.data[Y]-=this.DV,++Y>=this.t&&(this.data[this.t++]=0),++this.data[Y]}},w.prototype.multiplyLowerTo=function Qe(W,Y,ee){var Oe,le=Math.min(this.t+W.t,Y);for(ee.s=0,ee.t=le;le>0;)ee.data[--le]=0;for(Oe=ee.t-this.t;le=0;)ee.data[le]=0;for(le=Math.max(Y-this.t,0);le0)if(0==Y)ee=this.data[0]%W;else for(var le=this.t-1;le>=0;--le)ee=(Y*ee+this.data[le])%W;return ee},w.prototype.millerRabin=function Qf(W){var Y=this.subtract(w.ONE),ee=Y.getLowestSetBit();if(ee<=0)return!1;for(var He,le=Y.shiftRight(ee),Oe=function ka(){return{nextBytes:function(W){for(var Y=0;Y=0);var Ze=He.modPow(le,this);if(0!=Ze.compareTo(w.ONE)&&0!=Ze.compareTo(Y)){for(var on=1;on++>24},w.prototype.shortValue=function ni(){return 0==this.t?this.s:this.data[0]<<16>>16},w.prototype.signum=function fe(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},w.prototype.toByteArray=function Ne(){var W=this.t,Y=new Array;Y[0]=this.s;var le,ee=this.DB-W*this.DB%8,Oe=0;if(W-- >0)for(ee>ee)!=(this.s&this.DM)>>ee&&(Y[Oe++]=le|this.s<=0;)ee<8?(le=(this.data[W]&(1<>(ee+=this.DB-8)):(le=this.data[W]>>(ee-=8)&255,ee<=0&&(ee+=this.DB,--W)),0!=(128&le)&&(le|=-256),0==Oe&&(128&this.s)!=(128&le)&&++Oe,(Oe>0||le!=this.s)&&(Y[Oe++]=le);return Y},w.prototype.equals=function Ye(W){return 0==this.compareTo(W)},w.prototype.min=function qe(W){return this.compareTo(W)<0?this:W},w.prototype.max=function st(W){return this.compareTo(W)>0?this:W},w.prototype.and=function be(W){var Y=v();return this.bitwiseTo(W,je,Y),Y},w.prototype.or=function De(W){var Y=v();return this.bitwiseTo(W,ge,Y),Y},w.prototype.xor=function Be(W){var Y=v();return this.bitwiseTo(W,Ue,Y),Y},w.prototype.andNot=function Pt(W){var Y=v();return this.bitwiseTo(W,dt,Y),Y},w.prototype.not=function vt(){for(var W=v(),Y=0;Y=this.t?0!=this.s:0!=(this.data[Y]&1<1){var Ri=v();for(He.sqrTo(tt[1],Ri);Ze<=Ir;)tt[Ze]=v(),He.mulTo(Ri,tt[Ze-2],tt[Ze]),Ze+=2}var bs,vi,mi=W.t-1,Xo=!0,Xt=v();for(ee=H(W.data[mi])-1;mi>=0;){for(ee>=on?bs=W.data[mi]>>ee-on&Ir:(bs=(W.data[mi]&(1<0&&(bs|=W.data[mi-1]>>this.DB+ee-on)),Ze=le;0==(1&bs);)bs>>=1,--Ze;if((ee-=Ze)<0&&(ee+=this.DB,--mi),Xo)tt[bs].copyTo(Oe),Xo=!1;else{for(;Ze>1;)He.sqrTo(Oe,Xt),He.sqrTo(Xt,Oe),Ze-=2;Ze>0?He.sqrTo(Oe,Xt):(vi=Oe,Oe=Xt,Xt=vi),He.mulTo(Xt,tt[bs],Oe)}for(;mi>=0&&0==(W.data[mi]&1<=0?(ee.subTo(le,ee),Y&&Oe.subTo(tt,Oe),He.subTo(Ze,He)):(le.subTo(ee,le),Y&&tt.subTo(Oe,tt),Ze.subTo(He,Ze))}return 0!=le.compareTo(w.ONE)?w.ZERO:Ze.compareTo(W)>=0?Ze.subtract(W):Ze.signum()<0?(Ze.addTo(W,Ze),Ze.signum()<0?Ze.add(W):Ze):Ze},w.prototype.pow=function Ge(W){return this.exp(W,new ve)},w.prototype.gcd=function Nn(W){var Y=this.s<0?this.negate():this.clone(),ee=W.s<0?W.negate():W.clone();if(Y.compareTo(ee)<0){var le=Y;Y=ee,ee=le}var Oe=Y.getLowestSetBit(),He=ee.getLowestSetBit();if(He<0)return Y;for(Oe0&&(Y.rShiftTo(He,Y),ee.rShiftTo(He,ee));Y.signum()>0;)(Oe=Y.getLowestSetBit())>0&&Y.rShiftTo(Oe,Y),(Oe=ee.getLowestSetBit())>0&&ee.rShiftTo(Oe,ee),Y.compareTo(ee)>=0?(Y.subTo(ee,Y),Y.rShiftTo(1,Y)):(ee.subTo(Y,ee),ee.rShiftTo(1,ee));return He>0&&ee.lShiftTo(He,ee),ee},w.prototype.isProbablePrime=function Zo(W){var Y,ee=this.abs();if(1==ee.t&&ee.data[0]<=ir[ir.length-1]){for(Y=0;Y{var h=N(8659);J.exports=h.md=h.md||{},h.md.algorithms=h.md.algorithms||{}},9386:(J,G,N)=>{var h=N(8659);N(8449),J.exports=h.mgf=h.mgf||{},h.mgf.mgf1=h.mgf1},8449:(J,G,N)=>{var h=N(8659);N(4747),h.mgf=h.mgf||{},(J.exports=h.mgf.mgf1=h.mgf1=h.mgf1||{}).create=function(g){return{generate:function(w,v){for(var l=new h.util.ByteBuffer,p=Math.ceil(v/g.digestLength),d=0;d{var h=N(8659);h.pki=h.pki||{};var u=J.exports=h.pki.oids=h.oids=h.oids||{};function g(w,v){u[w]=v,u[v]=w}function b(w,v){u[w]=v}g("1.2.840.113549.1.1.1","rsaEncryption"),g("1.2.840.113549.1.1.4","md5WithRSAEncryption"),g("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),g("1.2.840.113549.1.1.7","RSAES-OAEP"),g("1.2.840.113549.1.1.8","mgf1"),g("1.2.840.113549.1.1.9","pSpecified"),g("1.2.840.113549.1.1.10","RSASSA-PSS"),g("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),g("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),g("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),g("1.3.101.112","EdDSA25519"),g("1.2.840.10040.4.3","dsa-with-sha1"),g("1.3.14.3.2.7","desCBC"),g("1.3.14.3.2.26","sha1"),g("1.3.14.3.2.29","sha1WithRSASignature"),g("2.16.840.1.101.3.4.2.1","sha256"),g("2.16.840.1.101.3.4.2.2","sha384"),g("2.16.840.1.101.3.4.2.3","sha512"),g("2.16.840.1.101.3.4.2.4","sha224"),g("2.16.840.1.101.3.4.2.5","sha512-224"),g("2.16.840.1.101.3.4.2.6","sha512-256"),g("1.2.840.113549.2.2","md2"),g("1.2.840.113549.2.5","md5"),g("1.2.840.113549.1.7.1","data"),g("1.2.840.113549.1.7.2","signedData"),g("1.2.840.113549.1.7.3","envelopedData"),g("1.2.840.113549.1.7.4","signedAndEnvelopedData"),g("1.2.840.113549.1.7.5","digestedData"),g("1.2.840.113549.1.7.6","encryptedData"),g("1.2.840.113549.1.9.1","emailAddress"),g("1.2.840.113549.1.9.2","unstructuredName"),g("1.2.840.113549.1.9.3","contentType"),g("1.2.840.113549.1.9.4","messageDigest"),g("1.2.840.113549.1.9.5","signingTime"),g("1.2.840.113549.1.9.6","counterSignature"),g("1.2.840.113549.1.9.7","challengePassword"),g("1.2.840.113549.1.9.8","unstructuredAddress"),g("1.2.840.113549.1.9.14","extensionRequest"),g("1.2.840.113549.1.9.20","friendlyName"),g("1.2.840.113549.1.9.21","localKeyId"),g("1.2.840.113549.1.9.22.1","x509Certificate"),g("1.2.840.113549.1.12.10.1.1","keyBag"),g("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),g("1.2.840.113549.1.12.10.1.3","certBag"),g("1.2.840.113549.1.12.10.1.4","crlBag"),g("1.2.840.113549.1.12.10.1.5","secretBag"),g("1.2.840.113549.1.12.10.1.6","safeContentsBag"),g("1.2.840.113549.1.5.13","pkcs5PBES2"),g("1.2.840.113549.1.5.12","pkcs5PBKDF2"),g("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),g("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),g("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),g("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),g("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),g("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),g("1.2.840.113549.2.7","hmacWithSHA1"),g("1.2.840.113549.2.8","hmacWithSHA224"),g("1.2.840.113549.2.9","hmacWithSHA256"),g("1.2.840.113549.2.10","hmacWithSHA384"),g("1.2.840.113549.2.11","hmacWithSHA512"),g("1.2.840.113549.3.7","des-EDE3-CBC"),g("2.16.840.1.101.3.4.1.2","aes128-CBC"),g("2.16.840.1.101.3.4.1.22","aes192-CBC"),g("2.16.840.1.101.3.4.1.42","aes256-CBC"),g("2.5.4.3","commonName"),g("2.5.4.4","surname"),g("2.5.4.5","serialNumber"),g("2.5.4.6","countryName"),g("2.5.4.7","localityName"),g("2.5.4.8","stateOrProvinceName"),g("2.5.4.9","streetAddress"),g("2.5.4.10","organizationName"),g("2.5.4.11","organizationalUnitName"),g("2.5.4.12","title"),g("2.5.4.13","description"),g("2.5.4.15","businessCategory"),g("2.5.4.17","postalCode"),g("2.5.4.42","givenName"),g("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),g("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),g("2.16.840.1.113730.1.1","nsCertType"),g("2.16.840.1.113730.1.13","nsComment"),b("2.5.29.1","authorityKeyIdentifier"),b("2.5.29.2","keyAttributes"),b("2.5.29.3","certificatePolicies"),b("2.5.29.4","keyUsageRestriction"),b("2.5.29.5","policyMapping"),b("2.5.29.6","subtreesConstraint"),b("2.5.29.7","subjectAltName"),b("2.5.29.8","issuerAltName"),b("2.5.29.9","subjectDirectoryAttributes"),b("2.5.29.10","basicConstraints"),b("2.5.29.11","nameConstraints"),b("2.5.29.12","policyConstraints"),b("2.5.29.13","basicConstraints"),g("2.5.29.14","subjectKeyIdentifier"),g("2.5.29.15","keyUsage"),b("2.5.29.16","privateKeyUsagePeriod"),g("2.5.29.17","subjectAltName"),g("2.5.29.18","issuerAltName"),g("2.5.29.19","basicConstraints"),b("2.5.29.20","cRLNumber"),b("2.5.29.21","cRLReason"),b("2.5.29.22","expirationDate"),b("2.5.29.23","instructionCode"),b("2.5.29.24","invalidityDate"),b("2.5.29.25","cRLDistributionPoints"),b("2.5.29.26","issuingDistributionPoint"),b("2.5.29.27","deltaCRLIndicator"),b("2.5.29.28","issuingDistributionPoint"),b("2.5.29.29","certificateIssuer"),b("2.5.29.30","nameConstraints"),g("2.5.29.31","cRLDistributionPoints"),g("2.5.29.32","certificatePolicies"),b("2.5.29.33","policyMappings"),b("2.5.29.34","policyConstraints"),g("2.5.29.35","authorityKeyIdentifier"),b("2.5.29.36","policyConstraints"),g("2.5.29.37","extKeyUsage"),b("2.5.29.46","freshestCRL"),b("2.5.29.54","inhibitAnyPolicy"),g("1.3.6.1.4.1.11129.2.4.2","timestampList"),g("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),g("1.3.6.1.5.5.7.3.1","serverAuth"),g("1.3.6.1.5.5.7.3.2","clientAuth"),g("1.3.6.1.5.5.7.3.3","codeSigning"),g("1.3.6.1.5.5.7.3.4","emailProtection"),g("1.3.6.1.5.5.7.3.8","timeStamping")},2158:(J,G,N)=>{var h=N(8659);if(N(1298),N(7791),N(279),N(979),N(6078),N(7949),N(8604),N(8365),N(209),N(5517),N(4747),typeof u>"u")var u=h.jsbn.BigInteger;var g=h.asn1,b=h.pki=h.pki||{};J.exports=b.pbe=h.pbe=h.pbe||{};var w=b.oids,v={name:"EncryptedPrivateKeyInfo",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:g.Class.UNIVERSAL,type:g.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},l={name:"PBES2Algorithms",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:g.Class.UNIVERSAL,type:g.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:g.Class.UNIVERSAL,type:g.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},p={name:"pkcs-12PbeParams",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:g.Class.UNIVERSAL,type:g.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,capture:"iterations"}]};function d(y,f){return y.start().update(f).digest().getBytes()}function _(y){var f;if(y){if(!(f=b.oids[g.derToOid(y)])){var C=new Error("Unsupported PRF OID.");throw C.oid=y,C.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],C}}else f="hmacWithSHA1";return I(f)}function I(y){var f=h.md;switch(y){case"hmacWithSHA224":f=h.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":y=y.substr(8).toLowerCase();break;default:var C=new Error("Unsupported PRF algorithm.");throw C.algorithm=y,C.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],C}if(!f||!(y in f))throw new Error("Unknown hash algorithm: "+y);return f[y].create()}b.encryptPrivateKeyInfo=function(y,f,C){(C=C||{}).saltSize=C.saltSize||8,C.count=C.count||2048,C.algorithm=C.algorithm||"aes128",C.prfAlgorithm=C.prfAlgorithm||"sha1";var x,M,B,A=h.random.getBytesSync(C.saltSize),P=C.count,D=g.integerToDer(P);if(0===C.algorithm.indexOf("aes")||"des"===C.algorithm){var F,z,S;switch(C.algorithm){case"aes128":x=16,F=16,z=w["aes128-CBC"],S=h.aes.createEncryptionCipher;break;case"aes192":x=24,F=16,z=w["aes192-CBC"],S=h.aes.createEncryptionCipher;break;case"aes256":x=32,F=16,z=w["aes256-CBC"],S=h.aes.createEncryptionCipher;break;case"des":x=8,F=8,z=w.desCBC,S=h.des.createEncryptionCipher;break;default:throw(O=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=C.algorithm,O}var H="hmacWith"+C.prfAlgorithm.toUpperCase(),L=I(H),j=h.pkcs5.pbkdf2(f,A,P,x,L),re=h.random.getBytesSync(F);($=S(j)).start(re),$.update(g.toDer(y)),$.finish(),B=$.output.getBytes();var te=function E(y,f,C,A){var P=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OCTETSTRING,!1,y),g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,f.getBytes())]);return"hmacWithSHA1"!==A&&P.value.push(g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,h.util.hexToBytes(C.toString(16))),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(b.oids[A]).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.NULL,!1,"")])),P}(A,D,x,H);M=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(w.pkcs5PBES2).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(w.pkcs5PBKDF2).getBytes()),te]),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(z).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.OCTETSTRING,!1,re)])])])}else{var O;if("3des"!==C.algorithm)throw(O=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=C.algorithm,O;x=24;var $,Z=new h.util.ByteBuffer(A);j=b.pbe.generatePkcs12Key(f,Z,1,P,x),re=b.pbe.generatePkcs12Key(f,Z,2,P,x),($=h.des.createEncryptionCipher(j)).start(re),$.update(g.toDer(y)),$.finish(),B=$.output.getBytes(),M=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(w["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OCTETSTRING,!1,A),g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,D.getBytes())])])}return g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[M,g.create(g.Class.UNIVERSAL,g.Type.OCTETSTRING,!1,B)])},b.decryptPrivateKeyInfo=function(y,f){var C=null,A={},P=[];if(!g.validate(y,v,A,P)){var D=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw D.errors=P,D}var x=g.derToOid(A.encryptionOid),M=b.pbe.getCipher(x,A.encryptionParams,f),B=h.util.createBuffer(A.encryptedData);return M.update(B),M.finish()&&(C=g.fromDer(M.output)),C},b.encryptedPrivateKeyToPem=function(y,f){var C={type:"ENCRYPTED PRIVATE KEY",body:g.toDer(y).getBytes()};return h.pem.encode(C,{maxline:f})},b.encryptedPrivateKeyFromPem=function(y){var f=h.pem.decode(y)[0];if("ENCRYPTED PRIVATE KEY"!==f.type){var C=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw C.headerType=f.type,C}if(f.procType&&"ENCRYPTED"===f.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return g.fromDer(f.body)},b.encryptRsaPrivateKey=function(y,f,C){if(!(C=C||{}).legacy){var A=b.wrapRsaPrivateKey(b.privateKeyToAsn1(y));return A=b.encryptPrivateKeyInfo(A,f,C),b.encryptedPrivateKeyToPem(A)}var P,D,x,M;switch(C.algorithm){case"aes128":P="AES-128-CBC",x=16,D=h.random.getBytesSync(16),M=h.aes.createEncryptionCipher;break;case"aes192":P="AES-192-CBC",x=24,D=h.random.getBytesSync(16),M=h.aes.createEncryptionCipher;break;case"aes256":P="AES-256-CBC",x=32,D=h.random.getBytesSync(16),M=h.aes.createEncryptionCipher;break;case"3des":P="DES-EDE3-CBC",x=24,D=h.random.getBytesSync(8),M=h.des.createEncryptionCipher;break;case"des":P="DES-CBC",x=8,D=h.random.getBytesSync(8),M=h.des.createEncryptionCipher;break;default:var B=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+C.algorithm+'".');throw B.algorithm=C.algorithm,B}var z=M(h.pbe.opensslDeriveBytes(f,D.substr(0,8),x));z.start(D),z.update(g.toDer(b.privateKeyToAsn1(y))),z.finish();var S={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:P,parameters:h.util.bytesToHex(D).toUpperCase()},body:z.output.getBytes()};return h.pem.encode(S)},b.decryptRsaPrivateKey=function(y,f){var C=null,A=h.pem.decode(y)[0];if("ENCRYPTED PRIVATE KEY"!==A.type&&"PRIVATE KEY"!==A.type&&"RSA PRIVATE KEY"!==A.type)throw(P=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=P,P;if(A.procType&&"ENCRYPTED"===A.procType.type){var D,x;switch(A.dekInfo.algorithm){case"DES-CBC":D=8,x=h.des.createDecryptionCipher;break;case"DES-EDE3-CBC":D=24,x=h.des.createDecryptionCipher;break;case"AES-128-CBC":D=16,x=h.aes.createDecryptionCipher;break;case"AES-192-CBC":D=24,x=h.aes.createDecryptionCipher;break;case"AES-256-CBC":D=32,x=h.aes.createDecryptionCipher;break;case"RC2-40-CBC":D=5,x=function(S){return h.rc2.createDecryptionCipher(S,40)};break;case"RC2-64-CBC":D=8,x=function(S){return h.rc2.createDecryptionCipher(S,64)};break;case"RC2-128-CBC":D=16,x=function(S){return h.rc2.createDecryptionCipher(S,128)};break;default:var P;throw(P=new Error('Could not decrypt private key; unsupported encryption algorithm "'+A.dekInfo.algorithm+'".')).algorithm=A.dekInfo.algorithm,P}var M=h.util.hexToBytes(A.dekInfo.parameters),F=x(h.pbe.opensslDeriveBytes(f,M.substr(0,8),D));if(F.start(M),F.update(h.util.createBuffer(A.body)),!F.finish())return C;C=F.output.getBytes()}else C=A.body;return null!==(C="ENCRYPTED PRIVATE KEY"===A.type?b.decryptPrivateKeyInfo(g.fromDer(C),f):g.fromDer(C))&&(C=b.privateKeyFromAsn1(C)),C},b.pbe.generatePkcs12Key=function(y,f,C,A,P,D){var x,M;if(typeof D>"u"||null===D){if(!("sha1"in h.md))throw new Error('"sha1" hash algorithm unavailable.');D=h.md.sha1.create()}var B=D.digestLength,F=D.blockLength,z=new h.util.ByteBuffer,S=new h.util.ByteBuffer;if(null!=y){for(M=0;M=0;M--)we>>=8,we+=pe.at(M)+Pe.at(M),Pe.setAt(M,255&we);Se.putBuffer(Pe)}Z=Se,z.putBuffer(oe)}return z.truncate(z.length()-P),z},b.pbe.getCipher=function(y,f,C){switch(y){case b.oids.pkcs5PBES2:return b.pbe.getCipherForPBES2(y,f,C);case b.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case b.oids["pbewithSHAAnd40BitRC2-CBC"]:return b.pbe.getCipherForPKCS12PBE(y,f,C);default:var A=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw A.oid=y,A.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],A}},b.pbe.getCipherForPBES2=function(y,f,C){var D,A={},P=[];if(!g.validate(f,l,A,P))throw(D=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=P,D;if((y=g.derToOid(A.kdfOid))!==b.oids.pkcs5PBKDF2)throw(D=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=y,D.supportedOids=["pkcs5PBKDF2"],D;if((y=g.derToOid(A.encOid))!==b.oids["aes128-CBC"]&&y!==b.oids["aes192-CBC"]&&y!==b.oids["aes256-CBC"]&&y!==b.oids["des-EDE3-CBC"]&&y!==b.oids.desCBC)throw(D=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=y,D.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],D;var B,F,x=A.kdfSalt,M=h.util.createBuffer(A.kdfIterationCount);switch(M=M.getInt(M.length()<<3),b.oids[y]){case"aes128-CBC":B=16,F=h.aes.createDecryptionCipher;break;case"aes192-CBC":B=24,F=h.aes.createDecryptionCipher;break;case"aes256-CBC":B=32,F=h.aes.createDecryptionCipher;break;case"des-EDE3-CBC":B=24,F=h.des.createDecryptionCipher;break;case"desCBC":B=8,F=h.des.createDecryptionCipher}var z=_(A.prfOid),S=h.pkcs5.pbkdf2(C,x,M,B,z),O=A.encIv,H=F(S);return H.start(O),H},b.pbe.getCipherForPKCS12PBE=function(y,f,C){var A={},P=[];if(!g.validate(f,p,A,P))throw(D=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=P,D;var B,F,z,x=h.util.createBuffer(A.salt),M=h.util.createBuffer(A.iterations);switch(M=M.getInt(M.length()<<3),y){case b.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:B=24,F=8,z=h.des.startDecrypting;break;case b.oids["pbewithSHAAnd40BitRC2-CBC"]:B=5,F=8,z=function(j,re){var $=h.rc2.createDecryptionCipher(j,40);return $.start(re,null),$};break;default:var D;throw(D=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=y,D}var S=_(A.prfOid),O=b.pbe.generatePkcs12Key(C,x,1,M,B,S);return S.start(),z(O,b.pbe.generatePkcs12Key(C,x,2,M,F,S))},b.pbe.opensslDeriveBytes=function(y,f,C,A){if(typeof A>"u"||null===A){if(!("md5"in h.md))throw new Error('"md5" hash algorithm unavailable.');A=h.md.md5.create()}null===f&&(f="");for(var P=[d(A,y+f)],D=16,x=1;D{var h=N(8659);N(9032),N(979),N(4747);var g,u=h.pkcs5=h.pkcs5||{};h.util.isNodejs&&!h.options.usePureJavaScript&&(g=N(5819)),J.exports=h.pbkdf2=u.pbkdf2=function(b,w,v,l,p,d){if("function"==typeof p&&(d=p,p=null),h.util.isNodejs&&!h.options.usePureJavaScript&&g.pbkdf2&&(null===p||"object"!=typeof p)&&(g.pbkdf2Sync.length>4||!p||"sha1"===p))return"string"!=typeof p&&(p="sha1"),b=Buffer.from(b,"binary"),w=Buffer.from(w,"binary"),d?4===g.pbkdf2Sync.length?g.pbkdf2(b,w,v,l,function(z,S){if(z)return d(z);d(null,S.toString("binary"))}):g.pbkdf2(b,w,v,l,p,function(z,S){if(z)return d(z);d(null,S.toString("binary"))}):4===g.pbkdf2Sync.length?g.pbkdf2Sync(b,w,v,l).toString("binary"):g.pbkdf2Sync(b,w,v,l,p).toString("binary");if((typeof p>"u"||null===p)&&(p="sha1"),"string"==typeof p){if(!(p in h.md.algorithms))throw new Error("Unknown hash algorithm: "+p);p=h.md[p].create()}var _=p.digestLength;if(l>4294967295*_){var I=new Error("Derived key is too long.");if(d)return d(I);throw I}var E=Math.ceil(l/_),y=l-(E-1)*_,f=h.hmac.create();f.start(p,b);var A,P,D,C="";if(!d){for(var x=1;x<=E;++x){f.start(null,null),f.update(w),f.update(h.util.int32ToBytes(x)),A=D=f.digest().getBytes();for(var M=2;M<=v;++M)f.start(null,null),f.update(D),P=f.digest().getBytes(),A=h.util.xorBytes(A,P,_),D=P;C+=xE)return d(null,C);f.start(null,null),f.update(w),f.update(h.util.int32ToBytes(x)),A=D=f.digest().getBytes(),M=2,F()}function F(){if(M<=v)return f.start(null,null),f.update(D),P=f.digest().getBytes(),A=h.util.xorBytes(A,P,_),D=P,++M,h.util.setImmediate(F);C+=x{var h=N(8659);N(4747);var u=J.exports=h.pem=h.pem||{};function g(w){for(var v=w.name+": ",l=[],p=function(y,f){return" "+f},d=0;d65&&-1!==I){var E=v[I];","===E?(++I,v=v.substr(0,I)+"\r\n "+v.substr(I)):v=v.substr(0,I)+"\r\n"+E+v.substr(I+1),_=d-I-1,I=-1,++d}else(" "===v[d]||"\t"===v[d]||","===v[d])&&(I=d);return v}function b(w){return w.replace(/^\s+/,"")}u.encode=function(w,v){v=v||{};var p,l="-----BEGIN "+w.type+"-----\r\n";if(w.procType&&(l+=g(p={name:"Proc-Type",values:[String(w.procType.version),w.procType.type]})),w.contentDomain&&(l+=g(p={name:"Content-Domain",values:[w.contentDomain]})),w.dekInfo&&(p={name:"DEK-Info",values:[w.dekInfo.algorithm]},w.dekInfo.parameters&&p.values.push(w.dekInfo.parameters),l+=g(p)),w.headers)for(var d=0;d{var h=N(8659);N(4747),N(8365),N(7690);var u=J.exports=h.pkcs1=h.pkcs1||{};function g(b,w,v){v||(v=h.md.sha1.create());for(var l="",p=Math.ceil(w/v.digestLength),d=0;d>24&255,d>>16&255,d>>8&255,255&d);v.start(),v.update(b+_),l+=v.digest().getBytes()}return l.substring(0,w)}u.encode_rsa_oaep=function(b,w,v){var l,p,d,_;"string"==typeof v?(l=v,p=arguments[3]||void 0,d=arguments[4]||void 0):v&&(l=v.label||void 0,p=v.seed||void 0,d=v.md||void 0,v.mgf1&&v.mgf1.md&&(_=v.mgf1.md)),d?d.start():d=h.md.sha1.create(),_||(_=d);var I=Math.ceil(b.n.bitLength()/8),E=I-2*d.digestLength-2;if(w.length>E)throw(y=new Error("RSAES-OAEP input message length is too long.")).length=w.length,y.maxLength=E,y;l||(l=""),d.update(l,"raw");for(var f=d.digest(),C="",A=E-w.length,P=0;P{var h=N(8659);N(1298),N(7791),N(279),N(6078),N(8604),N(4957),N(8365),N(4747),N(5911);var u=h.asn1,g=J.exports=h.pkcs7=h.pkcs7||{};function b(A){var P={},D=[];if(!u.validate(A,g.asn1.recipientInfoValidator,P,D)){var x=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw x.errors=D,x}return{version:P.version.charCodeAt(0),issuer:h.pki.RDNAttributesAsArray(P.issuer),serialNumber:h.util.createBuffer(P.serial).toHex(),encryptedContent:{algorithm:u.derToOid(P.encAlgorithm),parameter:P.encParameter?P.encParameter.value:void 0,content:P.encKey}}}function w(A){return u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.INTEGER,!1,u.integerToDer(A.version).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[h.pki.distinguishedNameToAsn1({attributes:A.issuer}),u.create(u.Class.UNIVERSAL,u.Type.INTEGER,!1,h.util.hexToBytes(A.serialNumber))]),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(A.encryptedContent.algorithm).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.NULL,!1,"")]),u.create(u.Class.UNIVERSAL,u.Type.OCTETSTRING,!1,A.encryptedContent.content)])}function l(A){for(var P=[],D=0;D0){for(var D=u.create(u.Class.CONTEXT_SPECIFIC,1,!0,[]),x=0;x=D&&M0&&F.value[0].value.push(u.create(u.Class.CONTEXT_SPECIFIC,0,!0,x)),B.length>0&&F.value[0].value.push(u.create(u.Class.CONTEXT_SPECIFIC,1,!0,B)),F.value[0].value.push(u.create(u.Class.UNIVERSAL,u.Type.SET,!0,A.signerInfos)),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(A.type).getBytes()),F])},addSigner:function(x){var M=x.issuer,B=x.serialNumber;if(x.certificate){var F=x.certificate;"string"==typeof F&&(F=h.pki.certificateFromPem(F)),M=F.issuer.attributes,B=F.serialNumber}var z=x.key;if(!z)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof z&&(z=h.pki.privateKeyFromPem(z));var S=x.digestAlgorithm||h.pki.oids.sha1;switch(S){case h.pki.oids.sha1:case h.pki.oids.sha256:case h.pki.oids.sha384:case h.pki.oids.sha512:case h.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+S)}var O=x.authenticatedAttributes||[];if(O.length>0){for(var H=!1,L=!1,j=0;j{var h=N(8659);N(7791),N(4747);var u=h.asn1,g=J.exports=h.pkcs7asn1=h.pkcs7asn1||{};h.pkcs7=h.pkcs7||{},h.pkcs7.asn1=g;var b={name:"ContentInfo",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:u.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};g.contentInfoValidator=b;var w={name:"EncryptedContentInfo",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:u.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:u.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};g.envelopedDataValidator={name:"EnvelopedData",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:u.Class.UNIVERSAL,type:u.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(w)},g.encryptedDataValidator={name:"EncryptedData",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"version"}].concat(w)},g.signedDataValidator={name:"SignedData",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:u.Class.UNIVERSAL,type:u.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},b,{name:"SignedData.Certificates",tagClass:u.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:u.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:u.Class.UNIVERSAL,type:u.Type.SET,capture:"signerInfos",optional:!0,value:[{name:"SignerInfo",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:u.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:u.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:u.Class.UNIVERSAL,type:u.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:u.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]}]}]},g.recipientInfoValidator={name:"RecipientInfo",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:u.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:u.Class.UNIVERSAL,type:u.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},9709:(J,G,N)=>{var h=N(8659);N(4747),N(730),N(8365),function(){if(h.prime)J.exports=h.prime;else{var u=J.exports=h.prime=h.prime||{},g=h.jsbn.BigInteger,b=[6,4,2,4,2,4,6,2],w=new g(null);w.fromInt(30);var v=function(y,f){return y|f};u.generateProbablePrime=function(y,f,C){"function"==typeof f&&(C=f,f={});var A=(f=f||{}).algorithm||"PRIMEINC";"string"==typeof A&&(A={name:A}),A.options=A.options||{};var P=f.prng||h.random;if("PRIMEINC"===A.name)return function l(y,f,C,A){return"workers"in C?function _(y,f,C,A){if(typeof Worker>"u")return p(y,f,C,A);var P=I(y,f),D=C.workers,x=C.workLoad||100,M=30*x/8,B=C.workerScript||"forge/prime.worker.js";if(-1===D)return h.util.estimateCores(function(z,S){z&&(S=2),D=S-1,F()});function F(){D=Math.max(1,D);for(var z=[],S=0;Sy&&(P=I(y,f));var te=P.toString(16);j.target.postMessage({hex:te,workLoad:x}),P.dAddOffset(M,0)}}}F()}(y,f,C,A):p(y,f,C,A)}(y,{nextBytes:function(x){for(var M=P.getBytesSync(x.length),B=0;Bf&&(y=I(f,C)),y.isProbablePrime(P))return x(null,y);y.dAddOffset(b[A++%8],0)}while(D<0||+new Date-M{var h=N(8659);N(4747);var u=null;h.util.isNodejs&&!h.options.usePureJavaScript&&!process.versions["node-webkit"]&&(u=N(5819)),(J.exports=h.prng=h.prng||{}).create=function(b){for(var w={plugin:b,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},v=b.md,l=new Array(32),p=0;p<32;++p)l[p]=v.create();function _(){if(w.pools[0].messageLength>=32)return I();w.collect(w.seedFileSync(32-w.pools[0].messageLength<<5)),I()}function I(){w.reseeds=4294967295===w.reseeds?0:w.reseeds+1;var y=w.plugin.md.create();y.update(w.keyBytes);for(var f=1,C=0;C<32;++C)w.reseeds%f==0&&(y.update(w.pools[C].digest().getBytes()),w.pools[C].start()),f<<=1;w.keyBytes=y.digest().getBytes(),y.start(),y.update(w.keyBytes);var A=y.digest().getBytes();w.key=w.plugin.formatKey(w.keyBytes),w.seed=w.plugin.formatSeed(A),w.generated=0}function E(y){var f=null,C=h.util.globalScope,A=C.crypto||C.msCrypto;A&&A.getRandomValues&&(f=function(O){return A.getRandomValues(O)});var P=h.util.createBuffer();if(f)for(;P.length()>16)))<<16,S=4294967295&(F=(2147483647&(F+=B>>15))+(F>>31)),M=0;M<3;++M)z=S>>>(M<<3),z^=Math.floor(256*Math.random()),P.putByte(255&z);return P.getBytes(y)}return w.pools=l,w.pool=0,w.generate=function(y,f){if(!f)return w.generateSync(y);var C=w.plugin.cipher,A=w.plugin.increment,P=w.plugin.formatKey,D=w.plugin.formatSeed,x=h.util.createBuffer();w.key=null,function M(B){if(B)return f(B);if(x.length()>=y)return f(null,x.getBytes(y));if(w.generated>1048575&&(w.key=null),null===w.key)return h.util.nextTick(function(){!function d(y){if(w.pools[0].messageLength>=32)return I(),y();w.seedFile(32-w.pools[0].messageLength<<5,function(C,A){if(C)return y(C);w.collect(A),I(),y()})}(M)});var F=C(w.key,w.seed);w.generated+=F.length,x.putBytes(F),w.key=P(C(w.key,A(w.seed))),w.seed=D(C(w.key,w.seed)),h.util.setImmediate(M)}()},w.generateSync=function(y){var f=w.plugin.cipher,C=w.plugin.increment,A=w.plugin.formatKey,P=w.plugin.formatSeed;w.key=null;for(var D=h.util.createBuffer();D.length()1048575&&(w.key=null),null===w.key&&_();var x=f(w.key,w.seed);w.generated+=x.length,D.putBytes(x),w.key=A(f(w.key,C(w.seed))),w.seed=P(f(w.key,w.seed))}return D.getBytes(y)},u?(w.seedFile=function(y,f){u.randomBytes(y,function(C,A){if(C)return f(C);f(null,A.toString())})},w.seedFileSync=function(y){return u.randomBytes(y).toString()}):(w.seedFile=function(y,f){try{f(null,E(y))}catch(C){f(C)}},w.seedFileSync=E),w.collect=function(y){for(var f=y.length,C=0;C>A&255);w.collect(C)},w.registerWorker=function(y){y===self?w.seedFile=function(C,A){self.addEventListener("message",function P(D){var x=D.data;x.forge&&x.forge.prng&&(self.removeEventListener("message",P),A(x.forge.prng.err,x.forge.prng.bytes))}),self.postMessage({forge:{prng:{needed:C}}})}:y.addEventListener("message",function(C){var A=C.data;A.forge&&A.forge.prng&&w.seedFile(A.forge.prng.needed,function(P,D){y.postMessage({forge:{prng:{err:P,bytes:D}}})})})},w}},7256:(J,G,N)=>{var h=N(8659);N(8365),N(4747),(J.exports=h.pss=h.pss||{}).create=function(g){3===arguments.length&&(g={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var p,b=g.md,w=g.mgf,v=b.digestLength,l=g.salt||null;if("string"==typeof l&&(l=h.util.createBuffer(l)),"saltLength"in g)p=g.saltLength;else{if(null===l)throw new Error("Salt length not specified or specific salt not given.");p=l.length()}if(null!==l&&l.length()!==p)throw new Error("Given salt length does not match length of given salt.");var d=g.prng||h.random,_={encode:function(I,E){var y,P,f=E-1,C=Math.ceil(f/8),A=I.digest().getBytes();if(C>8*C-f&255;return(S=String.fromCharCode(S.charCodeAt(0)&~O)+S.substr(1))+x+String.fromCharCode(188)},verify:function(I,E,y){var f,C=y-1,A=Math.ceil(C/8);if(E=E.substr(-A),A>8*A-C&255;if(0!=(D.charCodeAt(0)&M))throw new Error("Bits beyond keysize not zero as expected.");var B=w.generate(x,P),F="";for(f=0;f{var h=N(8659);N(1298),N(1594),N(4473),N(4747),h.random&&h.random.getBytes?J.exports=h.random:function(u){var g={},b=new Array(4),w=h.util.createBuffer();function v(){var y=h.prng.create(g);return y.getBytes=function(f,C){return y.generate(f,C)},y.getBytesSync=function(f){return y.generate(f)},y}g.formatKey=function(y){var f=h.util.createBuffer(y);return(y=new Array(4))[0]=f.getInt32(),y[1]=f.getInt32(),y[2]=f.getInt32(),y[3]=f.getInt32(),h.aes._expandKey(y,!1)},g.formatSeed=function(y){var f=h.util.createBuffer(y);return(y=new Array(4))[0]=f.getInt32(),y[1]=f.getInt32(),y[2]=f.getInt32(),y[3]=f.getInt32(),y},g.cipher=function(y,f){return h.aes._updateBlock(y,f,b,!1),w.putInt32(b[0]),w.putInt32(b[1]),w.putInt32(b[2]),w.putInt32(b[3]),w.getBytes()},g.increment=function(y){return++y[3],y},g.md=h.md.sha256;var l=v(),p=null,d=h.util.globalScope,_=d.crypto||d.msCrypto;if(_&&_.getRandomValues&&(p=function(y){return _.getRandomValues(y)}),h.options.usePureJavaScript||!h.util.isNodejs&&!p){if(typeof window>"u"||window,l.collectInt(+new Date,32),typeof navigator<"u"){var I="";for(var E in navigator)try{"string"==typeof navigator[E]&&(I+=navigator[E])}catch{}l.collect(I),I=null}u&&(u().mousemove(function(y){l.collectInt(y.clientX,16),l.collectInt(y.clientY,16)}),u().keypress(function(y){l.collectInt(y.charCode,8)}))}if(h.random)for(var E in l)h.random[E]=l[E];else h.random=l;h.random.createInstance=v,J.exports=h.random}(typeof jQuery<"u"?jQuery:null)},209:(J,G,N)=>{var h=N(8659);N(4747);var u=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],g=[1,2,3,5],b=function(l,p){return l<>16-p},w=function(l,p){return(65535&l)>>p|l<<16-p&65535};J.exports=h.rc2=h.rc2||{},h.rc2.expandKey=function(l,p){"string"==typeof l&&(l=h.util.createBuffer(l)),p=p||128;var f,d=l,_=l.length(),I=p,E=Math.ceil(I/8),y=255>>(7&I);for(f=_;f<128;f++)d.putByte(u[d.at(f-1)+d.at(f-_)&255]);for(d.setAt(128-E,u[d.at(128-E)&y]),f=127-E;f>=0;f--)d.setAt(f,u[d.at(f+1)^d.at(f+E)]);return d};var v=function(l,p,d){var f,C,A,P,_=!1,I=null,E=null,y=null,D=[];for(l=h.rc2.expandKey(l,p),A=0;A<64;A++)D.push(l.getInt16Le());d?(f=function(B){for(A=0;A<4;A++)B[A]+=D[P]+(B[(A+3)%4]&B[(A+2)%4])+(~B[(A+3)%4]&B[(A+1)%4]),B[A]=b(B[A],g[A]),P++},C=function(B){for(A=0;A<4;A++)B[A]+=D[63&B[(A+3)%4]]}):(f=function(B){for(A=3;A>=0;A--)B[A]=w(B[A],g[A]),B[A]-=D[P]+(B[(A+3)%4]&B[(A+2)%4])+(~B[(A+3)%4]&B[(A+1)%4]),P--},C=function(B){for(A=3;A>=0;A--)B[A]-=D[63&B[(A+3)%4]]});var x=function(B){var F=[];for(A=0;A<4;A++){var z=I.getInt16Le();null!==y&&(d?z^=y.getInt16Le():y.putInt16Le(z)),F.push(65535&z)}P=d?0:63;for(var S=0;S=8;)x([[5,f],[1,C],[6,f],[1,C],[5,f]])},finish:function(B){var F=!0;if(d)if(B)F=B(8,I,!d);else{var z=8===I.length()?8:8-I.length();I.fillWithByte(z,z)}if(F&&(_=!0,M.update()),!d&&(F=0===I.length()))if(B)F=B(8,E,!d);else{var S=E.length(),O=E.at(S-1);O>S?F=!1:E.truncate(O)}return F}}};h.rc2.startEncrypting=function(l,p,d){var _=h.rc2.createEncryptionCipher(l,128);return _.start(p,d),_},h.rc2.createEncryptionCipher=function(l,p){return v(l,p,!0)},h.rc2.startDecrypting=function(l,p,d){var _=h.rc2.createDecryptionCipher(l,128);return _.start(p,d),_},h.rc2.createDecryptionCipher=function(l,p){return v(l,p,!1)}},5517:(J,G,N)=>{var h=N(8659);if(N(7791),N(730),N(6078),N(7246),N(9709),N(8365),N(4747),typeof u>"u")var u=h.jsbn.BigInteger;var g=h.util.isNodejs?N(5819):null,b=h.asn1,w=h.util;h.pki=h.pki||{},J.exports=h.pki.rsa=h.rsa=h.rsa||{};var v=h.pki,l=[6,4,2,4,2,4,6,2],p={name:"PrivateKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},d={name:"RSAPrivateKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},_={name:"RSAPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},I=h.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},E={name:"DigestInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:b.Class.UNIVERSAL,type:b.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},y=function(L){if(!(L.algorithm in v.oids)){var re=new Error("Unknown message digest algorithm.");throw re.algorithm=L.algorithm,re}var $=b.oidToDer(v.oids[L.algorithm]).getBytes(),te=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[]),Z=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[]);Z.value.push(b.create(b.Class.UNIVERSAL,b.Type.OID,!1,$)),Z.value.push(b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,""));var q=b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,L.digest().getBytes());return te.value.push(Z),te.value.push(q),b.toDer(te).getBytes()},f=function(L,j,re){if(re)return L.modPow(j.e,j.n);if(!j.p||!j.q)return L.modPow(j.d,j.n);var $;j.dP||(j.dP=j.d.mod(j.p.subtract(u.ONE))),j.dQ||(j.dQ=j.d.mod(j.q.subtract(u.ONE))),j.qInv||(j.qInv=j.q.modInverse(j.p));do{$=new u(h.util.bytesToHex(h.random.getBytes(j.n.bitLength()/8)),16)}while($.compareTo(j.n)>=0||!$.gcd(j.n).equals(u.ONE));for(var te=(L=L.multiply($.modPow(j.e,j.n)).mod(j.n)).mod(j.p).modPow(j.dP,j.p),Z=L.mod(j.q).modPow(j.dQ,j.q);te.compareTo(Z)<0;)te=te.add(j.p);var q=te.subtract(Z).multiply(j.qInv).mod(j.p).multiply(j.q).add(Z);return q.multiply($.modInverse(j.n)).mod(j.n)};function C(L,j,re){var $=h.util.createBuffer(),te=Math.ceil(j.n.bitLength()/8);if(L.length>te-11){var Z=new Error("Message is too long for PKCS#1 v1.5 padding.");throw Z.length=L.length,Z.max=te-11,Z}$.putByte(0),$.putByte(re);var ne,q=te-3-L.length;if(0===re||1===re){ne=0===re?0:255;for(var oe=0;oe0;){var de=0,pe=h.random.getBytes(q);for(oe=0;oe"u")throw new Error("Encryption block is invalid.");var oe=0;if(0===ne){oe=te-3-$;for(var de=0;de1;){if(255!==Z.getByte()){--Z.read;break}++oe}else if(2===ne)for(oe=0;Z.length()>1;){if(0===Z.getByte()){--Z.read;break}++oe}if(0!==Z.getByte()||oe!==te-3-Z.length())throw new Error("Encryption block is invalid.");return Z.getBytes()}function P(L,j,re){"function"==typeof j&&(re=j,j={});var $={algorithm:{name:(j=j||{}).algorithm||"PRIMEINC",options:{workers:j.workers||2,workLoad:j.workLoad||100,workerScript:j.workerScript}}};function te(){Z(L.pBits,function(ne,oe){return ne?re(ne):(L.p=oe,null!==L.q?q(ne,L.q):void Z(L.qBits,q))})}function Z(ne,oe){h.prime.generateProbablePrime(ne,$,oe)}function q(ne,oe){if(ne)return re(ne);if(L.q=oe,L.p.compareTo(L.q)<0){var de=L.p;L.p=L.q,L.q=de}if(0!==L.p.subtract(u.ONE).gcd(L.e).compareTo(u.ONE))return L.p=null,void te();if(0!==L.q.subtract(u.ONE).gcd(L.e).compareTo(u.ONE))return L.q=null,void Z(L.qBits,q);if(L.p1=L.p.subtract(u.ONE),L.q1=L.q.subtract(u.ONE),L.phi=L.p1.multiply(L.q1),0!==L.phi.gcd(L.e).compareTo(u.ONE))return L.p=L.q=null,void te();if(L.n=L.p.multiply(L.q),L.n.bitLength()!==L.bits)return L.q=null,void Z(L.qBits,q);var pe=L.e.modInverse(L.phi);L.keys={privateKey:v.rsa.setPrivateKey(L.n,L.e,pe,L.p,L.q,pe.mod(L.p1),pe.mod(L.q1),L.q.modInverse(L.p)),publicKey:v.rsa.setPublicKey(L.n,L.e)},re(null,L.keys)}"prng"in j&&($.prng=j.prng),te()}function D(L){var j=L.toString(16);j[0]>="8"&&(j="00"+j);var re=h.util.hexToBytes(j);return re.length>1&&(0===re.charCodeAt(0)&&0==(128&re.charCodeAt(1))||255===re.charCodeAt(0)&&128==(128&re.charCodeAt(1)))?re.substr(1):re}function x(L){return L<=100?27:L<=150?18:L<=200?15:L<=250?12:L<=300?9:L<=350?8:L<=400?7:L<=500?6:L<=600?5:L<=800?4:L<=1250?3:2}function M(L){return h.util.isNodejs&&"function"==typeof g[L]}function B(L){return typeof w.globalScope<"u"&&"object"==typeof w.globalScope.crypto&&"object"==typeof w.globalScope.crypto.subtle&&"function"==typeof w.globalScope.crypto.subtle[L]}function F(L){return typeof w.globalScope<"u"&&"object"==typeof w.globalScope.msCrypto&&"object"==typeof w.globalScope.msCrypto.subtle&&"function"==typeof w.globalScope.msCrypto.subtle[L]}function z(L){for(var j=h.util.hexToBytes(L.toString(16)),re=new Uint8Array(j.length),$=0;$0;)de.putByte(0),--pe;return de.putBytes(h.util.hexToBytes(oe)),de.getBytes()},v.rsa.decrypt=function(L,j,re,$){var te=Math.ceil(j.n.bitLength()/8);if(L.length!==te){var Z=new Error("Encrypted message length is invalid.");throw Z.length=L.length,Z.expected=te,Z}var q=new u(h.util.createBuffer(L).toHex(),16);if(q.compareTo(j.n)>=0)throw new Error("Encrypted message is invalid.");for(var oe=f(q,j,re).toString(16),de=h.util.createBuffer(),pe=te-Math.ceil(oe.length/2);pe>0;)de.putByte(0),--pe;return de.putBytes(h.util.hexToBytes(oe)),!1!==$?A(de.getBytes(),j,re):de.getBytes()},v.rsa.createKeyPairGenerationState=function(L,j,re){"string"==typeof L&&(L=parseInt(L,10)),L=L||2048;var q,$=(re=re||{}).prng||h.random,te={nextBytes:function(ne){for(var oe=$.getBytesSync(ne.length),de=0;de>1,pBits:L-(L>>1),pqState:0,num:null,keys:null}).e.fromInt(q.eInt),q},v.rsa.stepKeyPairGenerationState=function(L,j){"algorithm"in L||(L.algorithm="PRIMEINC");var re=new u(null);re.fromInt(30);for(var q,$=0,te=function(ke,Se){return ke|Se},Z=+new Date,ne=0;null===L.keys&&(j<=0||neoe?L.pqState=0:L.num.isProbablePrime(x(L.num.bitLength()))?++L.pqState:L.num.dAddOffset(l[$++%8],0):2===L.pqState?L.pqState=0===L.num.subtract(u.ONE).gcd(L.e).compareTo(u.ONE)?3:0:3===L.pqState&&(L.pqState=0,null===L.p?L.p=L.num:L.q=L.num,null!==L.p&&null!==L.q&&++L.state,L.num=null)}else if(1===L.state)L.p.compareTo(L.q)<0&&(L.num=L.p,L.p=L.q,L.q=L.num),++L.state;else if(2===L.state)L.p1=L.p.subtract(u.ONE),L.q1=L.q.subtract(u.ONE),L.phi=L.p1.multiply(L.q1),++L.state;else if(3===L.state)0===L.phi.gcd(L.e).compareTo(u.ONE)?++L.state:(L.p=null,L.q=null,L.state=0);else if(4===L.state)L.n=L.p.multiply(L.q),L.n.bitLength()===L.bits?++L.state:(L.q=null,L.state=0);else if(5===L.state){var pe=L.e.modInverse(L.phi);L.keys={privateKey:v.rsa.setPrivateKey(L.n,L.e,pe,L.p,L.q,pe.mod(L.p1),pe.mod(L.q1),L.q.modInverse(L.p)),publicKey:v.rsa.setPublicKey(L.n,L.e)}}ne+=(q=+new Date)-Z,Z=q}return null!==L.keys},v.rsa.generateKeyPair=function(L,j,re,$){if(1===arguments.length?"object"==typeof L?(re=L,L=void 0):"function"==typeof L&&($=L,L=void 0):2===arguments.length?"number"==typeof L?"function"==typeof j?($=j,j=void 0):"number"!=typeof j&&(re=j,j=void 0):(re=L,$=j,L=void 0,j=void 0):3===arguments.length&&("number"==typeof j?"function"==typeof re&&($=re,re=void 0):($=re,re=j,j=void 0)),re=re||{},void 0===L&&(L=re.bits||2048),void 0===j&&(j=re.e||65537),!h.options.usePureJavaScript&&!re.prng&&L>=256&&L<=16384&&(65537===j||3===j))if($){if(M("generateKeyPair"))return g.generateKeyPair("rsa",{modulusLength:L,publicExponent:j,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(ne,oe,de){if(ne)return $(ne);$(null,{privateKey:v.privateKeyFromPem(de),publicKey:v.publicKeyFromPem(oe)})});if(B("generateKey")&&B("exportKey"))return w.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:L,publicExponent:z(j),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(ne){return w.globalScope.crypto.subtle.exportKey("pkcs8",ne.privateKey)}).then(void 0,function(ne){$(ne)}).then(function(ne){if(ne){var oe=v.privateKeyFromAsn1(b.fromDer(h.util.createBuffer(ne)));$(null,{privateKey:oe,publicKey:v.setRsaPublicKey(oe.n,oe.e)})}});if(F("generateKey")&&F("exportKey")){var te=w.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:L,publicExponent:z(j),hash:{name:"SHA-256"}},!0,["sign","verify"]);return te.oncomplete=function(ne){var de=w.globalScope.msCrypto.subtle.exportKey("pkcs8",ne.target.result.privateKey);de.oncomplete=function(pe){var Se=v.privateKeyFromAsn1(b.fromDer(h.util.createBuffer(pe.target.result)));$(null,{privateKey:Se,publicKey:v.setRsaPublicKey(Se.n,Se.e)})},de.onerror=function(pe){$(pe)}},void(te.onerror=function(ne){$(ne)})}}else if(M("generateKeyPairSync")){var Z=g.generateKeyPairSync("rsa",{modulusLength:L,publicExponent:j,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:v.privateKeyFromPem(Z.privateKey),publicKey:v.publicKeyFromPem(Z.publicKey)}}var q=v.rsa.createKeyPairGenerationState(L,j,re);if(!$)return v.rsa.stepKeyPairGenerationState(q,0),q.keys;P(q,re,$)},v.setRsaPublicKey=v.rsa.setPublicKey=function(L,j){var re={n:L,e:j,encrypt:function($,te,Z){if("string"==typeof te?te=te.toUpperCase():void 0===te&&(te="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===te)te={encode:function(ne,oe,de){return C(ne,oe,2).getBytes()}};else if("RSA-OAEP"===te||"RSAES-OAEP"===te)te={encode:function(ne,oe){return h.pkcs1.encode_rsa_oaep(oe,ne,Z)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(te))te={encode:function(ne){return ne}};else if("string"==typeof te)throw new Error('Unsupported encryption scheme: "'+te+'".');var q=te.encode($,re,!0);return v.rsa.encrypt(q,re,!0)},verify:function($,te,Z,q){"string"==typeof Z?Z=Z.toUpperCase():void 0===Z&&(Z="RSASSA-PKCS1-V1_5"),void 0===q&&(q={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in q||(q._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===Z?Z={verify:function(oe,de){de=A(de,re,!0);var pe=b.fromDer(de,{parseAllBytes:q._parseAllDigestBytes}),ke={},Se=[];if(!b.validate(pe,E,ke,Se))throw(Pe=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=Se,Pe;var Pe,we=b.derToOid(ke.algorithmIdentifier);if(we!==h.oids.md2&&we!==h.oids.md5&&we!==h.oids.sha1&&we!==h.oids.sha224&&we!==h.oids.sha256&&we!==h.oids.sha384&&we!==h.oids.sha512&&we!==h.oids["sha512-224"]&&we!==h.oids["sha512-256"])throw(Pe=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=we,Pe;if((we===h.oids.md2||we===h.oids.md5)&&!("parameters"in ke))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return oe===ke.digest}}:("NONE"===Z||"NULL"===Z||null===Z)&&(Z={verify:function(oe,de){return oe===A(de,re,!0)}});var ne=v.rsa.decrypt(te,re,!0,!1);return Z.verify($,ne,re.n.bitLength())}};return re},v.setRsaPrivateKey=v.rsa.setPrivateKey=function(L,j,re,$,te,Z,q,ne){var oe={n:L,e:j,d:re,p:$,q:te,dP:Z,dQ:q,qInv:ne,decrypt:function(de,pe,ke){"string"==typeof pe?pe=pe.toUpperCase():void 0===pe&&(pe="RSAES-PKCS1-V1_5");var Se=v.rsa.decrypt(de,oe,!1,!1);if("RSAES-PKCS1-V1_5"===pe)pe={decode:A};else if("RSA-OAEP"===pe||"RSAES-OAEP"===pe)pe={decode:function(Pe,we){return h.pkcs1.decode_rsa_oaep(we,Pe,ke)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(pe))throw new Error('Unsupported encryption scheme: "'+pe+'".');pe={decode:function(Pe){return Pe}}}return pe.decode(Se,oe,!1)},sign:function(de,pe){var ke=!1;"string"==typeof pe&&(pe=pe.toUpperCase()),void 0===pe||"RSASSA-PKCS1-V1_5"===pe?(pe={encode:y},ke=1):("NONE"===pe||"NULL"===pe||null===pe)&&(pe={encode:function(){return de}},ke=1);var Se=pe.encode(de,oe.n.bitLength());return v.rsa.encrypt(Se,oe,ke)}};return oe},v.wrapRsaPrivateKey=function(L){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,b.integerToDer(0).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(v.oids.rsaEncryption).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,"")]),b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,b.toDer(L).getBytes())])},v.privateKeyFromAsn1=function(L){var te,Z,q,ne,oe,de,pe,ke,j={},re=[];if(b.validate(L,p,j,re)&&(L=b.fromDer(h.util.createBuffer(j.privateKey))),!b.validate(L,d,j={},re=[])){var $=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw $.errors=re,$}return te=h.util.createBuffer(j.privateKeyModulus).toHex(),Z=h.util.createBuffer(j.privateKeyPublicExponent).toHex(),q=h.util.createBuffer(j.privateKeyPrivateExponent).toHex(),ne=h.util.createBuffer(j.privateKeyPrime1).toHex(),oe=h.util.createBuffer(j.privateKeyPrime2).toHex(),de=h.util.createBuffer(j.privateKeyExponent1).toHex(),pe=h.util.createBuffer(j.privateKeyExponent2).toHex(),ke=h.util.createBuffer(j.privateKeyCoefficient).toHex(),v.setRsaPrivateKey(new u(te,16),new u(Z,16),new u(q,16),new u(ne,16),new u(oe,16),new u(de,16),new u(pe,16),new u(ke,16))},v.privateKeyToAsn1=v.privateKeyToRSAPrivateKey=function(L){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,b.integerToDer(0).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.n)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.e)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.d)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.p)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.q)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.dP)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.dQ)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.qInv))])},v.publicKeyFromAsn1=function(L){var j={},re=[];if(b.validate(L,I,j,re)){var te,$=b.derToOid(j.publicKeyOid);if($!==v.oids.rsaEncryption)throw(te=new Error("Cannot read public key. Unknown OID.")).oid=$,te;L=j.rsaPublicKey}if(!b.validate(L,_,j,re=[]))throw(te=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=re,te;var Z=h.util.createBuffer(j.publicKeyModulus).toHex(),q=h.util.createBuffer(j.publicKeyExponent).toHex();return v.setRsaPublicKey(new u(Z,16),new u(q,16))},v.publicKeyToAsn1=v.publicKeyToSubjectPublicKeyInfo=function(L){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(v.oids.rsaEncryption).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,"")]),b.create(b.Class.UNIVERSAL,b.Type.BITSTRING,!1,[v.publicKeyToRSAPublicKey(L)])])},v.publicKeyToRSAPublicKey=function(L){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.n)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,D(L.e))])}},7690:(J,G,N)=>{var h=N(8659);N(979),N(4747);var u=J.exports=h.sha1=h.sha1||{};h.md.sha1=h.md.algorithms.sha1=u,u.create=function(){b||function w(){g=String.fromCharCode(128),g+=h.util.fillString(String.fromCharCode(0),64),b=!0}();var l=null,p=h.util.createBuffer(),d=new Array(80),_={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){_.messageLength=0,_.fullMessageLength=_.messageLength64=[];for(var I=_.messageLengthSize/4,E=0;E>>0,y>>>0];for(var f=_.fullMessageLength.length-1;f>=0;--f)_.fullMessageLength[f]+=y[1],y[1]=y[0]+(_.fullMessageLength[f]/4294967296>>>0),_.fullMessageLength[f]=_.fullMessageLength[f]>>>0,y[0]=y[1]/4294967296>>>0;return p.putBytes(I),v(l,d,p),(p.read>2048||0===p.length())&&p.compact(),_},_.digest=function(){var I=h.util.createBuffer();I.putBytes(p.bytes()),I.putBytes(g.substr(0,_.blockLength-(_.fullMessageLength[_.fullMessageLength.length-1]+_.messageLengthSize&_.blockLength-1)));for(var f,A=8*_.fullMessageLength[0],P=0;P<_.fullMessageLength.length-1;++P)I.putInt32((A+=(f=8*_.fullMessageLength[P+1])/4294967296>>>0)>>>0),A=f>>>0;I.putInt32(A);var D={h0:l.h0,h1:l.h1,h2:l.h2,h3:l.h3,h4:l.h4};v(D,d,I);var x=h.util.createBuffer();return x.putInt32(D.h0),x.putInt32(D.h1),x.putInt32(D.h2),x.putInt32(D.h3),x.putInt32(D.h4),x},_};var g=null,b=!1;function v(l,p,d){for(var _,I,E,y,f,C,P,D=d.length();D>=64;){for(I=l.h0,E=l.h1,y=l.h2,f=l.h3,C=l.h4,P=0;P<16;++P)_=d.getInt32(),p[P]=_,_=(I<<5|I>>>27)+(f^E&(y^f))+C+1518500249+_,C=f,f=y,y=(E<<30|E>>>2)>>>0,E=I,I=_;for(;P<20;++P)p[P]=_=(_=p[P-3]^p[P-8]^p[P-14]^p[P-16])<<1|_>>>31,_=(I<<5|I>>>27)+(f^E&(y^f))+C+1518500249+_,C=f,f=y,y=(E<<30|E>>>2)>>>0,E=I,I=_;for(;P<32;++P)p[P]=_=(_=p[P-3]^p[P-8]^p[P-14]^p[P-16])<<1|_>>>31,_=(I<<5|I>>>27)+(E^y^f)+C+1859775393+_,C=f,f=y,y=(E<<30|E>>>2)>>>0,E=I,I=_;for(;P<40;++P)p[P]=_=(_=p[P-6]^p[P-16]^p[P-28]^p[P-32])<<2|_>>>30,_=(I<<5|I>>>27)+(E^y^f)+C+1859775393+_,C=f,f=y,y=(E<<30|E>>>2)>>>0,E=I,I=_;for(;P<60;++P)p[P]=_=(_=p[P-6]^p[P-16]^p[P-28]^p[P-32])<<2|_>>>30,_=(I<<5|I>>>27)+(E&y|f&(E^y))+C+2400959708+_,C=f,f=y,y=(E<<30|E>>>2)>>>0,E=I,I=_;for(;P<80;++P)p[P]=_=(_=p[P-6]^p[P-16]^p[P-28]^p[P-32])<<2|_>>>30,_=(I<<5|I>>>27)+(E^y^f)+C+3395469782+_,C=f,f=y,y=(E<<30|E>>>2)>>>0,E=I,I=_;l.h0=l.h0+I|0,l.h1=l.h1+E|0,l.h2=l.h2+y|0,l.h3=l.h3+f|0,l.h4=l.h4+C|0,D-=64}}},1594:(J,G,N)=>{var h=N(8659);N(979),N(4747);var u=J.exports=h.sha256=h.sha256||{};h.md.sha256=h.md.algorithms.sha256=u,u.create=function(){b||function v(){g=String.fromCharCode(128),g+=h.util.fillString(String.fromCharCode(0),64),w=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],b=!0}();var p=null,d=h.util.createBuffer(),_=new Array(64),I={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){I.messageLength=0,I.fullMessageLength=I.messageLength64=[];for(var E=I.messageLengthSize/4,y=0;y>>0,f>>>0];for(var C=I.fullMessageLength.length-1;C>=0;--C)I.fullMessageLength[C]+=f[1],f[1]=f[0]+(I.fullMessageLength[C]/4294967296>>>0),I.fullMessageLength[C]=I.fullMessageLength[C]>>>0,f[0]=f[1]/4294967296>>>0;return d.putBytes(E),l(p,_,d),(d.read>2048||0===d.length())&&d.compact(),I},I.digest=function(){var E=h.util.createBuffer();E.putBytes(d.bytes()),E.putBytes(g.substr(0,I.blockLength-(I.fullMessageLength[I.fullMessageLength.length-1]+I.messageLengthSize&I.blockLength-1)));for(var C,P=8*I.fullMessageLength[0],D=0;D>>0)>>>0),P=C>>>0;E.putInt32(P);var x={h0:p.h0,h1:p.h1,h2:p.h2,h3:p.h3,h4:p.h4,h5:p.h5,h6:p.h6,h7:p.h7};l(x,_,E);var M=h.util.createBuffer();return M.putInt32(x.h0),M.putInt32(x.h1),M.putInt32(x.h2),M.putInt32(x.h3),M.putInt32(x.h4),M.putInt32(x.h5),M.putInt32(x.h6),M.putInt32(x.h7),M},I};var g=null,b=!1,w=null;function l(p,d,_){for(var I,E,A,P,D,x,M,B,F,z,S,O,H=_.length();H>=64;){for(P=0;P<16;++P)d[P]=_.getInt32();for(;P<64;++P)d[P]=(I=((I=d[P-2])>>>17|I<<15)^(I>>>19|I<<13)^I>>>10)+d[P-7]+(E=((E=d[P-15])>>>7|E<<25)^(E>>>18|E<<14)^E>>>3)+d[P-16]|0;for(D=p.h0,x=p.h1,M=p.h2,B=p.h3,F=p.h4,z=p.h5,S=p.h6,O=p.h7,P=0;P<64;++P)A=D&x|M&(D^x),I=O+((F>>>6|F<<26)^(F>>>11|F<<21)^(F>>>25|F<<7))+(S^F&(z^S))+w[P]+d[P],O=S,S=z,z=F,F=B+I>>>0,B=M,M=x,x=D,D=I+(E=((D>>>2|D<<30)^(D>>>13|D<<19)^(D>>>22|D<<10))+A)>>>0;p.h0=p.h0+D|0,p.h1=p.h1+x|0,p.h2=p.h2+M|0,p.h3=p.h3+B|0,p.h4=p.h4+F|0,p.h5=p.h5+z|0,p.h6=p.h6+S|0,p.h7=p.h7+O|0,H-=64}}},8985:(J,G,N)=>{var h=N(8659);N(979),N(4747);var u=J.exports=h.sha512=h.sha512||{};h.md.sha512=h.md.algorithms.sha512=u;var g=h.sha384=h.sha512.sha384=h.sha512.sha384||{};g.create=function(){return u.create("SHA-384")},h.md.sha384=h.md.algorithms.sha384=g,h.sha512.sha256=h.sha512.sha256||{create:function(){return u.create("SHA-512/256")}},h.md["sha512/256"]=h.md.algorithms["sha512/256"]=h.sha512.sha256,h.sha512.sha224=h.sha512.sha224||{create:function(){return u.create("SHA-512/224")}},h.md["sha512/224"]=h.md.algorithms["sha512/224"]=h.sha512.sha224,u.create=function(_){if(w||function p(){b=String.fromCharCode(128),b+=h.util.fillString(String.fromCharCode(0),128),v=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],(l={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],l["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],l["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],l["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],w=!0}(),typeof _>"u"&&(_="SHA-512"),!(_ in l))throw new Error("Invalid SHA-512 algorithm: "+_);for(var I=l[_],E=null,y=h.util.createBuffer(),f=new Array(80),C=0;C<80;++C)f[C]=new Array(2);var A=64;switch(_){case"SHA-384":A=48;break;case"SHA-512/256":A=32;break;case"SHA-512/224":A=28}var P={algorithm:_.replace("-","").toLowerCase(),blockLength:128,digestLength:A,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){P.messageLength=0,P.fullMessageLength=P.messageLength128=[];for(var D=P.messageLengthSize/4,x=0;x>>0,M>>>0];for(var B=P.fullMessageLength.length-1;B>=0;--B)P.fullMessageLength[B]+=M[1],M[1]=M[0]+(P.fullMessageLength[B]/4294967296>>>0),P.fullMessageLength[B]=P.fullMessageLength[B]>>>0,M[0]=M[1]/4294967296>>>0;return y.putBytes(D),d(E,f,y),(y.read>2048||0===y.length())&&y.compact(),P},P.digest=function(){var D=h.util.createBuffer();D.putBytes(y.bytes()),D.putBytes(b.substr(0,P.blockLength-(P.fullMessageLength[P.fullMessageLength.length-1]+P.messageLengthSize&P.blockLength-1)));for(var B,z=8*P.fullMessageLength[0],S=0;S>>0)>>>0),z=B>>>0;D.putInt32(z);var O=new Array(E.length);for(S=0;S=128;){for(we=0;we<16;++we)I[we][0]=E.getInt32()>>>0,I[we][1]=E.getInt32()>>>0;for(;we<80;++we)f=((($e=(Ee=I[we-2])[0])<<13|(K=Ee[1])>>>19)^(K<<3|$e>>>29)^($e<<26|K>>>6))>>>0,I[we][0]=(y=(($e>>>19|K<<13)^(K>>>29|$e<<3)^$e>>>6)>>>0)+(Ce=I[we-7])[0]+(C=((($e=(xe=I[we-15])[0])>>>1|(K=xe[1])<<31)^($e>>>8|K<<24)^$e>>>7)>>>0)+(Ke=I[we-16])[0]+((K=f+Ce[1]+(A=(($e<<31|K>>>1)^($e<<24|K>>>8)^($e<<25|K>>>7))>>>0)+Ke[1])/4294967296>>>0)>>>0,I[we][1]=K>>>0;for(O=_[0][0],H=_[0][1],L=_[1][0],j=_[1][1],re=_[2][0],$=_[2][1],te=_[3][0],Z=_[3][1],q=_[4][0],ne=_[4][1],oe=_[5][0],de=_[5][1],pe=_[6][0],ke=_[6][1],Se=_[7][0],Pe=_[7][1],we=0;we<80;++we)y=Se+(((q>>>14|ne<<18)^(q>>>18|ne<<14)^(ne>>>9|q<<23))>>>0)+((pe^q&(oe^pe))>>>0)+v[we][0]+I[we][0]+((K=Pe+(((q<<18|ne>>>14)^(q<<14|ne>>>18)^(ne<<23|q>>>9))>>>0)+((ke^ne&(de^ke))>>>0)+v[we][1]+I[we][1])/4294967296>>>0)>>>0,f=K>>>0,C=(((O>>>28|H<<4)^(H>>>2|O<<30)^(H>>>7|O<<25))>>>0)+((O&L|re&(O^L))>>>0)+((K=(((O<<4|H>>>28)^(H<<30|O>>>2)^(H<<25|O>>>7))>>>0)+((H&j|$&(H^j))>>>0))/4294967296>>>0)>>>0,A=K>>>0,Se=pe,Pe=ke,pe=oe,ke=de,oe=q,de=ne,q=te+y+((K=Z+f)/4294967296>>>0)>>>0,ne=K>>>0,te=re,Z=$,re=L,$=j,L=O,j=H,O=y+C+((K=f+A)/4294967296>>>0)>>>0,H=K>>>0;_[0][0]=_[0][0]+O+((K=_[0][1]+H)/4294967296>>>0)>>>0,_[0][1]=K>>>0,_[1][0]=_[1][0]+L+((K=_[1][1]+j)/4294967296>>>0)>>>0,_[1][1]=K>>>0,_[2][0]=_[2][0]+re+((K=_[2][1]+$)/4294967296>>>0)>>>0,_[2][1]=K>>>0,_[3][0]=_[3][0]+te+((K=_[3][1]+Z)/4294967296>>>0)>>>0,_[3][1]=K>>>0,_[4][0]=_[4][0]+q+((K=_[4][1]+ne)/4294967296>>>0)>>>0,_[4][1]=K>>>0,_[5][0]=_[5][0]+oe+((K=_[5][1]+de)/4294967296>>>0)>>>0,_[5][1]=K>>>0,_[6][0]=_[6][0]+pe+((K=_[6][1]+ke)/4294967296>>>0)>>>0,_[6][1]=K>>>0,_[7][0]=_[7][0]+Se+((K=_[7][1]+Pe)/4294967296>>>0)>>>0,_[7][1]=K>>>0,We-=128}}},4747:(J,G,N)=>{var h=N(8659),u=N(2020),g=J.exports=h.util=h.util||{};function b(D){if(8!==D&&16!==D&&24!==D&&32!==D)throw new Error("Only 8, 16, 24, or 32 bits supported: "+D)}function w(D){if(this.data="",this.read=0,"string"==typeof D)this.data=D;else if(g.isArrayBuffer(D)||g.isArrayBufferView(D))if(typeof Buffer<"u"&&D instanceof Buffer)this.data=D.toString("binary");else{var x=new Uint8Array(D);try{this.data=String.fromCharCode.apply(null,x)}catch{for(var M=0;M15?(M=Date.now(),z(H)):(x.push(H),1===x.length&&F.setAttribute("a",B=!B))}}g.nextTick=g.setImmediate})(),g.isNodejs=typeof process<"u"&&process.versions&&process.versions.node,g.globalScope=g.isNodejs?global:typeof self>"u"?window:self,g.isArray=Array.isArray||function(D){return"[object Array]"===Object.prototype.toString.call(D)},g.isArrayBuffer=function(D){return typeof ArrayBuffer<"u"&&D instanceof ArrayBuffer},g.isArrayBufferView=function(D){return D&&g.isArrayBuffer(D.buffer)&&void 0!==D.byteLength},g.ByteBuffer=w,g.ByteStringBuffer=w,g.ByteStringBuffer.prototype._optimizeConstructedString=function(D){this._constructedStringLength+=D,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},g.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},g.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},g.ByteStringBuffer.prototype.putByte=function(D){return this.putBytes(String.fromCharCode(D))},g.ByteStringBuffer.prototype.fillWithByte=function(D,x){D=String.fromCharCode(D);for(var M=this.data;x>0;)1&x&&(M+=D),(x>>>=1)>0&&(D+=D);return this.data=M,this._optimizeConstructedString(x),this},g.ByteStringBuffer.prototype.putBytes=function(D){return this.data+=D,this._optimizeConstructedString(D.length),this},g.ByteStringBuffer.prototype.putString=function(D){return this.putBytes(g.encodeUtf8(D))},g.ByteStringBuffer.prototype.putInt16=function(D){return this.putBytes(String.fromCharCode(D>>8&255)+String.fromCharCode(255&D))},g.ByteStringBuffer.prototype.putInt24=function(D){return this.putBytes(String.fromCharCode(D>>16&255)+String.fromCharCode(D>>8&255)+String.fromCharCode(255&D))},g.ByteStringBuffer.prototype.putInt32=function(D){return this.putBytes(String.fromCharCode(D>>24&255)+String.fromCharCode(D>>16&255)+String.fromCharCode(D>>8&255)+String.fromCharCode(255&D))},g.ByteStringBuffer.prototype.putInt16Le=function(D){return this.putBytes(String.fromCharCode(255&D)+String.fromCharCode(D>>8&255))},g.ByteStringBuffer.prototype.putInt24Le=function(D){return this.putBytes(String.fromCharCode(255&D)+String.fromCharCode(D>>8&255)+String.fromCharCode(D>>16&255))},g.ByteStringBuffer.prototype.putInt32Le=function(D){return this.putBytes(String.fromCharCode(255&D)+String.fromCharCode(D>>8&255)+String.fromCharCode(D>>16&255)+String.fromCharCode(D>>24&255))},g.ByteStringBuffer.prototype.putInt=function(D,x){b(x);var M="";do{x-=8,M+=String.fromCharCode(D>>x&255)}while(x>0);return this.putBytes(M)},g.ByteStringBuffer.prototype.putSignedInt=function(D,x){return D<0&&(D+=2<0);return x},g.ByteStringBuffer.prototype.getSignedInt=function(D){var x=this.getInt(D),M=2<=M&&(x-=M<<1),x},g.ByteStringBuffer.prototype.getBytes=function(D){var x;return D?(D=Math.min(this.length(),D),x=this.data.slice(this.read,this.read+D),this.read+=D):0===D?x="":(x=0===this.read?this.data:this.data.slice(this.read),this.clear()),x},g.ByteStringBuffer.prototype.bytes=function(D){return typeof D>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+D)},g.ByteStringBuffer.prototype.at=function(D){return this.data.charCodeAt(this.read+D)},g.ByteStringBuffer.prototype.setAt=function(D,x){return this.data=this.data.substr(0,this.read+D)+String.fromCharCode(x)+this.data.substr(this.read+D+1),this},g.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},g.ByteStringBuffer.prototype.copy=function(){var D=g.createBuffer(this.data);return D.read=this.read,D},g.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},g.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},g.ByteStringBuffer.prototype.truncate=function(D){var x=Math.max(0,this.length()-D);return this.data=this.data.substr(this.read,x),this.read=0,this},g.ByteStringBuffer.prototype.toHex=function(){for(var D="",x=this.read;x=D)return this;x=Math.max(x||this.growSize,D);var M=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),B=new Uint8Array(this.length()+x);return B.set(M),this.data=new DataView(B.buffer),this},g.DataBuffer.prototype.putByte=function(D){return this.accommodate(1),this.data.setUint8(this.write++,D),this},g.DataBuffer.prototype.fillWithByte=function(D,x){this.accommodate(x);for(var M=0;M>8&65535),this.data.setInt8(this.write,D>>16&255),this.write+=3,this},g.DataBuffer.prototype.putInt32=function(D){return this.accommodate(4),this.data.setInt32(this.write,D),this.write+=4,this},g.DataBuffer.prototype.putInt16Le=function(D){return this.accommodate(2),this.data.setInt16(this.write,D,!0),this.write+=2,this},g.DataBuffer.prototype.putInt24Le=function(D){return this.accommodate(3),this.data.setInt8(this.write,D>>16&255),this.data.setInt16(this.write,D>>8&65535,!0),this.write+=3,this},g.DataBuffer.prototype.putInt32Le=function(D){return this.accommodate(4),this.data.setInt32(this.write,D,!0),this.write+=4,this},g.DataBuffer.prototype.putInt=function(D,x){b(x),this.accommodate(x/8);do{x-=8,this.data.setInt8(this.write++,D>>x&255)}while(x>0);return this},g.DataBuffer.prototype.putSignedInt=function(D,x){return b(x),this.accommodate(x/8),D<0&&(D+=2<0);return x},g.DataBuffer.prototype.getSignedInt=function(D){var x=this.getInt(D),M=2<=M&&(x-=M<<1),x},g.DataBuffer.prototype.getBytes=function(D){var x;return D?(D=Math.min(this.length(),D),x=this.data.slice(this.read,this.read+D),this.read+=D):0===D?x="":(x=0===this.read?this.data:this.data.slice(this.read),this.clear()),x},g.DataBuffer.prototype.bytes=function(D){return typeof D>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+D)},g.DataBuffer.prototype.at=function(D){return this.data.getUint8(this.read+D)},g.DataBuffer.prototype.setAt=function(D,x){return this.data.setUint8(D,x),this},g.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},g.DataBuffer.prototype.copy=function(){return new g.DataBuffer(this)},g.DataBuffer.prototype.compact=function(){if(this.read>0){var D=new Uint8Array(this.data.buffer,this.read),x=new Uint8Array(D.byteLength);x.set(D),this.data=new DataView(x),this.write-=this.read,this.read=0}return this},g.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},g.DataBuffer.prototype.truncate=function(D){return this.write=Math.max(0,this.length()-D),this.read=Math.min(this.read,this.write),this},g.DataBuffer.prototype.toHex=function(){for(var D="",x=this.read;x0;)1&x&&(M+=D),(x>>>=1)>0&&(D+=D);return M},g.xorBytes=function(D,x,M){for(var B="",F="",z="",S=0,O=0;M>0;--M,++S)F=D.charCodeAt(S)^x.charCodeAt(S),O>=10&&(B+=z,z="",O=0),z+=String.fromCharCode(F),++O;return B+z},g.hexToBytes=function(D){var x="",M=0;for(!0&D.length&&(M=1,x+=String.fromCharCode(parseInt(D[0],16)));M>24&255)+String.fromCharCode(D>>16&255)+String.fromCharCode(D>>8&255)+String.fromCharCode(255&D)};var p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",d=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],_="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";g.encode64=function(D,x){for(var F,z,S,M="",B="",O=0;O>2),M+=p.charAt((3&F)<<4|z>>4),isNaN(z)?M+="==":(M+=p.charAt((15&z)<<2|S>>6),M+=isNaN(S)?"=":p.charAt(63&S)),x&&M.length>x&&(B+=M.substr(0,x)+"\r\n",M=M.substr(x));return B+M},g.decode64=function(D){D=D.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var M,B,F,z,x="",S=0;S>4),64!==F&&(x+=String.fromCharCode((15&B)<<4|F>>2),64!==z&&(x+=String.fromCharCode((3&F)<<6|z)));return x},g.encodeUtf8=function(D){return unescape(encodeURIComponent(D))},g.decodeUtf8=function(D){return decodeURIComponent(escape(D))},g.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:u.encode,decode:u.decode}},g.binary.raw.encode=function(D){return String.fromCharCode.apply(null,D)},g.binary.raw.decode=function(D,x,M){var B=x;B||(B=new Uint8Array(D.length));for(var F=M=M||0,z=0;z>2),M+=p.charAt((3&F)<<4|z>>4),isNaN(z)?M+="==":(M+=p.charAt((15&z)<<2|S>>6),M+=isNaN(S)?"=":p.charAt(63&S)),x&&M.length>x&&(B+=M.substr(0,x)+"\r\n",M=M.substr(x));return B+M},g.binary.base64.decode=function(D,x,M){var B=x;B||(B=new Uint8Array(3*Math.ceil(D.length/4))),D=D.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var F,z,S,O,H=0,L=M=M||0;H>4,64!==S&&(B[L++]=(15&z)<<4|S>>2,64!==O&&(B[L++]=(3&S)<<6|O));return x?L-M:B.subarray(0,L)},g.binary.base58.encode=function(D,x){return g.binary.baseN.encode(D,_,x)},g.binary.base58.decode=function(D,x){return g.binary.baseN.decode(D,_,x)},g.text={utf8:{},utf16:{}},g.text.utf8.encode=function(D,x,M){D=g.encodeUtf8(D);var B=x;B||(B=new Uint8Array(D.length));for(var F=M=M||0,z=0;z"u"&&(M=["web","flash"]);var F,z=!1,S=null;for(var O in M){F=M[O];try{if("flash"===F||"both"===F){if(null===x[0])throw new Error("Flash local storage not available.");B=D.apply(this,x),z="flash"===F}("web"===F||"both"===F)&&(x[0]=localStorage,B=D.apply(this,x),z=!0)}catch(H){S=H}if(z)break}if(!z)throw S;return B};g.setItem=function(D,x,M,B,F){P(y,arguments,F)},g.getItem=function(D,x,M,B){return P(f,arguments,B)},g.removeItem=function(D,x,M,B){P(C,arguments,B)},g.clearItems=function(D,x,M){P(A,arguments,M)},g.isEmpty=function(D){for(var x in D)if(D.hasOwnProperty(x))return!1;return!0},g.format=function(D){for(var M,B,x=/%./g,F=0,z=[],S=0;M=x.exec(D);){(B=D.substring(S,x.lastIndex-2)).length>0&&z.push(B),S=x.lastIndex;var O=M[0][1];switch(O){case"s":case"o":z.push(F");break;case"%":z.push("%");break;default:z.push("<%"+O+"?>")}}return z.push(D.substring(S)),z.join("")},g.formatNumber=function(D,x,M,B){var F=D,z=isNaN(x=Math.abs(x))?2:x,S=void 0===M?",":M,O=void 0===B?".":B,H=F<0?"-":"",L=parseInt(F=Math.abs(+F||0).toFixed(z),10)+"",j=L.length>3?L.length%3:0;return H+(j?L.substr(0,j)+O:"")+L.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+O)+(z?S+Math.abs(F-L).toFixed(z).slice(2):"")},g.formatSize=function(D){return D>=1073741824?g.formatNumber(D/1073741824,2,".","")+" GiB":D>=1048576?g.formatNumber(D/1048576,2,".","")+" MiB":D>=1024?g.formatNumber(D/1024,0)+" KiB":g.formatNumber(D,0)+" bytes"},g.bytesFromIP=function(D){return-1!==D.indexOf(".")?g.bytesFromIPv4(D):-1!==D.indexOf(":")?g.bytesFromIPv6(D):null},g.bytesFromIPv4=function(D){if(4!==(D=D.split(".")).length)return null;for(var x=g.createBuffer(),M=0;MM[B].end-M[B].start&&(B=M.length-1)):M.push({start:O,end:O})}x.push(z)}if(M.length>0){var H=M[B];H.end-H.start>0&&(x.splice(H.start,H.end-H.start+1,""),0===H.start&&x.unshift(""),7===H.end&&x.push(""))}return x.join(":")},g.estimateCores=function(D,x){if("function"==typeof D&&(x=D,D={}),D=D||{},"cores"in g&&!D.update)return x(null,g.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return g.cores=navigator.hardwareConcurrency,x(null,g.cores);if(typeof Worker>"u")return g.cores=1,x(null,g.cores);if(typeof Blob>"u")return g.cores=2,x(null,g.cores);var M=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(S){for(var O=Date.now(),H=O+4;Date.now()te.st&&j.stj.st&&te.st{var h=N(8659);N(1298),N(7791),N(279),N(979),N(9386),N(6078),N(8604),N(7256),N(5517),N(4747);var u=h.asn1,g=J.exports=h.pki=h.pki||{},b=g.oids,w={};w.CN=b.commonName,w.commonName="CN",w.C=b.countryName,w.countryName="C",w.L=b.localityName,w.localityName="L",w.ST=b.stateOrProvinceName,w.stateOrProvinceName="ST",w.O=b.organizationName,w.organizationName="O",w.OU=b.organizationalUnitName,w.organizationalUnitName="OU",w.E=b.emailAddress,w.emailAddress="E";var v=h.pki.rsa.publicKeyValidator,l={name:"Certificate",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:u.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:u.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:u.Class.UNIVERSAL,type:u.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:u.Class.UNIVERSAL,type:u.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:u.Class.UNIVERSAL,type:u.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:u.Class.UNIVERSAL,type:u.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},v,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:u.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:u.Class.UNIVERSAL,type:u.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:u.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:u.Class.UNIVERSAL,type:u.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:u.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:u.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:u.Class.UNIVERSAL,type:u.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},p={name:"rsapss",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:u.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:u.Class.UNIVERSAL,type:u.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:u.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:u.Class.UNIVERSAL,type:u.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:u.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:u.Class.UNIVERSAL,type:u.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:u.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:u.Class.UNIVERSAL,type:u.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},_={name:"CertificationRequest",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[{name:"CertificationRequestInfo",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},v,{name:"CertificationRequestInfo.attributes",tagClass:u.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:u.Class.UNIVERSAL,type:u.Type.SET,constructed:!0}]}]}]},{name:"CertificationRequest.signatureAlgorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:u.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:u.Class.UNIVERSAL,type:u.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};function I(S,O){"string"==typeof O&&(O={shortName:O});for(var L,H=null,j=0;null===H&&j"u"&&(O.type&&O.type in g.oids?O.name=g.oids[O.type]:O.shortName&&O.shortName in w&&(O.name=g.oids[w[O.shortName]])),typeof O.type>"u"){if(!O.name||!(O.name in g.oids))throw(L=new Error("Attribute type not specified.")).attribute=O,L;O.type=g.oids[O.name]}if(typeof O.shortName>"u"&&O.name&&O.name in w&&(O.shortName=w[O.name]),O.type===b.extensionRequest&&(O.valueConstructed=!0,O.valueTagClass=u.Type.SEQUENCE,!O.value&&O.extensions)){O.value=[];for(var j=0;j"u")throw(L=new Error("Attribute value not specified.")).attribute=O,L}}function D(S,O){if(O=O||{},typeof S.name>"u"&&S.id&&S.id in g.oids&&(S.name=g.oids[S.id]),typeof S.id>"u"){if(!S.name||!(S.name in g.oids))throw(H=new Error("Extension ID not specified.")).extension=S,H;S.id=g.oids[S.name]}if(typeof S.value<"u")return S;if("keyUsage"===S.name){var L=0,j=0,re=0;S.digitalSignature&&(j|=128,L=7),S.nonRepudiation&&(j|=64,L=6),S.keyEncipherment&&(j|=32,L=5),S.dataEncipherment&&(j|=16,L=4),S.keyAgreement&&(j|=8,L=3),S.keyCertSign&&(j|=4,L=2),S.cRLSign&&(j|=2,L=1),S.encipherOnly&&(j|=1,L=0),S.decipherOnly&&(re|=128,L=7);var $=String.fromCharCode(L);0!==re?$+=String.fromCharCode(j)+String.fromCharCode(re):0!==j&&($+=String.fromCharCode(j)),S.value=u.create(u.Class.UNIVERSAL,u.Type.BITSTRING,!1,$)}else if("basicConstraints"===S.name)S.value=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[]),S.cA&&S.value.value.push(u.create(u.Class.UNIVERSAL,u.Type.BOOLEAN,!1,String.fromCharCode(255))),"pathLenConstraint"in S&&S.value.value.push(u.create(u.Class.UNIVERSAL,u.Type.INTEGER,!1,u.integerToDer(S.pathLenConstraint).getBytes()));else if("extKeyUsage"===S.name){S.value=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[]);var te=S.value.value;for(var Z in S)!0===S[Z]&&(Z in b?te.push(u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(b[Z]).getBytes())):-1!==Z.indexOf(".")&&te.push(u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(Z).getBytes())))}else if("nsCertType"===S.name)L=0,j=0,S.client&&(j|=128,L=7),S.server&&(j|=64,L=6),S.email&&(j|=32,L=5),S.objsign&&(j|=16,L=4),S.reserved&&(j|=8,L=3),S.sslCA&&(j|=4,L=2),S.emailCA&&(j|=2,L=1),S.objCA&&(j|=1,L=0),$=String.fromCharCode(L),0!==j&&($+=String.fromCharCode(j)),S.value=u.create(u.Class.UNIVERSAL,u.Type.BITSTRING,!1,$);else if("subjectAltName"===S.name||"issuerAltName"===S.name){S.value=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[]);for(var ne=0;ne128)throw new Error('Invalid "nsComment" content.');S.value=u.create(u.Class.UNIVERSAL,u.Type.IA5STRING,!1,S.comment)}else if("subjectKeyIdentifier"===S.name&&O.cert){var oe=O.cert.generateSubjectKeyIdentifier();S.subjectKeyIdentifier=oe.toHex(),S.value=u.create(u.Class.UNIVERSAL,u.Type.OCTETSTRING,!1,oe.getBytes())}else if("authorityKeyIdentifier"===S.name&&O.cert){if(S.value=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[]),te=S.value.value,S.keyIdentifier){var de=!0===S.keyIdentifier?O.cert.generateSubjectKeyIdentifier().getBytes():S.keyIdentifier;te.push(u.create(u.Class.CONTEXT_SPECIFIC,0,!1,de))}if(S.authorityCertIssuer){var pe=[u.create(u.Class.CONTEXT_SPECIFIC,4,!0,[C(!0===S.authorityCertIssuer?O.cert.issuer:S.authorityCertIssuer)])];te.push(u.create(u.Class.CONTEXT_SPECIFIC,1,!0,pe))}if(S.serialNumber){var ke=h.util.hexToBytes(!0===S.serialNumber?O.cert.serialNumber:S.serialNumber);te.push(u.create(u.Class.CONTEXT_SPECIFIC,2,!1,ke))}}else if("cRLDistributionPoints"===S.name){S.value=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[]),te=S.value.value;var q,Se=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[]),Pe=u.create(u.Class.CONTEXT_SPECIFIC,0,!0,[]);for(ne=0;ne"u")throw(H=new Error("Extension value not specified.")).extension=S,H;return S}function x(S,O){if(S===b["RSASSA-PSS"]){var H=[];return void 0!==O.hash.algorithmOid&&H.push(u.create(u.Class.CONTEXT_SPECIFIC,0,!0,[u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(O.hash.algorithmOid).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.NULL,!1,"")])])),void 0!==O.mgf.algorithmOid&&H.push(u.create(u.Class.CONTEXT_SPECIFIC,1,!0,[u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(O.mgf.algorithmOid).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(O.mgf.hash.algorithmOid).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.NULL,!1,"")])])])),void 0!==O.saltLength&&H.push(u.create(u.Class.CONTEXT_SPECIFIC,2,!0,[u.create(u.Class.UNIVERSAL,u.Type.INTEGER,!1,u.integerToDer(O.saltLength).getBytes())])),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,H)}return u.create(u.Class.UNIVERSAL,u.Type.NULL,!1,"")}function M(S){var O=u.create(u.Class.CONTEXT_SPECIFIC,0,!0,[]);if(0===S.attributes.length)return O;for(var H=S.attributes,L=0;L2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(Z.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if($.validity.notBefore=Z[0],$.validity.notAfter=Z[1],$.tbsCertificate=H.tbsCertificate,O){$.md=y({signatureOid:$.signatureOid,type:"certificate"});var q=u.toDer($.tbsCertificate);$.md.update(q.getBytes())}var ne=h.md.sha1.create(),oe=u.toDer(H.certIssuer);ne.update(oe.getBytes()),$.issuer.getField=function(ke){return I($.issuer,ke)},$.issuer.addField=function(ke){P([ke]),$.issuer.attributes.push(ke)},$.issuer.attributes=g.RDNAttributesAsArray(H.certIssuer),H.certIssuerUniqueId&&($.issuer.uniqueId=H.certIssuerUniqueId),$.issuer.hash=ne.digest().toHex();var de=h.md.sha1.create(),pe=u.toDer(H.certSubject);return de.update(pe.getBytes()),$.subject.getField=function(ke){return I($.subject,ke)},$.subject.addField=function(ke){P([ke]),$.subject.attributes.push(ke)},$.subject.attributes=g.RDNAttributesAsArray(H.certSubject),H.certSubjectUniqueId&&($.subject.uniqueId=H.certSubjectUniqueId),$.subject.hash=de.digest().toHex(),$.extensions=H.certExtensions?g.certificateExtensionsFromAsn1(H.certExtensions):[],$.publicKey=g.publicKeyFromAsn1(H.subjectPublicKeyInfo),$},g.certificateExtensionsFromAsn1=function(S){for(var O=[],H=0;H1&&(L=H.value.charCodeAt(1),j=H.value.length>2?H.value.charCodeAt(2):0),O.digitalSignature=128==(128&L),O.nonRepudiation=64==(64&L),O.keyEncipherment=32==(32&L),O.dataEncipherment=16==(16&L),O.keyAgreement=8==(8&L),O.keyCertSign=4==(4&L),O.cRLSign=2==(2&L),O.encipherOnly=1==(1&L),O.decipherOnly=128==(128&j)}else if("basicConstraints"===O.name){var H=u.fromDer(O.value);O.cA=H.value.length>0&&H.value[0].type===u.Type.BOOLEAN&&0!==H.value[0].value.charCodeAt(0);var re=null;H.value.length>0&&H.value[0].type===u.Type.INTEGER?re=H.value[0].value:H.value.length>1&&(re=H.value[1].value),null!==re&&(O.pathLenConstraint=u.derToInteger(re))}else if("extKeyUsage"===O.name){H=u.fromDer(O.value);for(var $=0;$1&&(L=H.value.charCodeAt(1)),O.client=128==(128&L),O.server=64==(64&L),O.email=32==(32&L),O.objsign=16==(16&L),O.reserved=8==(8&L),O.sslCA=4==(4&L),O.emailCA=2==(2&L),O.objCA=1==(1&L);else if("subjectAltName"===O.name||"issuerAltName"===O.name){O.altNames=[],H=u.fromDer(O.value);for(var Z,q=0;q=B&&S0&&L.value.push(g.certificateExtensionsToAsn1(S.extensions)),L},g.getCertificationRequestInfo=function(S){return u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.INTEGER,!1,u.integerToDer(S.version).getBytes()),C(S.subject),g.publicKeyToAsn1(S.publicKey),M(S)])},g.distinguishedNameToAsn1=function(S){return C(S)},g.certificateToAsn1=function(S){var O=S.tbsCertificate||g.getTBSCertificate(S);return u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[O,u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(S.signatureOid).getBytes()),x(S.signatureOid,S.signatureParameters)]),u.create(u.Class.UNIVERSAL,u.Type.BITSTRING,!1,String.fromCharCode(0)+S.signature)])},g.certificateExtensionsToAsn1=function(S){var O=u.create(u.Class.CONTEXT_SPECIFIC,3,!0,[]),H=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[]);O.value.push(H);for(var L=0;L"u"&&(j=new Date);var re=!0,$=null,te=0;do{var Z=O.shift(),q=null,ne=!1;if(j&&(jZ.validity.notAfter)&&($={message:"Certificate is not valid yet or has expired.",error:g.certificateError.certificate_expired,notBefore:Z.validity.notBefore,notAfter:Z.validity.notAfter,now:j}),null===$){if(null===(q=O[0]||S.getIssuer(Z))&&Z.isIssuer(Z)&&(ne=!0,q=Z),q){var oe=q;h.util.isArray(oe)||(oe=[oe]);for(var de=!1;!de&&oe.length>0;){q=oe.shift();try{de=q.verify(Z)}catch{}}de||($={message:"Certificate signature is invalid.",error:g.certificateError.bad_certificate})}null===$&&(!q||ne)&&!S.hasCertificate(Z)&&($={message:"Certificate is not trusted.",error:g.certificateError.unknown_ca})}if(null===$&&q&&!Z.isIssuer(q)&&($={message:"Certificate issuer is invalid.",error:g.certificateError.bad_certificate}),null===$)for(var pe={keyUsage:!0,basicConstraints:!0},ke=0;null===$&&kePe.pathLenConstraint&&($={message:"Certificate basicConstraints pathLenConstraint violated.",error:g.certificateError.bad_certificate})}var K=null===$||$.error,Ee=H.verify?H.verify(K,te,L):K;if(!0!==Ee)throw!0===K&&($={message:"The application rejected the certificate.",error:g.certificateError.bad_certificate}),(Ee||0===Ee)&&("object"!=typeof Ee||h.util.isArray(Ee)?"string"==typeof Ee&&($.error=Ee):(Ee.message&&($.message=Ee.message),Ee.error&&($.error=Ee.error))),$;$=null,re=!1,++te}while(O.length>0);return!0}},8614:(J,G,N)=>{const h=N(1159),u=N(281);J.exports=class{constructor(){this._buffer=new h,this._waitingConsumers=new h}push(b){const{promise:w,resolve:v}=u();return this._buffer.push({chunk:b,resolve:v}),this._consume(),w}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){const b=this._waitingConsumers.shift(),w=this._buffer.shift();b.resolve(w.chunk),w.resolve()}}shift(){const{promise:b,resolve:w}=u();return this._waitingConsumers.push({resolve:w}),this._consume(),b}isEmpty(){return this._buffer.isEmpty()}}},281:J=>{"use strict";J.exports=()=>{const N={};return N.promise=new Promise((h,u)=>{N.resolve=h,N.reject=u}),N}},4108:(J,G,N)=>{"use strict";J.exports=N(8777).default},8777:function(J,G,N){"use strict";var h=this&&this.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(G,"__esModule",{value:!0});const u=N(7910),g=h(N(4066)),b=h(N(6599)),w=N(1396),l=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map(_=>new u.Netmask(_));function d(_){return/^::$/.test(_)||/^::1$/.test(_)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(_)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(_)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(_)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(_)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(_)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(_)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(_)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(_)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(_)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(_)||/^ff([0-9a-fA-F]{2,2}):/i.test(_)}G.default=_=>{if((0,w.isValid)(_)){const I=(0,w.parse)(_);if("ipv4"===I.kind())return function p(_){for(let I of l)if(I.contains(_))return!0;return!1}(I.toNormalizedString());if("ipv6"===I.kind())return d(_)}else if((0,b.default)(_)&&g.default.v6().test(_))return d(_)}},3863:(J,G,N)=>{"use strict";J.exports=N(2540)},4599:J=>{"use strict";J.exports=N;var h,G=/\/|\./;function N(u,g){G.test(u)||(u="google/protobuf/"+u+".proto",g={nested:{google:{nested:{protobuf:{nested:g}}}}}),N[u]=g}N("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),N("duration",{Duration:h={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),N("timestamp",{Timestamp:h}),N("empty",{Empty:{fields:{}}}),N("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),N("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),N("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),N.get=function(g){return N[g]||null}},6533:(J,G,N)=>{"use strict";var h=G,u=N(4269),g=N(8572);function b(v,l,p,d){if(l.resolvedType)if(l.resolvedType instanceof u){v("switch(d%s){",d);for(var _=l.resolvedType.values,I=Object.keys(_),E=0;E>>0",d,d);break;case"int32":case"sint32":case"sfixed32":v("m%s=d%s|0",d,d);break;case"uint64":y=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":v("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",d,d,y)('else if(typeof d%s==="string")',d)("m%s=parseInt(d%s,10)",d,d)('else if(typeof d%s==="number")',d)("m%s=d%s",d,d)('else if(typeof d%s==="object")',d)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",d,d,d,y?"true":"");break;case"bytes":v('if(typeof d%s==="string")',d)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",d,d,d)("else if(d%s.length >= 0)",d)("m%s=d%s",d,d);break;case"string":v("m%s=String(d%s)",d,d);break;case"bool":v("m%s=Boolean(d%s)",d,d)}}return v}function w(v,l,p,d){if(l.resolvedType)l.resolvedType instanceof u?v("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",d,p,d,d,p,d,d):v("d%s=types[%i].toObject(m%s,o)",d,p,d);else{var _=!1;switch(l.type){case"double":case"float":v("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",d,d,d,d);break;case"uint64":_=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":v('if(typeof m%s==="number")',d)("d%s=o.longs===String?String(m%s):m%s",d,d,d)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",d,d,d,d,_?"true":"",d);break;case"bytes":v("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",d,d,d,d,d);break;default:v("d%s=m%s",d,d)}}return v}h.fromObject=function(l){var p=l.fieldsArray,d=g.codegen(["d"],l.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!p.length)return d("return new this.ctor");d("var m=new this.ctor");for(var _=0;_{"use strict";J.exports=function w(v){var l=g.codegen(["r","l"],v.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(v.fieldsArray.filter(function(y){return y.map}).length?",k,value":""))("while(r.pos>>3){");for(var p=0;p>>3){")("case 1: k=r.%s(); break",d.keyType)("case 2:"),void 0===u.basic[_]?l("value=types[%i].decode(r,r.uint32())",p):l("value=r.%s()",_),l("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),l(void 0!==u.long[d.keyType]?'%s[typeof k==="object"?util.longToHash(k):k]=value':"%s[k]=value",I)):d.repeated?(l("if(!(%s&&%s.length))",I,I)("%s=[]",I),void 0!==u.packed[_]&&l("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos{"use strict";J.exports=function w(v){for(var d,l=g.codegen(["m","w"],v.name+"$encode")("if(!w)")("w=Writer.create()"),_=v.fieldsArray.slice().sort(g.compareFieldsById),p=0;p<_.length;++p){var I=_[p].resolve(),E=v._fieldsArray.indexOf(I),y=I.resolvedType instanceof h?"int32":I.type,f=u.basic[y];d="m"+g.safeProp(I.name),I.map?(l("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",d,I.name)("for(var ks=Object.keys(%s),i=0;i>>0,8|u.mapKey[I.keyType],I.keyType),void 0===f?l("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",E,d):l(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|f,y,d),l("}")("}")):I.repeated?(l("if(%s!=null&&%s.length){",d,d),I.packed&&void 0!==u.packed[y]?l("w.uint32(%i).fork()",(I.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",d)("w.%s(%s[i])",y,d)("w.ldelim()"):(l("for(var i=0;i<%s.length;++i)",d),void 0===f?b(l,I,E,d+"[i]"):l("w.uint32(%i).%s(%s[i])",(I.id<<3|f)>>>0,y,d)),l("}")):(I.optional&&l("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",d,I.name),void 0===f?b(l,I,E,d):l("w.uint32(%i).%s(%s)",(I.id<<3|f)>>>0,y,d))}return l("return w")};var h=N(4269),u=N(688),g=N(8572);function b(v,l,p,d){return l.resolvedType.group?v("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",p,d,(l.id<<3|3)>>>0,(l.id<<3|4)>>>0):v("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",p,d,(l.id<<3|2)>>>0)}},4269:(J,G,N)=>{"use strict";J.exports=b;var h=N(9487);((b.prototype=Object.create(h.prototype)).constructor=b).className="Enum";var u=N(326),g=N(8572);function b(w,v,l,p,d,_){if(h.call(this,w,l),v&&"object"!=typeof v)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=p,this.comments=d||{},this.valuesOptions=_,this.reserved=void 0,v)for(var I=Object.keys(v),E=0;E{"use strict";J.exports=l;var h=N(9487);((l.prototype=Object.create(h.prototype)).constructor=l).className="Field";var w,u=N(4269),g=N(688),b=N(8572),v=/^required|optional|repeated$/;function l(p,d,_,I,E,y,f){if(b.isObject(I)?(f=E,y=I,I=E=void 0):b.isObject(E)&&(f=y,y=E,E=void 0),h.call(this,p,y),!b.isInteger(d)||d<0)throw TypeError("id must be a non-negative integer");if(!b.isString(_))throw TypeError("type must be a string");if(void 0!==I&&!v.test(I=I.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==E&&!b.isString(E))throw TypeError("extend must be a string");"proto3_optional"===I&&(I="optional"),this.rule=I&&"optional"!==I?I:void 0,this.type=_,this.id=d,this.extend=E||void 0,this.required="required"===I,this.optional=!this.required,this.repeated="repeated"===I,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!b.Long&&void 0!==g.long[_],this.bytes="bytes"===_,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=f}l.fromJSON=function(d,_){return new l(d,_.id,_.type,_.rule,_.extend,_.options,_.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(d,_,I){return"packed"===d&&(this._packed=null),h.prototype.setOption.call(this,d,_,I)},l.prototype.toJSON=function(d){var _=!!d&&Boolean(d.keepComments);return b.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",_?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=g.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.typeDefault=this.resolvedType instanceof w?null:this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof u&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&((!0===this.options.packed||void 0!==this.options.packed&&this.resolvedType&&!(this.resolvedType instanceof u))&&delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=b.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var d;b.base64.test(this.typeDefault)?b.base64.decode(this.typeDefault,d=b.newBuffer(b.base64.length(this.typeDefault)),0):b.utf8.write(this.typeDefault,d=b.newBuffer(b.utf8.length(this.typeDefault)),0),this.typeDefault=d}return this.defaultValue=this.map?b.emptyObject:this.repeated?b.emptyArray:this.typeDefault,this.parent instanceof w&&(this.parent.ctor.prototype[this.name]=this.defaultValue),h.prototype.resolve.call(this)},l.d=function(d,_,I,E){return"function"==typeof _?_=b.decorateType(_).name:_&&"object"==typeof _&&(_=b.decorateEnum(_).name),function(f,C){b.decorateType(f.constructor).add(new l(C,d,_,I,{default:E}))}},l._configure=function(d){w=d}},5803:(J,G,N)=>{"use strict";var h=J.exports=N(95);h.build="light",h.load=function u(b,w,v){return"function"==typeof w?(v=w,w=new h.Root):w||(w=new h.Root),w.load(b,v)},h.loadSync=function g(b,w){return w||(w=new h.Root),w.loadSync(b)},h.encoder=N(133),h.decoder=N(225),h.verifier=N(8617),h.converter=N(6533),h.ReflectionObject=N(9487),h.Namespace=N(326),h.Root=N(5257),h.Enum=N(4269),h.Type=N(7845),h.Field=N(2986),h.OneOf=N(7397),h.MapField=N(9455),h.Service=N(9630),h.Method=N(1618),h.Message=N(1413),h.wrappers=N(761),h.types=N(688),h.util=N(8572),h.ReflectionObject._configure(h.Root),h.Namespace._configure(h.Type,h.Service,h.Enum),h.Root._configure(h.Type),h.Field._configure(h.Type)},95:(J,G,N)=>{"use strict";var h=G;function u(){h.util._configure(),h.Writer._configure(h.BufferWriter),h.Reader._configure(h.BufferReader)}h.build="minimal",h.Writer=N(1650),h.BufferWriter=N(813),h.Reader=N(7270),h.BufferReader=N(4354),h.util=N(7211),h.rpc=N(7830),h.roots=N(6671),h.configure=u,u()},2540:(J,G,N)=>{"use strict";var h=J.exports=N(5803);h.build="full",h.tokenize=N(691),h.parse=N(8992),h.common=N(4599),h.Root._configure(h.Type,h.parse,h.common)},9455:(J,G,N)=>{"use strict";J.exports=b;var h=N(2986);((b.prototype=Object.create(h.prototype)).constructor=b).className="MapField";var u=N(688),g=N(8572);function b(w,v,l,p,d,_){if(h.call(this,w,v,p,void 0,void 0,d,_),!g.isString(l))throw TypeError("keyType must be a string");this.keyType=l,this.resolvedKeyType=null,this.map=!0}b.fromJSON=function(v,l){return new b(v,l.id,l.keyType,l.type,l.options,l.comment)},b.prototype.toJSON=function(v){var l=!!v&&Boolean(v.keepComments);return g.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",l?this.comment:void 0])},b.prototype.resolve=function(){if(this.resolved)return this;if(void 0===u.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return h.prototype.resolve.call(this)},b.d=function(v,l,p){return"function"==typeof p?p=g.decorateType(p).name:p&&"object"==typeof p&&(p=g.decorateEnum(p).name),function(_,I){g.decorateType(_.constructor).add(new b(I,v,l,p))}}},1413:(J,G,N)=>{"use strict";J.exports=u;var h=N(7211);function u(g){if(g)for(var b=Object.keys(g),w=0;w{"use strict";J.exports=g;var h=N(9487);((g.prototype=Object.create(h.prototype)).constructor=g).className="Method";var u=N(8572);function g(b,w,v,l,p,d,_,I,E){if(u.isObject(p)?(_=p,p=d=void 0):u.isObject(d)&&(_=d,d=void 0),void 0!==w&&!u.isString(w))throw TypeError("type must be a string");if(!u.isString(v))throw TypeError("requestType must be a string");if(!u.isString(l))throw TypeError("responseType must be a string");h.call(this,b,_),this.type=w||"rpc",this.requestType=v,this.requestStream=!!p||void 0,this.responseType=l,this.responseStream=!!d||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=I,this.parsedOptions=E}g.fromJSON=function(w,v){return new g(w,v.type,v.requestType,v.responseType,v.requestStream,v.responseStream,v.options,v.comment,v.parsedOptions)},g.prototype.toJSON=function(w){var v=!!w&&Boolean(w.keepComments);return u.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",v?this.comment:void 0,"parsedOptions",this.parsedOptions])},g.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),h.prototype.resolve.call(this))}},326:(J,G,N)=>{"use strict";J.exports=d;var h=N(9487);((d.prototype=Object.create(h.prototype)).constructor=d).className="Namespace";var w,v,l,u=N(2986),g=N(8572),b=N(7397);function p(I,E){if(I&&I.length){for(var y={},f=0;fy)return!0;return!1},d.isReservedName=function(E,y){if(E)for(var f=0;f0;){var C=E.shift();if(f.nested&&f.nested[C]){if(!((f=f.nested[C])instanceof d))throw Error("path conflicts with non-namespace objects")}else f.add(f=new d(C))}return y&&f.addJSON(y),f},d.prototype.resolveAll=function(){for(var E=this.nestedArray,y=0;y-1)return C}else if(C instanceof d&&(C=C.lookup(E.slice(1),y,!0)))return C}else for(var A=0;A{"use strict";J.exports=g,g.className="ReflectionObject";var u,h=N(8572);function g(b,w){if(!h.isString(b))throw TypeError("name must be a string");if(w&&!h.isObject(w))throw TypeError("options must be an object");this.options=w,this.parsedOptions=null,this.name=b,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(g.prototype,{root:{get:function(){for(var b=this;null!==b.parent;)b=b.parent;return b}},fullName:{get:function(){for(var b=[this.name],w=this.parent;w;)b.unshift(w.name),w=w.parent;return b.join(".")}}}),g.prototype.toJSON=function(){throw Error()},g.prototype.onAdd=function(w){this.parent&&this.parent!==w&&this.parent.remove(this),this.parent=w,this.resolved=!1;var v=w.root;v instanceof u&&v._handleAdd(this)},g.prototype.onRemove=function(w){var v=w.root;v instanceof u&&v._handleRemove(this),this.parent=null,this.resolved=!1},g.prototype.resolve=function(){return this.resolved||this.root instanceof u&&(this.resolved=!0),this},g.prototype.getOption=function(w){if(this.options)return this.options[w]},g.prototype.setOption=function(w,v,l){return(!l||!this.options||void 0===this.options[w])&&((this.options||(this.options={}))[w]=v),this},g.prototype.setParsedOption=function(w,v,l){this.parsedOptions||(this.parsedOptions=[]);var p=this.parsedOptions;if(l){var d=p.find(function(E){return Object.prototype.hasOwnProperty.call(E,w)});d?h.setProperty(d[w],l,v):((d={})[w]=h.setProperty({},l,v),p.push(d))}else{var I={};I[w]=v,p.push(I)}return this},g.prototype.setOptions=function(w,v){if(w)for(var l=Object.keys(w),p=0;p{"use strict";J.exports=b;var h=N(9487);((b.prototype=Object.create(h.prototype)).constructor=b).className="OneOf";var u=N(2986),g=N(8572);function b(v,l,p,d){if(Array.isArray(l)||(p=l,l=void 0),h.call(this,v,p),void 0!==l&&!Array.isArray(l))throw TypeError("fieldNames must be an Array");this.oneof=l||[],this.fieldsArray=[],this.comment=d}function w(v){if(v.parent)for(var l=0;l-1&&this.oneof.splice(p,1),l.partOf=null,this},b.prototype.onAdd=function(l){h.prototype.onAdd.call(this,l);for(var d=0;d{"use strict";J.exports=F,F.filename=null,F.defaults={keepCase:!1};var h=N(691),u=N(5257),g=N(7845),b=N(2986),w=N(9455),v=N(7397),l=N(4269),p=N(9630),d=N(1618),_=N(688),I=N(8572),E=/^[1-9][0-9]*$/,y=/^-?[1-9][0-9]*$/,f=/^0[x][0-9a-fA-F]+$/,C=/^-?0[x][0-9a-fA-F]+$/,A=/^0[0-7]+$/,P=/^-?0[0-7]+$/,D=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,x=/^[a-zA-Z_][a-zA-Z_0-9]*$/,M=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,B=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function F(z,S,O){S instanceof u||(O=S,S=new u),O||(O=F.defaults);var ne,oe,de,pe,je,H=O.preferTrailingComment||!1,L=h(z,O.alternateCommentMode||!1),j=L.next,re=L.push,$=L.peek,te=L.skip,Z=L.cmnt,q=!0,ke=!1,Se=S,Pe=O.keepCase?function(be){return be}:I.camelCase;function we(be,ge,De){var Ue=F.filename;return De||(F.filename=null),Error("illegal "+(ge||"token")+" '"+be+"' ("+(Ue?Ue+", ":"")+"line "+L.line+")")}function $e(){var ge,be=[];do{if('"'!==(ge=j())&&"'"!==ge)throw we(ge);be.push(j()),te(ge),ge=$()}while('"'===ge||"'"===ge);return be.join("")}function K(be){var ge=j();switch(ge){case"'":case'"':return re(ge),$e();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function Ce(be,ge){var De=1;switch("-"===be.charAt(0)&&(De=-1,be=be.substring(1)),be){case"inf":case"INF":case"Inf":return De*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(E.test(be))return De*parseInt(be,10);if(f.test(be))return De*parseInt(be,16);if(A.test(be))return De*parseInt(be,8);if(D.test(be))return De*parseFloat(be);throw we(be,"number",ge)}(ge,!0)}catch{if(be&&M.test(ge))return ge;throw we(ge,"value")}}function Ee(be,ge){var De,Ue;do{!ge||'"'!==(De=$())&&"'"!==De?be.push([Ue=xe(j()),te("to",!0)?xe(j()):Ue]):be.push($e())}while(te(",",!0));te(";")}function xe(be,ge){switch(be){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!ge&&"-"===be.charAt(0))throw we(be,"id");if(y.test(be))return parseInt(be,10);if(C.test(be))return parseInt(be,16);if(P.test(be))return parseInt(be,8);throw we(be,"id")}function Ke(){if(void 0!==ne)throw we("package");if(ne=j(),!M.test(ne))throw we(ne,"name");Se=Se.define(ne),te(";")}function We(){var ge,be=$();switch(be){case"weak":ge=de||(de=[]),j();break;case"public":j();default:ge=oe||(oe=[])}be=$e(),te(";"),ge.push(be)}function Je(){if(te("="),pe=$e(),!(ke="proto3"===pe)&&"proto2"!==pe)throw we(pe,"syntax");te(";")}function Xe(be,ge){switch(ge){case"option":return ye(be,ge),te(";"),!0;case"message":return pt(be,ge),!0;case"enum":return ie(be,ge),!0;case"service":return function qe(be,ge){if(!x.test(ge=j()))throw we(ge,"service name");var De=new p(ge);Ot(De,function(Be){if(!Xe(De,Be)){if("rpc"!==Be)throw we(Be);!function st(be,ge){var De=Z(),Ue=ge;if(!x.test(ge=j()))throw we(ge,"name");var dt,Pt,vt,et,Be=ge;if(te("("),te("stream",!0)&&(Pt=!0),!M.test(ge=j())||(dt=ge,te(")"),te("returns"),te("("),te("stream",!0)&&(et=!0),!M.test(ge=j())))throw we(ge);vt=ge,te(")");var Pn=new d(Be,Ue,dt,vt,Pt,et);Pn.comment=De,Ot(Pn,function(yn){if("option"!==yn)throw we(yn);ye(Pn,yn),te(";")}),be.add(Pn)}(De,Be)}}),be.add(De)}(be,ge),!0;case"extend":return function nt(be,ge){if(!M.test(ge=j()))throw we(ge,"reference");var De=ge;Ot(null,function(Be){switch(Be){case"required":case"repeated":Dt(be,Be,De);break;case"optional":Dt(be,ke?"proto3_optional":"optional",De);break;default:if(!ke||!M.test(Be))throw we(Be);re(Be),Dt(be,"optional",De)}})}(be,ge),!0}return!1}function Ot(be,ge,De){var Ue=L.line;if(be&&("string"!=typeof be.comment&&(be.comment=Z()),be.filename=F.filename),te("{",!0)){for(var Be;"}"!==(Be=j());)ge(Be);te(";",!0)}else De&&De(),te(";"),be&&("string"!=typeof be.comment||H)&&(be.comment=Z(Ue)||be.comment)}function pt(be,ge){if(!x.test(ge=j()))throw we(ge,"type name");var De=new g(ge);Ot(De,function(Be){if(!Xe(De,Be))switch(Be){case"map":!function Sr(be){te("<");var ge=j();if(void 0===_.mapKey[ge])throw we(ge,"type");te(",");var De=j();if(!M.test(De))throw we(De,"type");te(">");var Ue=j();if(!x.test(Ue))throw we(Ue,"name");te("=");var Be=new w(Pe(Ue),xe(j()),ge,De);Ot(Be,function(Pt){if("option"!==Pt)throw we(Pt);ye(Be,Pt),te(";")},function(){Ye(Be)}),be.add(Be)}(De);break;case"required":case"repeated":Dt(De,Be);break;case"optional":Dt(De,ke?"proto3_optional":"optional");break;case"oneof":!function ni(be,ge){if(!x.test(ge=j()))throw we(ge,"name");var De=new v(Pe(ge));Ot(De,function(Be){"option"===Be?(ye(De,Be),te(";")):(re(Be),Dt(De,"optional"))}),be.add(De)}(De,Be);break;case"extensions":Ee(De.extensions||(De.extensions=[]));break;case"reserved":Ee(De.reserved||(De.reserved=[]),!0);break;default:if(!ke||!M.test(Be))throw we(Be);re(Be),Dt(De,"optional")}}),be.add(De)}function Dt(be,ge,De){var Ue=j();if("group"!==Ue){if(!M.test(Ue))throw we(Ue,"type");var Be=j();if(!x.test(Be))throw we(Be,"name");Be=Pe(Be),te("=");var dt=new b(Be,xe(j()),Ue,ge,De);if(Ot(dt,function(et){if("option"!==et)throw we(et);ye(dt,et),te(";")},function(){Ye(dt)}),"proto3_optional"===ge){var Pt=new v("_"+Be);dt.setOption("proto3_optional",!0),Pt.add(dt),be.add(Pt)}else be.add(dt);!ke&&dt.repeated&&(void 0!==_.packed[Ue]||void 0===_.basic[Ue])&&dt.setOption("packed",!1,!0)}else!function Wr(be,ge){var De=j();if(!x.test(De))throw we(De,"name");var Ue=I.lcFirst(De);De===Ue&&(De=I.ucFirst(De)),te("=");var Be=xe(j()),dt=new g(De);dt.group=!0;var Pt=new b(Ue,Be,De,ge);Pt.filename=F.filename,Ot(dt,function(et){switch(et){case"option":ye(dt,et),te(";");break;case"required":case"repeated":Dt(dt,et);break;case"optional":Dt(dt,ke?"proto3_optional":"optional");break;case"message":pt(dt,et);break;case"enum":ie(dt,et);break;default:throw we(et)}}),be.add(dt).add(Pt)}(be,ge)}function ie(be,ge){if(!x.test(ge=j()))throw we(ge,"name");var De=new l(ge);Ot(De,function(Be){switch(Be){case"option":ye(De,Be),te(";");break;case"reserved":Ee(De.reserved||(De.reserved=[]),!0);break;default:!function fe(be,ge){if(!x.test(ge))throw we(ge,"name");te("=");var De=xe(j(),!0),Ue={options:void 0,setOption:function(Be,dt){void 0===this.options&&(this.options={}),this.options[Be]=dt}};Ot(Ue,function(dt){if("option"!==dt)throw we(dt);ye(Ue,dt),te(";")},function(){Ye(Ue)}),be.add(ge,De,Ue.comment,Ue.options)}(De,Be)}}),be.add(De)}function ye(be,ge){var De=te("(",!0);if(!M.test(ge=j()))throw we(ge,"name");var dt,Ue=ge,Be=Ue;De&&(te(")"),Be=Ue="("+Ue+")",ge=$(),B.test(ge)&&(dt=ge.slice(1),Ue+=ge,j())),te("="),function Ne(be,ge,De,Ue){be.setParsedOption&&be.setParsedOption(ge,De,Ue)}(be,Be,me(be,Ue),dt)}function me(be,ge){if(te("{",!0)){for(var De={};!te("}",!0);){if(!x.test(je=j()))throw we(je,"name");var Ue,Be=je;if(te(":",!0),"{"===$())Ue=me(be,ge+"."+je);else if("["===$()){var dt;if(Ue=[],te("[",!0)){do{dt=K(!0),Ue.push(dt)}while(te(",",!0));te("]"),typeof dt<"u"&&_e(be,ge+"."+je,dt)}}else Ue=K(!0),_e(be,ge+"."+je,Ue);var Pt=De[Be];Pt&&(Ue=[].concat(Pt).concat(Ue)),De[Be]=Ue,te(",",!0),te(";",!0)}return De}var vt=K(!0);return _e(be,ge,vt),vt}function _e(be,ge,De){be.setOption&&be.setOption(ge,De)}function Ye(be){if(te("[",!0)){do{ye(be,"option")}while(te(",",!0));te("]")}return be}for(;null!==(je=j());)switch(je){case"package":if(!q)throw we(je);Ke();break;case"import":if(!q)throw we(je);We();break;case"syntax":if(!q)throw we(je);Je();break;case"option":ye(Se,je),te(";");break;default:if(Xe(Se,je)){q=!1;continue}throw we(je)}return F.filename=null,{package:ne,imports:oe,weakImports:de,syntax:pe,root:S}}},7270:(J,G,N)=>{"use strict";J.exports=v;var u,h=N(7211),g=h.LongBits,b=h.utf8;function w(E,y){return RangeError("index out of range: "+E.pos+" + "+(y||1)+" > "+E.len)}function v(E){this.buf=E,this.pos=0,this.len=E.length}var y,l=typeof Uint8Array<"u"?function(y){if(y instanceof Uint8Array||Array.isArray(y))return new v(y);throw Error("illegal buffer")}:function(y){if(Array.isArray(y))return new v(y);throw Error("illegal buffer")},p=function(){return h.Buffer?function(f){return(v.create=function(A){return h.Buffer.isBuffer(A)?new u(A):l(A)})(f)}:l};function d(){var E=new g(0,0),y=0;if(!(this.len-this.pos>4)){for(;y<3;++y){if(this.pos>=this.len)throw w(this);if(E.lo=(E.lo|(127&this.buf[this.pos])<<7*y)>>>0,this.buf[this.pos++]<128)return E}return E.lo=(E.lo|(127&this.buf[this.pos++])<<7*y)>>>0,E}for(;y<4;++y)if(E.lo=(E.lo|(127&this.buf[this.pos])<<7*y)>>>0,this.buf[this.pos++]<128)return E;if(E.lo=(E.lo|(127&this.buf[this.pos])<<28)>>>0,E.hi=(E.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return E;if(y=0,this.len-this.pos>4){for(;y<5;++y)if(E.hi=(E.hi|(127&this.buf[this.pos])<<7*y+3)>>>0,this.buf[this.pos++]<128)return E}else for(;y<5;++y){if(this.pos>=this.len)throw w(this);if(E.hi=(E.hi|(127&this.buf[this.pos])<<7*y+3)>>>0,this.buf[this.pos++]<128)return E}throw Error("invalid varint encoding")}function _(E,y){return(E[y-4]|E[y-3]<<8|E[y-2]<<16|E[y-1]<<24)>>>0}function I(){if(this.pos+8>this.len)throw w(this,8);return new g(_(this.buf,this.pos+=4),_(this.buf,this.pos+=4))}v.create=p(),v.prototype._slice=h.Array.prototype.subarray||h.Array.prototype.slice,v.prototype.uint32=(y=4294967295,function(){if(y=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(y=(y|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(y=(y|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(y=(y|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(y=(y|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return y;if((this.pos+=5)>this.len)throw this.pos=this.len,w(this,10);return y}),v.prototype.int32=function(){return 0|this.uint32()},v.prototype.sint32=function(){var y=this.uint32();return y>>>1^-(1&y)|0},v.prototype.bool=function(){return 0!==this.uint32()},v.prototype.fixed32=function(){if(this.pos+4>this.len)throw w(this,4);return _(this.buf,this.pos+=4)},v.prototype.sfixed32=function(){if(this.pos+4>this.len)throw w(this,4);return 0|_(this.buf,this.pos+=4)},v.prototype.float=function(){if(this.pos+4>this.len)throw w(this,4);var y=h.float.readFloatLE(this.buf,this.pos);return this.pos+=4,y},v.prototype.double=function(){if(this.pos+8>this.len)throw w(this,4);var y=h.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,y},v.prototype.bytes=function(){var y=this.uint32(),f=this.pos,C=this.pos+y;if(C>this.len)throw w(this,y);return this.pos+=y,Array.isArray(this.buf)?this.buf.slice(f,C):f===C?new this.buf.constructor(0):this._slice.call(this.buf,f,C)},v.prototype.string=function(){var y=this.bytes();return b.read(y,0,y.length)},v.prototype.skip=function(y){if("number"==typeof y){if(this.pos+y>this.len)throw w(this,y);this.pos+=y}else do{if(this.pos>=this.len)throw w(this)}while(128&this.buf[this.pos++]);return this},v.prototype.skipType=function(E){switch(E){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(E=7&this.uint32());)this.skipType(E);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+E+" at offset "+this.pos)}return this},v._configure=function(E){u=E,v.create=p(),u._configure();var y=h.Long?"toLong":"toNumber";h.merge(v.prototype,{int64:function(){return d.call(this)[y](!1)},uint64:function(){return d.call(this)[y](!0)},sint64:function(){return d.call(this).zzDecode()[y](!1)},fixed64:function(){return I.call(this)[y](!0)},sfixed64:function(){return I.call(this)[y](!1)}})}},4354:(J,G,N)=>{"use strict";J.exports=g;var h=N(7270);(g.prototype=Object.create(h.prototype)).constructor=g;var u=N(7211);function g(b){h.call(this,b)}g._configure=function(){u.Buffer&&(g.prototype._slice=u.Buffer.prototype.slice)},g.prototype.string=function(){var w=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+w,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+w,this.len))},g._configure()},5257:(J,G,N)=>{"use strict";J.exports=d;var h=N(326);((d.prototype=Object.create(h.prototype)).constructor=d).className="Root";var v,l,p,u=N(2986),g=N(4269),b=N(7397),w=N(8572);function d(y){h.call(this,"",y),this.deferred=[],this.files=[]}function _(){}d.fromJSON=function(f,C){return C||(C=new d),f.options&&C.setOptions(f.options),C.addJSON(f.nested)},d.prototype.resolvePath=w.path.resolve,d.prototype.fetch=w.fetch,d.prototype.load=function y(f,C,A){"function"==typeof C&&(A=C,C=void 0);var P=this;if(!A)return w.asPromise(y,P,f,C);var D=A===_;function x(H,L){if(A){var j=A;if(A=null,D)throw H;j(H,L)}}function M(H){var L=H.lastIndexOf("google/protobuf/");if(L>-1){var j=H.substring(L);if(j in p)return j}return null}function B(H,L){try{if(w.isString(L)&&"{"===L.charAt(0)&&(L=JSON.parse(L)),w.isString(L)){l.filename=H;var re,j=l(L,P,C),$=0;if(j.imports)for(;$-1)){if(P.files.push(H),H in p)return void(D?B(H,p[H]):(++z,setTimeout(function(){--z,B(H,p[H])})));if(D){var j;try{j=w.fs.readFileSync(H).toString("utf8")}catch(re){return void(L||x(re))}B(H,j)}else++z,P.fetch(H,function(re,$){if(--z,A){if(re)return void(L?z||x(null,P):x(re));B(H,$)}})}}var z=0;w.isString(f)&&(f=[f]);for(var O,S=0;S-1&&this.deferred.splice(C,1)}}else if(f instanceof g)I.test(f.name)&&delete f.parent[f.name];else if(f instanceof h){for(var A=0;A{"use strict";J.exports={}},7830:(J,G,N)=>{"use strict";G.Service=N(6346)},6346:(J,G,N)=>{"use strict";J.exports=u;var h=N(7211);function u(g,b,w){if("function"!=typeof g)throw TypeError("rpcImpl must be a function");h.EventEmitter.call(this),this.rpcImpl=g,this.requestDelimited=Boolean(b),this.responseDelimited=Boolean(w)}(u.prototype=Object.create(h.EventEmitter.prototype)).constructor=u,u.prototype.rpcCall=function g(b,w,v,l,p){if(!l)throw TypeError("request must be specified");var d=this;if(!p)return h.asPromise(g,d,b,w,v,l);if(d.rpcImpl)try{return d.rpcImpl(b,w[d.requestDelimited?"encodeDelimited":"encode"](l).finish(),function(I,E){if(I)return d.emit("error",I,b),p(I);if(null!==E){if(!(E instanceof v))try{E=v[d.responseDelimited?"decodeDelimited":"decode"](E)}catch(y){return d.emit("error",y,b),p(y)}return d.emit("data",E,b),p(null,E)}d.end(!0)})}catch(_){return d.emit("error",_,b),void setTimeout(function(){p(_)},0)}else setTimeout(function(){p(Error("already ended"))},0)},u.prototype.end=function(b){return this.rpcImpl&&(b||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},9630:(J,G,N)=>{"use strict";J.exports=w;var h=N(326);((w.prototype=Object.create(h.prototype)).constructor=w).className="Service";var u=N(1618),g=N(8572),b=N(7830);function w(l,p){h.call(this,l,p),this.methods={},this._methodsArray=null}function v(l){return l._methodsArray=null,l}w.fromJSON=function(p,d){var _=new w(p,d.options);if(d.methods)for(var I=Object.keys(d.methods),E=0;E{"use strict";J.exports=d;var G=/[\s{}=;:[\],'"()<>]/g,N=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,h=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,u=/^ *[*/]+ */,g=/^\s*\*?\/*/,b=/\n/g,w=/\s/,v=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function p(_){return _.replace(v,function(I,E){switch(E){case"\\":case"":return E;default:return l[E]||""}})}function d(_,I){_=_.toString();var E=0,y=_.length,f=1,C=0,A={},P=[],D=null;function x($){return Error("illegal "+$+" (line "+f+")")}function B($){return _.charAt($)}function F($,te,Z){var de,q={type:_.charAt($++),lineEmpty:!1,leading:Z},oe=$-(I?2:3);do{if(--oe<0||"\n"===(de=_.charAt(oe))){q.lineEmpty=!0;break}}while(" "===de||"\t"===de);for(var pe=_.substring($,te).split(b),ke=0;ke0)return P.shift();if(D)return function M(){var $="'"===D?h:N;$.lastIndex=E-1;var te=$.exec(_);if(!te)throw x("string");return E=$.lastIndex,H(D),D=null,p(te[1])}();var $,te,Z,q,ne,oe=0===E;do{if(E===y)return null;for($=!1;w.test(Z=B(E));)if("\n"===Z&&(oe=!0,++f),++E===y)return null;if("/"===B(E)){if(++E===y)throw x("comment");if("/"===B(E))if(I){if(q=E,ne=!1,z(E)){ne=!0;do{if((E=S(E))===y||(E++,!oe))break}while(z(E))}else E=Math.min(y,S(E)+1);ne&&(F(q,E,oe),oe=!0),f++,$=!0}else{for(ne="/"===B(q=E+1);"\n"!==B(++E);)if(E===y)return null;++E,ne&&(F(q,E-1,oe),oe=!0),++f,$=!0}else{if("*"!==(Z=B(E)))return"/";q=E+1,ne=I||"*"===B(q);do{if("\n"===Z&&++f,++E===y)throw x("comment");te=Z,Z=B(E)}while("*"!==te||"/"!==Z);++E,ne&&(F(q,E-2,oe),oe=!0),$=!0}}}while($);var de=E;if(G.lastIndex=0,!G.test(B(de++)))for(;de{"use strict";J.exports=A;var h=N(326);((A.prototype=Object.create(h.prototype)).constructor=A).className="Type";var u=N(4269),g=N(7397),b=N(2986),w=N(9455),v=N(9630),l=N(1413),p=N(7270),d=N(1650),_=N(8572),I=N(133),E=N(225),y=N(8617),f=N(6533),C=N(761);function A(D,x){h.call(this,D,x),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function P(D){return D._fieldsById=D._fieldsArray=D._oneofsArray=null,delete D.encode,delete D.decode,delete D.verify,D}Object.defineProperties(A.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var D=Object.keys(this.fields),x=0;x{"use strict";var h=G,u=N(8572),g=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function b(w,v){var l=0,p={};for(v|=0;l{"use strict";var g,b,h=J.exports=N(7211),u=N(6671);h.codegen=N(9749),h.fetch=N(8832),h.path=N(1311),h.fs=h.inquire("fs"),h.toArray=function(_){if(_){for(var I=Object.keys(_),E=new Array(I.length),y=0;y0)f[P]=y(f[P]||{},C,A);else{var D=f[P];D&&(A=[].concat(D).concat(A)),f[P]=A}return f}(_,I=I.split("."),E)},Object.defineProperty(h,"decorateRoot",{get:function(){return u.decorated||(u.decorated=new(N(5257)))}})},942:(J,G,N)=>{"use strict";J.exports=u;var h=N(7211);function u(v,l){this.lo=v>>>0,this.hi=l>>>0}var g=u.zero=new u(0,0);g.toNumber=function(){return 0},g.zzEncode=g.zzDecode=function(){return this},g.length=function(){return 1};var b=u.zeroHash="\0\0\0\0\0\0\0\0";u.fromNumber=function(l){if(0===l)return g;var p=l<0;p&&(l=-l);var d=l>>>0,_=(l-d)/4294967296>>>0;return p&&(_=~_>>>0,d=~d>>>0,++d>4294967295&&(d=0,++_>4294967295&&(_=0))),new u(d,_)},u.from=function(l){if("number"==typeof l)return u.fromNumber(l);if(h.isString(l)){if(!h.Long)return u.fromNumber(parseInt(l,10));l=h.Long.fromString(l)}return l.low||l.high?new u(l.low>>>0,l.high>>>0):g},u.prototype.toNumber=function(l){if(!l&&this.hi>>>31){var p=1+~this.lo>>>0,d=~this.hi>>>0;return p||(d=d+1>>>0),-(p+4294967296*d)}return this.lo+4294967296*this.hi},u.prototype.toLong=function(l){return h.Long?new h.Long(0|this.lo,0|this.hi,Boolean(l)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(l)}};var w=String.prototype.charCodeAt;u.fromHash=function(l){return l===b?g:new u((w.call(l,0)|w.call(l,1)<<8|w.call(l,2)<<16|w.call(l,3)<<24)>>>0,(w.call(l,4)|w.call(l,5)<<8|w.call(l,6)<<16|w.call(l,7)<<24)>>>0)},u.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},u.prototype.zzEncode=function(){var l=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^l)>>>0,this.lo=(this.lo<<1^l)>>>0,this},u.prototype.zzDecode=function(){var l=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^l)>>>0,this.hi=(this.hi>>>1^l)>>>0,this},u.prototype.length=function(){var l=this.lo,p=(this.lo>>>28|this.hi<<4)>>>0,d=this.hi>>>24;return 0===d?0===p?l<16384?l<128?1:2:l<2097152?3:4:p<16384?p<128?5:6:p<2097152?7:8:d<128?9:10}},7211:function(J,G,N){"use strict";var h=G;function u(b,w,v){for(var l=Object.keys(w),p=0;pb,set:void 0,enumerable:!1,configurable:!0},toString:{value(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),w}h.asPromise=N(1280),h.base64=N(9039),h.EventEmitter=N(9889),h.float=N(530),h.inquire=N(716),h.utf8=N(7768),h.pool=N(4479),h.LongBits=N(942),h.isNode=Boolean(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node),h.global=h.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||this,h.emptyArray=Object.freeze?Object.freeze([]):[],h.emptyObject=Object.freeze?Object.freeze({}):{},h.isInteger=Number.isInteger||function(w){return"number"==typeof w&&isFinite(w)&&Math.floor(w)===w},h.isString=function(w){return"string"==typeof w||w instanceof String},h.isObject=function(w){return w&&"object"==typeof w},h.isset=h.isSet=function(w,v){var l=w[v];return!(null==l||!w.hasOwnProperty(v))&&("object"!=typeof l||(Array.isArray(l)?l.length:Object.keys(l).length)>0)},h.Buffer=function(){try{var b=h.inquire("buffer").Buffer;return b.prototype.utf8Write?b:null}catch{return null}}(),h._Buffer_from=null,h._Buffer_allocUnsafe=null,h.newBuffer=function(w){return"number"==typeof w?h.Buffer?h._Buffer_allocUnsafe(w):new h.Array(w):h.Buffer?h._Buffer_from(w):typeof Uint8Array>"u"?w:new Uint8Array(w)},h.Array=typeof Uint8Array<"u"?Uint8Array:Array,h.Long=h.global.dcodeIO&&h.global.dcodeIO.Long||h.global.Long||h.inquire("long"),h.key2Re=/^true|false|0|1$/,h.key32Re=/^-?(?:0|[1-9][0-9]*)$/,h.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,h.longToHash=function(w){return w?h.LongBits.from(w).toHash():h.LongBits.zeroHash},h.longFromHash=function(w,v){var l=h.LongBits.fromHash(w);return h.Long?h.Long.fromBits(l.lo,l.hi,v):l.toNumber(Boolean(v))},h.merge=u,h.lcFirst=function(w){return w.charAt(0).toLowerCase()+w.substring(1)},h.newError=g,h.ProtocolError=g("ProtocolError"),h.oneOfGetter=function(w){for(var v={},l=0;l-1;--d)if(1===v[p[d]]&&null!=this[p[d]])return p[d]}},h.oneOfSetter=function(w){return function(v){for(var l=0;l{"use strict";J.exports=function v(l){var p=u.codegen(["m"],l.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),_={};l.oneofsArray.length&&p("var p={}");for(var I=0;I{"use strict";var h=G,u=N(1413);h[".google.protobuf.Any"]={fromObject:function(g){if(g&&g["@type"]){var b=g["@type"].substring(g["@type"].lastIndexOf("/")+1),w=this.lookup(b);if(w){var v="."===g["@type"].charAt(0)?g["@type"].slice(1):g["@type"];return-1===v.indexOf("/")&&(v="/"+v),this.create({type_url:v,value:w.encode(w.fromObject(g)).finish()})}}return this.fromObject(g)},toObject:function(g,b){var v="",l="";if(b&&b.json&&g.type_url&&g.value){l=g.type_url.substring(g.type_url.lastIndexOf("/")+1),v=g.type_url.substring(0,g.type_url.lastIndexOf("/")+1);var p=this.lookup(l);p&&(g=p.decode(g.value))}if(!(g instanceof this.ctor)&&g instanceof u){var d=g.$type.toObject(g,b),_="."===g.$type.fullName[0]?g.$type.fullName.slice(1):g.$type.fullName;return""===v&&(v="type.googleapis.com/"),d["@type"]=l=v+_,d}return this.toObject(g,b)}}},1650:(J,G,N)=>{"use strict";J.exports=d;var u,h=N(7211),g=h.LongBits,b=h.base64,w=h.utf8;function v(P,D,x){this.fn=P,this.len=D,this.next=void 0,this.val=x}function l(){}function p(P){this.head=P.head,this.tail=P.tail,this.len=P.len,this.next=P.states}function d(){this.len=0,this.head=new v(l,0,0),this.tail=this.head,this.states=null}var _=function(){return h.Buffer?function(){return(d.create=function(){return new u})()}:function(){return new d}};function I(P,D,x){D[x]=255&P}function y(P,D){this.len=P,this.next=void 0,this.val=D}function f(P,D,x){for(;P.hi;)D[x++]=127&P.lo|128,P.lo=(P.lo>>>7|P.hi<<25)>>>0,P.hi>>>=7;for(;P.lo>127;)D[x++]=127&P.lo|128,P.lo=P.lo>>>7;D[x++]=P.lo}function C(P,D,x){D[x]=255&P,D[x+1]=P>>>8&255,D[x+2]=P>>>16&255,D[x+3]=P>>>24}d.create=_(),d.alloc=function(D){return new h.Array(D)},h.Array!==Array&&(d.alloc=h.pool(d.alloc,h.Array.prototype.subarray)),d.prototype._push=function(D,x,M){return this.tail=this.tail.next=new v(D,x,M),this.len+=x,this},(y.prototype=Object.create(v.prototype)).fn=function E(P,D,x){for(;P>127;)D[x++]=127&P|128,P>>>=7;D[x]=P},d.prototype.uint32=function(D){return this.len+=(this.tail=this.tail.next=new y((D>>>=0)<128?1:D<16384?2:D<2097152?3:D<268435456?4:5,D)).len,this},d.prototype.int32=function(D){return D<0?this._push(f,10,g.fromNumber(D)):this.uint32(D)},d.prototype.sint32=function(D){return this.uint32((D<<1^D>>31)>>>0)},d.prototype.int64=d.prototype.uint64=function(D){var x=g.from(D);return this._push(f,x.length(),x)},d.prototype.sint64=function(D){var x=g.from(D).zzEncode();return this._push(f,x.length(),x)},d.prototype.bool=function(D){return this._push(I,1,D?1:0)},d.prototype.sfixed32=d.prototype.fixed32=function(D){return this._push(C,4,D>>>0)},d.prototype.sfixed64=d.prototype.fixed64=function(D){var x=g.from(D);return this._push(C,4,x.lo)._push(C,4,x.hi)},d.prototype.float=function(D){return this._push(h.float.writeFloatLE,4,D)},d.prototype.double=function(D){return this._push(h.float.writeDoubleLE,8,D)};var A=h.Array.prototype.set?function(D,x,M){x.set(D,M)}:function(D,x,M){for(var B=0;B>>0;if(!x)return this._push(I,1,0);if(h.isString(D)){var M=d.alloc(x=b.length(D));b.decode(D,M,0),D=M}return this.uint32(x)._push(A,x,D)},d.prototype.string=function(D){var x=w.length(D);return x?this.uint32(x)._push(w.write,x,D):this._push(I,1,0)},d.prototype.fork=function(){return this.states=new p(this),this.head=this.tail=new v(l,0,0),this.len=0,this},d.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new v(l,0,0),this.len=0),this},d.prototype.ldelim=function(){var D=this.head,x=this.tail,M=this.len;return this.reset().uint32(M),M&&(this.tail.next=D.next,this.tail=x,this.len+=M),this},d.prototype.finish=function(){for(var D=this.head.next,x=this.constructor.alloc(this.len),M=0;D;)D.fn(D.val,x,M),M+=D.len,D=D.next;return x},d._configure=function(P){u=P,d.create=_(),u._configure()}},813:(J,G,N)=>{"use strict";J.exports=g;var h=N(1650);(g.prototype=Object.create(h.prototype)).constructor=g;var u=N(7211);function g(){h.call(this)}function b(w,v,l){w.length<40?u.utf8.write(w,v,l):v.utf8Write?v.utf8Write(w,l):v.write(w,l)}g._configure=function(){g.alloc=u._Buffer_allocUnsafe,g.writeBytesBuffer=u.Buffer&&u.Buffer.prototype instanceof Uint8Array&&"set"===u.Buffer.prototype.set.name?function(v,l,p){l.set(v,p)}:function(v,l,p){if(v.copy)v.copy(l,p,0,v.length);else for(var d=0;d>>0;return this.uint32(l),l&&this._push(g.writeBytesBuffer,l,v),this},g.prototype.string=function(v){var l=u.Buffer.byteLength(v);return this.uint32(l),l&&this._push(b,l,v),this},g._configure()},4033:(J,G,N)=>{"use strict";J.exports=w;var h=N(4366),u=w.prototype,g=new Date%1e9;function w(v){this.id=(v=v||{}).id||function b(){return(1e9*Math.random()>>>0)+g++}(),this.max=v.max||1/0,this.items=v.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(v.lastModified||new Date);for(var l,p,d=this.items.length;d--;)l=this.items[d],p=new Date(l.expires)-new Date,this._lookup[l.key]=l,p>0?this.expire(l.key,p):p<=0&&this.delete(l.key)}u.has=function(v){return v in this._lookup},u.get=function(v){if(!this.has(v))return null;var l=this._lookup[v];return l.refresh&&this.expire(v,l.refresh),this.items.splice(this.items.indexOf(l),1),this.items.push(l),l.value},u.meta=function(v){if(!this.has(v))return null;var l=this._lookup[v];return"meta"in l?l.meta:null},u.set=function(v,l,p){var d=this._lookup[v],_=this._lookup[v]={key:v,value:l};return this.lastModified=new Date,d?(clearTimeout(d.timeout),this.items.splice(this.items.indexOf(d),1,_)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(_),this.size++),p&&("ttl"in p&&this.expire(v,p.ttl),"meta"in p&&(_.meta=p.meta),p.refresh&&(_.refresh=p.ttl)),this},u.delete=function(v){var l=this._lookup[v];return!!l&&(this.lastModified=new Date,this.items.splice(this.items.indexOf(l),1),clearTimeout(l.timeout),delete this._lookup[v],this.size--,this)},u.expire=function(v,l){var p=l||0,d=this._lookup[v];if(!d)return this;if("string"==typeof p&&(p=h(l)),"number"!=typeof p)throw new TypeError("Expiration time must be a string or number.");return clearTimeout(d.timeout),d.timeout=setTimeout(this.delete.bind(this,d.key),p),d.expires=Number(new Date)+p,this},u.clear=function(){for(var v=this.items.length;v--;)this.delete(this.items[v].key);return this},u.toJSON=function(){for(var l,v=new Array(this.items.length),p=v.length;p--;)v[p]={key:(l=this.items[p]).key,meta:l.meta,value:l.value,expires:l.expires,refresh:l.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:v}}},2502:(J,G,N)=>{"use strict";const h=N(7806);class u{constructor(w,v,l){const p=this;this._started=h(),this._rescheduled=0,this._scheduled=v,this._args=l,this._triggered=!1,this._timerWrapper=()=>{p._rescheduled>0?(p._scheduled=p._rescheduled-(h()-p._started),p._schedule(p._scheduled)):(p._triggered=!0,w.apply(null,p._args))},this._timer=setTimeout(this._timerWrapper,v)}reschedule(w){w||(w=this._scheduled);const v=h();v+w-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(w)):this._triggered?this._schedule(w):(this._started=v,this._rescheduled=w)}_schedule(w){this._triggered=!1,this._started=h(),this._rescheduled=0,this._scheduled=w,this._timer=setTimeout(this._timerWrapper,w)}clear(){clearTimeout(this._timer)}}J.exports=function g(){if("function"!=typeof arguments[0])throw new Error("callback needed");if("number"!=typeof arguments[1])throw new Error("timeout needed");let b;if(arguments.length>0){b=new Array(arguments.length-2);for(var w=0;w{"use strict";J.exports=function(){return Date.now()}},9014:(J,G,N)=>{"use strict";var h=N(9942),u=/[\/\?<>\\:\*\|"]/g,g=/[\x00-\x1f\x80-\x9f]/g,b=/^\.+$/,w=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,v=/[\. ]+$/;function l(p,d){if("string"!=typeof p)throw new Error("Input must be string");var _=p.replace(u,d).replace(g,d).replace(b,d).replace(w,d).replace(v,d);return h(_,255)}J.exports=function(p,d){var _=d&&d.replacement||"",I=l(p,_);return""===_?I:l(I,"")}},1466:(J,G,N)=>{"use strict";var h=N(7156).default;const u=new Map;function w(){return(w=h(function*(p,d,_){for(;u.get(_);){try{yield p()}catch(I){setTimeout(()=>{throw I},1);break}if(!u.get(_))break;yield new Promise(I=>{const E=setTimeout(I,d);u.set(_,E)})}})).apply(this,arguments)}J.exports={setDelayedInterval:function v(p,d,_){_=_||d;const I=`${Date.now()}:${Math.floor(1e6*Math.random())}`,E=setTimeout(()=>{!function b(p,d,_){w.apply(this,arguments)}(p,d,I)},_);return u.set(I,E),I},clearDelayedInterval:function l(p){const d=u.get(p);d&&(clearTimeout(d),u.delete(p))}}},1420:(J,G,N)=>{"use strict";const{AbortController:h}=globalThis,u=N(2502);class g extends h{constructor(w){super(),this._ms=w,this._timer=u(()=>this.abort(),w),Object.setPrototypeOf(this,g.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=u(()=>this.abort(),this._ms)}}J.exports={TimeoutController:g}},9942:(J,G,N)=>{"use strict";var h=N(8831),u=N(8871);J.exports=h.bind(null,u)},8831:J=>{"use strict";function N(h){return h>=56320&&h<=57343}J.exports=function(u,g,b){if("string"!=typeof g)throw new Error("Input must be string");for(var l,p,w=g.length,v=0,d=0;d=55296&&h<=56319&&N(g.charCodeAt(d+1))&&(p+=g[d+=1]),(v+=u(p))===b)return g.slice(0,d+1);if(v>b)return g.slice(0,d-p.length+1)}var h;return g}},8871:J=>{"use strict";function G(h){return h>=55296&&h<=56319}J.exports=function(u){if("string"!=typeof u)throw new Error("Input must be string");for(var g=u.length,b=0,w=null,v=null,l=0;l=56320&&h<=57343?null!=v&&G(v)?b+=1:b+=3:w<=127?b+=1:w>=128&&w<=2047?b+=2:w>=2048&&w<=65535&&(b+=3),v=w;var h;return b}},3004:J=>{J.exports=function h(u,w){var p,b=0,v=0,l=w=w||0,d=u.length;do{if(l>=d||v>49)throw h.bytes=0,new RangeError("Could not decode varint");p=u[l++],b+=v<28?(127&p)<=128);return h.bytes=l-w,b}},5723:J=>{J.exports=function g(b,w,v){if(Number.MAX_SAFE_INTEGER&&b>Number.MAX_SAFE_INTEGER)throw g.bytes=0,new RangeError("Could not encode varint");w=w||[];for(var l=v=v||0;b>=u;)w[v++]=255&b|128,b/=128;for(;-128&b;)w[v++]=255&b|128,b>>>=7;return w[v]=0|b,g.bytes=v-l+1,w};var u=Math.pow(2,31)},1732:(J,G,N)=>{J.exports={encode:N(5723),decode:N(3004),encodingLength:N(4036)}},4036:J=>{var G=Math.pow(2,7),N=Math.pow(2,14),h=Math.pow(2,21),u=Math.pow(2,28),g=Math.pow(2,35),b=Math.pow(2,42),w=Math.pow(2,49),v=Math.pow(2,56),l=Math.pow(2,63);J.exports=function(p){return p{"use strict";!function(ie){const fe=ie.performance;function ye(Ft){fe&&fe.mark&&fe.mark(Ft)}function me(Ft,ut){fe&&fe.measure&&fe.measure(Ft,ut)}ye("Zone");const _e=ie.__Zone_symbol_prefix||"__zone_symbol__";function Ne(Ft){return _e+Ft}const Ye=!0===ie[Ne("forceDuplicateZoneCheck")];if(ie.Zone){if(Ye||"function"!=typeof ie.Zone.__symbol__)throw new Error("Zone already loaded.");return ie.Zone}let qe=(()=>{class Ft{constructor(ce,ve){this._parent=ce,this._name=ve?ve.name||"unnamed":"",this._properties=ve&&ve.properties||{},this._zoneDelegate=new nt(this,this._parent&&this._parent._zoneDelegate,ve)}static assertZonePatched(){if(ie.Promise!==Hr.ZoneAwarePromise)throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.\nMost likely cause is that a Promise polyfill has been loaded after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. If you must load one, do so before loading zone.js.)")}static get root(){let ce=Ft.current;for(;ce.parent;)ce=ce.parent;return ce}static get current(){return bn.zone}static get currentTask(){return vr}static __load_patch(ce,ve,yt=!1){if(Hr.hasOwnProperty(ce)){if(!yt&&Ye)throw Error("Already loaded patch: "+ce)}else if(!ie["__Zone_disable_"+ce]){const St="Zone:"+ce;ye(St),Hr[ce]=ve(ie,Ft,Fn),me(St,St)}}get parent(){return this._parent}get name(){return this._name}get(ce){const ve=this.getZoneWith(ce);if(ve)return ve._properties[ce]}getZoneWith(ce){let ve=this;for(;ve;){if(ve._properties.hasOwnProperty(ce))return ve;ve=ve._parent}return null}fork(ce){if(!ce)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,ce)}wrap(ce,ve){if("function"!=typeof ce)throw new Error("Expecting function got: "+ce);const yt=this._zoneDelegate.intercept(this,ce,ve),St=this;return function(){return St.runGuarded(yt,this,arguments,ve)}}run(ce,ve,yt,St){bn={parent:bn,zone:this};try{return this._zoneDelegate.invoke(this,ce,ve,yt,St)}finally{bn=bn.parent}}runGuarded(ce,ve=null,yt,St){bn={parent:bn,zone:this};try{try{return this._zoneDelegate.invoke(this,ce,ve,yt,St)}catch(mn){if(this._zoneDelegate.handleError(this,mn))throw mn}}finally{bn=bn.parent}}runTask(ce,ve,yt){if(ce.zone!=this)throw new Error("A task can only be run in the zone of creation! (Creation: "+(ce.zone||Pn).name+"; Execution: "+this.name+")");if(ce.state===Bt&&(ce.type===lr||ce.type===bt))return;const St=ce.state!=ft;St&&ce._transitionTo(ft,tn),ce.runCount++;const mn=vr;vr=ce,bn={parent:bn,zone:this};try{ce.type==bt&&ce.data&&!ce.data.isPeriodic&&(ce.cancelFn=void 0);try{return this._zoneDelegate.invokeTask(this,ce,ve,yt)}catch(Ge){if(this._zoneDelegate.handleError(this,Ge))throw Ge}}finally{ce.state!==Bt&&ce.state!==ot&&(ce.type==lr||ce.data&&ce.data.isPeriodic?St&&ce._transitionTo(tn,ft):(ce.runCount=0,this._updateTaskCount(ce,-1),St&&ce._transitionTo(Bt,ft,Bt))),bn=bn.parent,vr=mn}}scheduleTask(ce){if(ce.zone&&ce.zone!==this){let yt=this;for(;yt;){if(yt===ce.zone)throw Error(`can not reschedule task to ${this.name} which is descendants of the original zone ${ce.zone.name}`);yt=yt.parent}}ce._transitionTo(yn,Bt);const ve=[];ce._zoneDelegates=ve,ce._zone=this;try{ce=this._zoneDelegate.scheduleTask(this,ce)}catch(yt){throw ce._transitionTo(ot,yn,Bt),this._zoneDelegate.handleError(this,yt),yt}return ce._zoneDelegates===ve&&this._updateTaskCount(ce,1),ce.state==yn&&ce._transitionTo(tn,yn),ce}scheduleMicroTask(ce,ve,yt,St){return this.scheduleTask(new je(Kt,ce,ve,yt,St,void 0))}scheduleMacroTask(ce,ve,yt,St,mn){return this.scheduleTask(new je(bt,ce,ve,yt,St,mn))}scheduleEventTask(ce,ve,yt,St,mn){return this.scheduleTask(new je(lr,ce,ve,yt,St,mn))}cancelTask(ce){if(ce.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(ce.zone||Pn).name+"; Execution: "+this.name+")");ce._transitionTo(hn,tn,ft);try{this._zoneDelegate.cancelTask(this,ce)}catch(ve){throw ce._transitionTo(ot,hn),this._zoneDelegate.handleError(this,ve),ve}return this._updateTaskCount(ce,-1),ce._transitionTo(Bt,hn),ce.runCount=0,ce}_updateTaskCount(ce,ve){const yt=ce._zoneDelegates;-1==ve&&(ce._zoneDelegates=null);for(let St=0;StFt.hasTask(ce,ve),onScheduleTask:(Ft,ut,ce,ve)=>Ft.scheduleTask(ce,ve),onInvokeTask:(Ft,ut,ce,ve,yt,St)=>Ft.invokeTask(ce,ve,yt,St),onCancelTask:(Ft,ut,ce,ve)=>Ft.cancelTask(ce,ve)};class nt{constructor(ut,ce,ve){this._taskCounts={microTask:0,macroTask:0,eventTask:0},this.zone=ut,this._parentDelegate=ce,this._forkZS=ve&&(ve&&ve.onFork?ve:ce._forkZS),this._forkDlgt=ve&&(ve.onFork?ce:ce._forkDlgt),this._forkCurrZone=ve&&(ve.onFork?this.zone:ce._forkCurrZone),this._interceptZS=ve&&(ve.onIntercept?ve:ce._interceptZS),this._interceptDlgt=ve&&(ve.onIntercept?ce:ce._interceptDlgt),this._interceptCurrZone=ve&&(ve.onIntercept?this.zone:ce._interceptCurrZone),this._invokeZS=ve&&(ve.onInvoke?ve:ce._invokeZS),this._invokeDlgt=ve&&(ve.onInvoke?ce:ce._invokeDlgt),this._invokeCurrZone=ve&&(ve.onInvoke?this.zone:ce._invokeCurrZone),this._handleErrorZS=ve&&(ve.onHandleError?ve:ce._handleErrorZS),this._handleErrorDlgt=ve&&(ve.onHandleError?ce:ce._handleErrorDlgt),this._handleErrorCurrZone=ve&&(ve.onHandleError?this.zone:ce._handleErrorCurrZone),this._scheduleTaskZS=ve&&(ve.onScheduleTask?ve:ce._scheduleTaskZS),this._scheduleTaskDlgt=ve&&(ve.onScheduleTask?ce:ce._scheduleTaskDlgt),this._scheduleTaskCurrZone=ve&&(ve.onScheduleTask?this.zone:ce._scheduleTaskCurrZone),this._invokeTaskZS=ve&&(ve.onInvokeTask?ve:ce._invokeTaskZS),this._invokeTaskDlgt=ve&&(ve.onInvokeTask?ce:ce._invokeTaskDlgt),this._invokeTaskCurrZone=ve&&(ve.onInvokeTask?this.zone:ce._invokeTaskCurrZone),this._cancelTaskZS=ve&&(ve.onCancelTask?ve:ce._cancelTaskZS),this._cancelTaskDlgt=ve&&(ve.onCancelTask?ce:ce._cancelTaskDlgt),this._cancelTaskCurrZone=ve&&(ve.onCancelTask?this.zone:ce._cancelTaskCurrZone),this._hasTaskZS=null,this._hasTaskDlgt=null,this._hasTaskDlgtOwner=null,this._hasTaskCurrZone=null;const yt=ve&&ve.onHasTask;(yt||ce&&ce._hasTaskZS)&&(this._hasTaskZS=yt?ve:st,this._hasTaskDlgt=ce,this._hasTaskDlgtOwner=this,this._hasTaskCurrZone=ut,ve.onScheduleTask||(this._scheduleTaskZS=st,this._scheduleTaskDlgt=ce,this._scheduleTaskCurrZone=this.zone),ve.onInvokeTask||(this._invokeTaskZS=st,this._invokeTaskDlgt=ce,this._invokeTaskCurrZone=this.zone),ve.onCancelTask||(this._cancelTaskZS=st,this._cancelTaskDlgt=ce,this._cancelTaskCurrZone=this.zone))}fork(ut,ce){return this._forkZS?this._forkZS.onFork(this._forkDlgt,this.zone,ut,ce):new qe(ut,ce)}intercept(ut,ce,ve){return this._interceptZS?this._interceptZS.onIntercept(this._interceptDlgt,this._interceptCurrZone,ut,ce,ve):ce}invoke(ut,ce,ve,yt,St){return this._invokeZS?this._invokeZS.onInvoke(this._invokeDlgt,this._invokeCurrZone,ut,ce,ve,yt,St):ce.apply(ve,yt)}handleError(ut,ce){return!this._handleErrorZS||this._handleErrorZS.onHandleError(this._handleErrorDlgt,this._handleErrorCurrZone,ut,ce)}scheduleTask(ut,ce){let ve=ce;if(this._scheduleTaskZS)this._hasTaskZS&&ve._zoneDelegates.push(this._hasTaskDlgtOwner),ve=this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt,this._scheduleTaskCurrZone,ut,ce),ve||(ve=ce);else if(ce.scheduleFn)ce.scheduleFn(ce);else{if(ce.type!=Kt)throw new Error("Task is missing scheduleFn.");vt(ce)}return ve}invokeTask(ut,ce,ve,yt){return this._invokeTaskZS?this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt,this._invokeTaskCurrZone,ut,ce,ve,yt):ce.callback.apply(ve,yt)}cancelTask(ut,ce){let ve;if(this._cancelTaskZS)ve=this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt,this._cancelTaskCurrZone,ut,ce);else{if(!ce.cancelFn)throw Error("Task is not cancelable");ve=ce.cancelFn(ce)}return ve}hasTask(ut,ce){try{this._hasTaskZS&&this._hasTaskZS.onHasTask(this._hasTaskDlgt,this._hasTaskCurrZone,ut,ce)}catch(ve){this.handleError(ut,ve)}}_updateTaskCount(ut,ce){const ve=this._taskCounts,yt=ve[ut],St=ve[ut]=yt+ce;if(St<0)throw new Error("More tasks executed then were scheduled.");0!=yt&&0!=St||this.hasTask(this.zone,{microTask:ve.microTask>0,macroTask:ve.macroTask>0,eventTask:ve.eventTask>0,change:ut})}}class je{constructor(ut,ce,ve,yt,St,mn){if(this._zone=null,this.runCount=0,this._zoneDelegates=null,this._state="notScheduled",this.type=ut,this.source=ce,this.data=yt,this.scheduleFn=St,this.cancelFn=mn,!ve)throw new Error("callback is not defined");this.callback=ve;const Ge=this;this.invoke=ut===lr&&yt&&yt.useG?je.invokeTask:function(){return je.invokeTask.call(ie,Ge,this,arguments)}}static invokeTask(ut,ce,ve){ut||(ut=this),rr++;try{return ut.runCount++,ut.zone.runTask(ut,ce,ve)}finally{1==rr&&et(),rr--}}get zone(){return this._zone}get state(){return this._state}cancelScheduleRequest(){this._transitionTo(Bt,yn)}_transitionTo(ut,ce,ve){if(this._state!==ce&&this._state!==ve)throw new Error(`${this.type} '${this.source}': can not transition to '${ut}', expecting state '${ce}'${ve?" or '"+ve+"'":""}, was '${this._state}'.`);this._state=ut,ut==Bt&&(this._zoneDelegates=null)}toString(){return this.data&&typeof this.data.handleId<"u"?this.data.handleId.toString():Object.prototype.toString.call(this)}toJSON(){return{type:this.type,state:this.state,source:this.source,zone:this.zone.name,runCount:this.runCount}}}const be=Ne("setTimeout"),ge=Ne("Promise"),De=Ne("then");let dt,Ue=[],Be=!1;function Pt(Ft){if(dt||ie[ge]&&(dt=ie[ge].resolve(0)),dt){let ut=dt[De];ut||(ut=dt.then),ut.call(dt,Ft)}else ie[be](Ft,0)}function vt(Ft){0===rr&&0===Ue.length&&Pt(et),Ft&&Ue.push(Ft)}function et(){if(!Be){for(Be=!0;Ue.length;){const Ft=Ue;Ue=[];for(let ut=0;utbn,onUnhandledError:_n,microtaskDrainDone:_n,scheduleMicroTask:vt,showUncaughtError:()=>!qe[Ne("ignoreConsoleErrorUncaughtError")],patchEventTarget:()=>[],patchOnProperties:_n,patchMethod:()=>_n,bindArguments:()=>[],patchThen:()=>_n,patchMacroTask:()=>_n,patchEventPrototype:()=>_n,isIEOrEdge:()=>!1,getGlobalObjects:()=>{},ObjectDefineProperty:()=>_n,ObjectGetOwnPropertyDescriptor:()=>{},ObjectCreate:()=>{},ArraySlice:()=>[],patchClass:()=>_n,wrapWithCurrentZone:()=>_n,filterProperties:()=>[],attachOriginToPatched:()=>_n,_redefineProperty:()=>_n,patchCallbacks:()=>_n,nativeScheduleMicroTask:Pt};let bn={parent:null,zone:new qe(null,null)},vr=null,rr=0;function _n(){}me("Zone","Zone"),ie.Zone=qe}(typeof window<"u"&&window||typeof self<"u"&&self||global);const J=Object.getOwnPropertyDescriptor,G=Object.defineProperty,N=Object.getPrototypeOf,h=Object.create,u=Array.prototype.slice,g="addEventListener",b="removeEventListener",w=Zone.__symbol__(g),v=Zone.__symbol__(b),l="true",p="false",d=Zone.__symbol__("");function _(ie,fe){return Zone.current.wrap(ie,fe)}function I(ie,fe,ye,me,_e){return Zone.current.scheduleMacroTask(ie,fe,ye,me,_e)}const E=Zone.__symbol__,y=typeof window<"u",f=y?window:void 0,C=y&&f||"object"==typeof self&&self||global;function P(ie,fe){for(let ye=ie.length-1;ye>=0;ye--)"function"==typeof ie[ye]&&(ie[ye]=_(ie[ye],fe+"_"+ye));return ie}function x(ie){return!ie||!1!==ie.writable&&!("function"==typeof ie.get&&typeof ie.set>"u")}const M=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,B=!("nw"in C)&&typeof C.process<"u"&&"[object process]"==={}.toString.call(C.process),F=!B&&!M&&!(!y||!f.HTMLElement),z=typeof C.process<"u"&&"[object process]"==={}.toString.call(C.process)&&!M&&!(!y||!f.HTMLElement),S={},O=function(ie){if(!(ie=ie||C.event))return;let fe=S[ie.type];fe||(fe=S[ie.type]=E("ON_PROPERTY"+ie.type));const ye=this||ie.target||C,me=ye[fe];let _e;if(F&&ye===f&&"error"===ie.type){const Ne=ie;_e=me&&me.call(this,Ne.message,Ne.filename,Ne.lineno,Ne.colno,Ne.error),!0===_e&&ie.preventDefault()}else _e=me&&me.apply(this,arguments),null!=_e&&!_e&&ie.preventDefault();return _e};function H(ie,fe,ye){let me=J(ie,fe);if(!me&&ye&&J(ye,fe)&&(me={enumerable:!0,configurable:!0}),!me||!me.configurable)return;const _e=E("on"+fe+"patched");if(ie.hasOwnProperty(_e)&&ie[_e])return;delete me.writable,delete me.value;const Ne=me.get,Ye=me.set,qe=fe.slice(2);let st=S[qe];st||(st=S[qe]=E("ON_PROPERTY"+qe)),me.set=function(nt){let je=this;!je&&ie===C&&(je=C),je&&("function"==typeof je[st]&&je.removeEventListener(qe,O),Ye&&Ye.call(je,null),je[st]=nt,"function"==typeof nt&&je.addEventListener(qe,O,!1))},me.get=function(){let nt=this;if(!nt&&ie===C&&(nt=C),!nt)return null;const je=nt[st];if(je)return je;if(Ne){let be=Ne.call(this);if(be)return me.set.call(this,be),"function"==typeof nt.removeAttribute&&nt.removeAttribute(fe),be}return null},G(ie,fe,me),ie[_e]=!0}function L(ie,fe,ye){if(fe)for(let me=0;mefunction(Ye,qe){const st=ye(Ye,qe);return st.cbIdx>=0&&"function"==typeof qe[st.cbIdx]?I(st.name,qe[st.cbIdx],st,_e):Ne.apply(Ye,qe)})}function Z(ie,fe){ie[E("OriginalDelegate")]=fe}let q=!1,ne=!1;function de(){if(q)return ne;q=!0;try{const ie=f.navigator.userAgent;(-1!==ie.indexOf("MSIE ")||-1!==ie.indexOf("Trident/")||-1!==ie.indexOf("Edge/"))&&(ne=!0)}catch{}return ne}Zone.__load_patch("ZoneAwarePromise",(ie,fe,ye)=>{const me=Object.getOwnPropertyDescriptor,_e=Object.defineProperty,Ye=ye.symbol,qe=[],st=!0===ie[Ye("DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION")],nt=Ye("Promise"),je=Ye("then");ye.onUnhandledError=Ge=>{if(ye.showUncaughtError()){const Qe=Ge&&Ge.rejection;Qe?console.error("Unhandled Promise rejection:",Qe instanceof Error?Qe.message:Qe,"; Zone:",Ge.zone.name,"; Task:",Ge.task&&Ge.task.source,"; Value:",Qe,Qe instanceof Error?Qe.stack:void 0):console.error(Ge)}},ye.microtaskDrainDone=()=>{for(;qe.length;){const Ge=qe.shift();try{Ge.zone.runGuarded(()=>{throw Ge.throwOriginal?Ge.rejection:Ge})}catch(Qe){De(Qe)}}};const ge=Ye("unhandledPromiseRejectionHandler");function De(Ge){ye.onUnhandledError(Ge);try{const Qe=fe[ge];"function"==typeof Qe&&Qe.call(this,Ge)}catch{}}function Ue(Ge){return Ge&&Ge.then}function Be(Ge){return Ge}function dt(Ge){return ce.reject(Ge)}const Pt=Ye("state"),vt=Ye("value"),et=Ye("finally"),Pn=Ye("parentPromiseValue"),Bt=Ye("parentPromiseState"),tn=null,hn=!1;function Kt(Ge,Qe){return Te=>{try{Fn(Ge,Qe,Te)}catch(ze){Fn(Ge,!1,ze)}}}const bt=function(){let Ge=!1;return function(Te){return function(){Ge||(Ge=!0,Te.apply(null,arguments))}}},Hr=Ye("currentTaskTrace");function Fn(Ge,Qe,Te){const ze=bt();if(Ge===Te)throw new TypeError("Promise resolved with itself");if(Ge[Pt]===tn){let ht=null;try{("object"==typeof Te||"function"==typeof Te)&&(ht=Te&&Te.then)}catch(Et){return ze(()=>{Fn(Ge,!1,Et)})(),Ge}if(Qe!==hn&&Te instanceof ce&&Te.hasOwnProperty(Pt)&&Te.hasOwnProperty(vt)&&Te[Pt]!==tn)vr(Te),Fn(Ge,Te[Pt],Te[vt]);else if(Qe!==hn&&"function"==typeof ht)try{ht.call(Te,ze(Kt(Ge,Qe)),ze(Kt(Ge,!1)))}catch(Et){ze(()=>{Fn(Ge,!1,Et)})()}else{Ge[Pt]=Qe;const Et=Ge[vt];if(Ge[vt]=Te,Ge[et]===et&&!0===Qe&&(Ge[Pt]=Ge[Bt],Ge[vt]=Ge[Pn]),Qe===hn&&Te instanceof Error){const lt=fe.currentTask&&fe.currentTask.data&&fe.currentTask.data.__creationTrace__;lt&&_e(Te,Hr,{configurable:!0,enumerable:!1,writable:!0,value:lt})}for(let lt=0;lt{try{const It=Ge[vt],jt=!!Te&&et===Te[et];jt&&(Te[Pn]=It,Te[Bt]=Et);const Ut=Qe.run(lt,void 0,jt&<!==dt&<!==Be?[]:[It]);Fn(Te,!0,Ut)}catch(It){Fn(Te,!1,It)}},Te)}const Ft=function(){},ut=ie.AggregateError;class ce{static toString(){return"function ZoneAwarePromise() { [native code] }"}static resolve(Qe){return Fn(new this(null),!0,Qe)}static reject(Qe){return Fn(new this(null),hn,Qe)}static any(Qe){if(!Qe||"function"!=typeof Qe[Symbol.iterator])return Promise.reject(new ut([],"All promises were rejected"));const Te=[];let ze=0;try{for(let lt of Qe)ze++,Te.push(ce.resolve(lt))}catch{return Promise.reject(new ut([],"All promises were rejected"))}if(0===ze)return Promise.reject(new ut([],"All promises were rejected"));let ht=!1;const Et=[];return new ce((lt,It)=>{for(let jt=0;jt{ht||(ht=!0,lt(Ut))},Ut=>{Et.push(Ut),ze--,0===ze&&(ht=!0,It(new ut(Et,"All promises were rejected")))})})}static race(Qe){let Te,ze,ht=new this((It,jt)=>{Te=It,ze=jt});function Et(It){Te(It)}function lt(It){ze(It)}for(let It of Qe)Ue(It)||(It=this.resolve(It)),It.then(Et,lt);return ht}static all(Qe){return ce.allWithCallback(Qe)}static allSettled(Qe){return(this&&this.prototype instanceof ce?this:ce).allWithCallback(Qe,{thenCallback:ze=>({status:"fulfilled",value:ze}),errorCallback:ze=>({status:"rejected",reason:ze})})}static allWithCallback(Qe,Te){let ze,ht,Et=new this((Ut,Nn)=>{ze=Ut,ht=Nn}),lt=2,It=0;const jt=[];for(let Ut of Qe){Ue(Ut)||(Ut=this.resolve(Ut));const Nn=It;try{Ut.then(Tn=>{jt[Nn]=Te?Te.thenCallback(Tn):Tn,lt--,0===lt&&ze(jt)},Tn=>{Te?(jt[Nn]=Te.errorCallback(Tn),lt--,0===lt&&ze(jt)):ht(Tn)})}catch(Tn){ht(Tn)}lt++,It++}return lt-=2,0===lt&&ze(jt),Et}constructor(Qe){const Te=this;if(!(Te instanceof ce))throw new Error("Must be an instanceof Promise.");Te[Pt]=tn,Te[vt]=[];try{const ze=bt();Qe&&Qe(ze(Kt(Te,!0)),ze(Kt(Te,hn)))}catch(ze){Fn(Te,!1,ze)}}get[Symbol.toStringTag](){return"Promise"}get[Symbol.species](){return ce}then(Qe,Te){var ze;let ht=null===(ze=this.constructor)||void 0===ze?void 0:ze[Symbol.species];(!ht||"function"!=typeof ht)&&(ht=this.constructor||ce);const Et=new ht(Ft),lt=fe.current;return this[Pt]==tn?this[vt].push(lt,Et,Qe,Te):rr(this,lt,Et,Qe,Te),Et}catch(Qe){return this.then(null,Qe)}finally(Qe){var Te;let ze=null===(Te=this.constructor)||void 0===Te?void 0:Te[Symbol.species];(!ze||"function"!=typeof ze)&&(ze=ce);const ht=new ze(Ft);ht[et]=et;const Et=fe.current;return this[Pt]==tn?this[vt].push(Et,ht,Qe,Qe):rr(this,Et,ht,Qe,Qe),ht}}ce.resolve=ce.resolve,ce.reject=ce.reject,ce.race=ce.race,ce.all=ce.all;const ve=ie[nt]=ie.Promise;ie.Promise=ce;const yt=Ye("thenPatched");function St(Ge){const Qe=Ge.prototype,Te=me(Qe,"then");if(Te&&(!1===Te.writable||!Te.configurable))return;const ze=Qe.then;Qe[je]=ze,Ge.prototype.then=function(ht,Et){return new ce((It,jt)=>{ze.call(this,It,jt)}).then(ht,Et)},Ge[yt]=!0}return ye.patchThen=St,ve&&(St(ve),$(ie,"fetch",Ge=>function mn(Ge){return function(Qe,Te){let ze=Ge.apply(Qe,Te);if(ze instanceof ce)return ze;let ht=ze.constructor;return ht[yt]||St(ht),ze}}(Ge))),Promise[fe.__symbol__("uncaughtPromiseErrors")]=qe,ce}),Zone.__load_patch("toString",ie=>{const fe=Function.prototype.toString,ye=E("OriginalDelegate"),me=E("Promise"),_e=E("Error"),Ne=function(){if("function"==typeof this){const nt=this[ye];if(nt)return"function"==typeof nt?fe.call(nt):Object.prototype.toString.call(nt);if(this===Promise){const je=ie[me];if(je)return fe.call(je)}if(this===Error){const je=ie[_e];if(je)return fe.call(je)}}return fe.call(this)};Ne[ye]=fe,Function.prototype.toString=Ne;const Ye=Object.prototype.toString;Object.prototype.toString=function(){return"function"==typeof Promise&&this instanceof Promise?"[object Promise]":Ye.call(this)}});let pe=!1;if(typeof window<"u")try{const ie=Object.defineProperty({},"passive",{get:function(){pe=!0}});window.addEventListener("test",ie,ie),window.removeEventListener("test",ie,ie)}catch{pe=!1}const ke={useG:!0},Se={},Pe={},we=new RegExp("^"+d+"(\\w+)(true|false)$"),$e=E("propagationStopped");function K(ie,fe){const ye=(fe?fe(ie):ie)+p,me=(fe?fe(ie):ie)+l,_e=d+ye,Ne=d+me;Se[ie]={},Se[ie][p]=_e,Se[ie][l]=Ne}function Ee(ie,fe,ye,me){const _e=me&&me.add||g,Ne=me&&me.rm||b,Ye=me&&me.listeners||"eventListeners",qe=me&&me.rmAll||"removeAllListeners",st=E(_e),nt="."+_e+":",ge=function(vt,et,Pn){if(vt.isRemoved)return;const Bt=vt.callback;let yn;"object"==typeof Bt&&Bt.handleEvent&&(vt.callback=ft=>Bt.handleEvent(ft),vt.originalDelegate=Bt);try{vt.invoke(vt,et,[Pn])}catch(ft){yn=ft}const tn=vt.options;return tn&&"object"==typeof tn&&tn.once&&et[Ne].call(et,Pn.type,vt.originalDelegate?vt.originalDelegate:vt.callback,tn),yn};function De(vt,et,Pn){if(!(et=et||ie.event))return;const Bt=vt||et.target||ie,yn=Bt[Se[et.type][Pn?l:p]];if(yn){const tn=[];if(1===yn.length){const ft=ge(yn[0],Bt,et);ft&&tn.push(ft)}else{const ft=yn.slice();for(let hn=0;hn{throw hn})}}}const Ue=function(vt){return De(this,vt,!1)},Be=function(vt){return De(this,vt,!0)};function dt(vt,et){if(!vt)return!1;let Pn=!0;et&&void 0!==et.useG&&(Pn=et.useG);const Bt=et&&et.vh;let yn=!0;et&&void 0!==et.chkDup&&(yn=et.chkDup);let tn=!1;et&&void 0!==et.rt&&(tn=et.rt);let ft=vt;for(;ft&&!ft.hasOwnProperty(_e);)ft=N(ft);if(!ft&&vt[_e]&&(ft=vt),!ft||ft[st])return!1;const hn=et&&et.eventNameToString,ot={},Kt=ft[st]=ft[_e],bt=ft[E(Ne)]=ft[Ne],lr=ft[E(Ye)]=ft[Ye],Hr=ft[E(qe)]=ft[qe];let Fn;function bn(Te,ze){return!pe&&"object"==typeof Te&&Te?!!Te.capture:pe&&ze?"boolean"==typeof Te?{capture:Te,passive:!0}:Te?"object"==typeof Te&&!1!==Te.passive?Object.assign(Object.assign({},Te),{passive:!0}):Te:{passive:!0}:Te}et&&et.prepend&&(Fn=ft[E(et.prepend)]=ft[et.prepend]);const ce=Pn?function(Te){if(!ot.isExisting)return Kt.call(ot.target,ot.eventName,ot.capture?Be:Ue,ot.options)}:function(Te){return Kt.call(ot.target,ot.eventName,Te.invoke,ot.options)},ve=Pn?function(Te){if(!Te.isRemoved){const ze=Se[Te.eventName];let ht;ze&&(ht=ze[Te.capture?l:p]);const Et=ht&&Te.target[ht];if(Et)for(let lt=0;ltfunction(_e,Ne){_e[$e]=!0,me&&me.apply(_e,Ne)})}function Ke(ie,fe,ye,me,_e){const Ne=Zone.__symbol__(me);if(fe[Ne])return;const Ye=fe[Ne]=fe[me];fe[me]=function(qe,st,nt){return st&&st.prototype&&_e.forEach(function(je){const be=`${ye}.${me}::`+je,ge=st.prototype;try{if(ge.hasOwnProperty(je)){const De=ie.ObjectGetOwnPropertyDescriptor(ge,je);De&&De.value?(De.value=ie.wrapWithCurrentZone(De.value,be),ie._redefineProperty(st.prototype,je,De)):ge[je]&&(ge[je]=ie.wrapWithCurrentZone(ge[je],be))}else ge[je]&&(ge[je]=ie.wrapWithCurrentZone(ge[je],be))}catch{}}),Ye.call(fe,qe,st,nt)},ie.attachOriginToPatched(fe[me],Ye)}function We(ie,fe,ye){if(!ye||0===ye.length)return fe;const me=ye.filter(Ne=>Ne.target===ie);if(!me||0===me.length)return fe;const _e=me[0].ignoreProperties;return fe.filter(Ne=>-1===_e.indexOf(Ne))}function Je(ie,fe,ye,me){ie&&L(ie,We(ie,fe,ye),me)}function Xe(ie){return Object.getOwnPropertyNames(ie).filter(fe=>fe.startsWith("on")&&fe.length>2).map(fe=>fe.substring(2))}Zone.__load_patch("util",(ie,fe,ye)=>{const me=Xe(ie);ye.patchOnProperties=L,ye.patchMethod=$,ye.bindArguments=P,ye.patchMacroTask=te;const _e=fe.__symbol__("BLACK_LISTED_EVENTS"),Ne=fe.__symbol__("UNPATCHED_EVENTS");ie[Ne]&&(ie[_e]=ie[Ne]),ie[_e]&&(fe[_e]=fe[Ne]=ie[_e]),ye.patchEventPrototype=xe,ye.patchEventTarget=Ee,ye.isIEOrEdge=de,ye.ObjectDefineProperty=G,ye.ObjectGetOwnPropertyDescriptor=J,ye.ObjectCreate=h,ye.ArraySlice=u,ye.patchClass=re,ye.wrapWithCurrentZone=_,ye.filterProperties=We,ye.attachOriginToPatched=Z,ye._redefineProperty=Object.defineProperty,ye.patchCallbacks=Ke,ye.getGlobalObjects=()=>({globalSources:Pe,zoneSymbolEventNames:Se,eventNames:me,isBrowser:F,isMix:z,isNode:B,TRUE_STR:l,FALSE_STR:p,ZONE_SYMBOL_PREFIX:d,ADD_EVENT_LISTENER_STR:g,REMOVE_EVENT_LISTENER_STR:b})});const pt=E("zoneTask");function Dt(ie,fe,ye,me){let _e=null,Ne=null;ye+=me;const Ye={};function qe(nt){const je=nt.data;return je.args[0]=function(){return nt.invoke.apply(this,arguments)},je.handleId=_e.apply(ie,je.args),nt}function st(nt){return Ne.call(ie,nt.data.handleId)}_e=$(ie,fe+=me,nt=>function(je,be){if("function"==typeof be[0]){const ge={isPeriodic:"Interval"===me,delay:"Timeout"===me||"Interval"===me?be[1]||0:void 0,args:be},De=be[0];be[0]=function(){try{return De.apply(this,arguments)}finally{ge.isPeriodic||("number"==typeof ge.handleId?delete Ye[ge.handleId]:ge.handleId&&(ge.handleId[pt]=null))}};const Ue=I(fe,be[0],ge,qe,st);if(!Ue)return Ue;const Be=Ue.data.handleId;return"number"==typeof Be?Ye[Be]=Ue:Be&&(Be[pt]=Ue),Be&&Be.ref&&Be.unref&&"function"==typeof Be.ref&&"function"==typeof Be.unref&&(Ue.ref=Be.ref.bind(Be),Ue.unref=Be.unref.bind(Be)),"number"==typeof Be||Be?Be:Ue}return nt.apply(ie,be)}),Ne=$(ie,ye,nt=>function(je,be){const ge=be[0];let De;"number"==typeof ge?De=Ye[ge]:(De=ge&&ge[pt],De||(De=ge)),De&&"string"==typeof De.type?"notScheduled"!==De.state&&(De.cancelFn&&De.data.isPeriodic||0===De.runCount)&&("number"==typeof ge?delete Ye[ge]:ge&&(ge[pt]=null),De.zone.cancelTask(De)):nt.apply(ie,be)})}Zone.__load_patch("legacy",ie=>{const fe=ie[Zone.__symbol__("legacyPatch")];fe&&fe()}),Zone.__load_patch("queueMicrotask",(ie,fe,ye)=>{ye.patchMethod(ie,"queueMicrotask",me=>function(_e,Ne){fe.current.scheduleMicroTask("queueMicrotask",Ne[0])})}),Zone.__load_patch("timers",ie=>{const ye="clear";Dt(ie,"set",ye,"Timeout"),Dt(ie,"set",ye,"Interval"),Dt(ie,"set",ye,"Immediate")}),Zone.__load_patch("requestAnimationFrame",ie=>{Dt(ie,"request","cancel","AnimationFrame"),Dt(ie,"mozRequest","mozCancel","AnimationFrame"),Dt(ie,"webkitRequest","webkitCancel","AnimationFrame")}),Zone.__load_patch("blocking",(ie,fe)=>{const ye=["alert","prompt","confirm"];for(let me=0;mefunction(st,nt){return fe.current.run(Ne,ie,nt,qe)})}),Zone.__load_patch("EventTarget",(ie,fe,ye)=>{(function ni(ie,fe){fe.patchEventPrototype(ie,fe)})(ie,ye),function Sr(ie,fe){if(Zone[fe.symbol("patchEventTarget")])return;const{eventNames:ye,zoneSymbolEventNames:me,TRUE_STR:_e,FALSE_STR:Ne,ZONE_SYMBOL_PREFIX:Ye}=fe.getGlobalObjects();for(let st=0;st{re("MutationObserver"),re("WebKitMutationObserver")}),Zone.__load_patch("IntersectionObserver",(ie,fe,ye)=>{re("IntersectionObserver")}),Zone.__load_patch("FileReader",(ie,fe,ye)=>{re("FileReader")}),Zone.__load_patch("on_property",(ie,fe,ye)=>{!function Ot(ie,fe){if(B&&!z||Zone[ie.symbol("patchEvents")])return;const ye=fe.__Zone_ignore_on_properties;let me=[];if(F){const _e=window;me=me.concat(["Document","SVGElement","Element","HTMLElement","HTMLBodyElement","HTMLMediaElement","HTMLFrameSetElement","HTMLFrameElement","HTMLIFrameElement","HTMLMarqueeElement","Worker"]);const Ne=function oe(){try{const ie=f.navigator.userAgent;if(-1!==ie.indexOf("MSIE ")||-1!==ie.indexOf("Trident/"))return!0}catch{}return!1}()?[{target:_e,ignoreProperties:["error"]}]:[];Je(_e,Xe(_e),ye&&ye.concat(Ne),N(_e))}me=me.concat(["XMLHttpRequest","XMLHttpRequestEventTarget","IDBIndex","IDBRequest","IDBOpenDBRequest","IDBDatabase","IDBTransaction","IDBCursor","WebSocket"]);for(let _e=0;_e{!function Wr(ie,fe){const{isBrowser:ye,isMix:me}=fe.getGlobalObjects();(ye||me)&&ie.customElements&&"customElements"in ie&&fe.patchCallbacks(fe,ie.customElements,"customElements","define",["connectedCallback","disconnectedCallback","adoptedCallback","attributeChangedCallback"])}(ie,ye)}),Zone.__load_patch("XHR",(ie,fe)=>{!function st(nt){const je=nt.XMLHttpRequest;if(!je)return;const be=je.prototype;let De=be[w],Ue=be[v];if(!De){const ot=nt.XMLHttpRequestEventTarget;if(ot){const Kt=ot.prototype;De=Kt[w],Ue=Kt[v]}}const Be="readystatechange",dt="scheduled";function Pt(ot){const Kt=ot.data,bt=Kt.target;bt[Ne]=!1,bt[qe]=!1;const lr=bt[_e];De||(De=bt[w],Ue=bt[v]),lr&&Ue.call(bt,Be,lr);const Hr=bt[_e]=()=>{if(bt.readyState===bt.DONE)if(!Kt.aborted&&bt[Ne]&&ot.state===dt){const bn=bt[fe.__symbol__("loadfalse")];if(0!==bt.status&&bn&&bn.length>0){const vr=ot.invoke;ot.invoke=function(){const rr=bt[fe.__symbol__("loadfalse")];for(let _n=0;_nfunction(ot,Kt){return ot[me]=0==Kt[2],ot[Ye]=Kt[1],Pn.apply(ot,Kt)}),yn=E("fetchTaskAborting"),tn=E("fetchTaskScheduling"),ft=$(be,"send",()=>function(ot,Kt){if(!0===fe.current[tn]||ot[me])return ft.apply(ot,Kt);{const bt={target:ot,url:ot[Ye],isPeriodic:!1,args:Kt,aborted:!1},lr=I("XMLHttpRequest.send",vt,bt,Pt,et);ot&&!0===ot[qe]&&!bt.aborted&&lr.state===dt&&lr.invoke()}}),hn=$(be,"abort",()=>function(ot,Kt){const bt=function ge(ot){return ot[ye]}(ot);if(bt&&"string"==typeof bt.type){if(null==bt.cancelFn||bt.data&&bt.data.aborted)return;bt.zone.cancelTask(bt)}else if(!0===fe.current[yn])return hn.apply(ot,Kt)})}(ie);const ye=E("xhrTask"),me=E("xhrSync"),_e=E("xhrListener"),Ne=E("xhrScheduled"),Ye=E("xhrURL"),qe=E("xhrErrorBeforeScheduled")}),Zone.__load_patch("geolocation",ie=>{ie.navigator&&ie.navigator.geolocation&&function D(ie,fe){const ye=ie.constructor.name;for(let me=0;me{const st=function(){return qe.apply(this,P(arguments,ye+"."+_e))};return Z(st,qe),st})(Ne)}}}(ie.navigator.geolocation,["getCurrentPosition","watchPosition"])}),Zone.__load_patch("PromiseRejectionEvent",(ie,fe)=>{function ye(me){return function(_e){Ce(ie,me).forEach(Ye=>{const qe=ie.PromiseRejectionEvent;if(qe){const st=new qe(me,{promise:_e.promise,reason:_e.rejection});Ye.invoke(st)}})}}ie.PromiseRejectionEvent&&(fe[E("unhandledPromiseRejectionHandler")]=ye("unhandledrejection"),fe[E("rejectionHandledHandler")]=ye("rejectionhandled"))})},7420:()=>{},5856:()=>{},5883:()=>{},6577:()=>{},5819:()=>{},8479:function(J,G,N){"use strict";var u,g;u=[N(1873)],void 0!==(g=function(b){var w=b.Reader,v=b.Writer,l=b.util,p=b.roots.default||(b.roots.default={});return p.RPC=function(){function d(I){if(this.subscriptions=[],this.messages=[],I)for(var E=Object.keys(I),y=0;y>>3){case 1:C.subscriptions&&C.subscriptions.length||(C.subscriptions=[]),C.subscriptions.push(p.RPC.SubOpts.decode(E,E.uint32()));break;case 2:C.messages&&C.messages.length||(C.messages=[]),C.messages.push(p.RPC.Message.decode(E,E.uint32()));break;case 3:C.control=p.RPC.ControlMessage.decode(E,E.uint32());break;default:E.skipType(7&A)}}return C},d.fromObject=function(E){if(E instanceof p.RPC)return E;var y=new p.RPC;if(E.subscriptions){if(!Array.isArray(E.subscriptions))throw TypeError(".RPC.subscriptions: array expected");y.subscriptions=[];for(var f=0;f>>3){case 1:P.subscribe=f.bool();break;case 2:P.topic=f.string();break;default:f.skipType(7&D)}}return P},I.fromObject=function(f){if(f instanceof p.RPC.SubOpts)return f;var C=new p.RPC.SubOpts;return null!=f.subscribe&&(C.subscribe=Boolean(f.subscribe)),null!=f.topic&&(C.topic=String(f.topic)),C},I.toObject=function(f,C){C||(C={});var A={};return null!=f.subscribe&&f.hasOwnProperty("subscribe")&&(A.subscribe=f.subscribe,C.oneofs&&(A._subscribe="subscribe")),null!=f.topic&&f.hasOwnProperty("topic")&&(A.topic=f.topic,C.oneofs&&(A._topic="topic")),A},I.prototype.toJSON=function(){return this.constructor.toObject(this,b.util.toJSONOptions)},I}(),d.Message=function(){function I(y){if(y)for(var f=Object.keys(y),C=0;C>>3){case 1:P.from=f.bytes();break;case 2:P.data=f.bytes();break;case 3:P.seqno=f.bytes();break;case 4:P.topic=f.string();break;case 5:P.signature=f.bytes();break;case 6:P.key=f.bytes();break;default:f.skipType(7&D)}}if(!P.hasOwnProperty("topic"))throw l.ProtocolError("missing required 'topic'",{instance:P});return P},I.fromObject=function(f){if(f instanceof p.RPC.Message)return f;var C=new p.RPC.Message;return null!=f.from&&("string"==typeof f.from?l.base64.decode(f.from,C.from=l.newBuffer(l.base64.length(f.from)),0):f.from.length&&(C.from=f.from)),null!=f.data&&("string"==typeof f.data?l.base64.decode(f.data,C.data=l.newBuffer(l.base64.length(f.data)),0):f.data.length&&(C.data=f.data)),null!=f.seqno&&("string"==typeof f.seqno?l.base64.decode(f.seqno,C.seqno=l.newBuffer(l.base64.length(f.seqno)),0):f.seqno.length&&(C.seqno=f.seqno)),null!=f.topic&&(C.topic=String(f.topic)),null!=f.signature&&("string"==typeof f.signature?l.base64.decode(f.signature,C.signature=l.newBuffer(l.base64.length(f.signature)),0):f.signature.length&&(C.signature=f.signature)),null!=f.key&&("string"==typeof f.key?l.base64.decode(f.key,C.key=l.newBuffer(l.base64.length(f.key)),0):f.key.length&&(C.key=f.key)),C},I.toObject=function(f,C){C||(C={});var A={};return C.defaults&&(A.topic=""),null!=f.from&&f.hasOwnProperty("from")&&(A.from=C.bytes===String?l.base64.encode(f.from,0,f.from.length):C.bytes===Array?Array.prototype.slice.call(f.from):f.from,C.oneofs&&(A._from="from")),null!=f.data&&f.hasOwnProperty("data")&&(A.data=C.bytes===String?l.base64.encode(f.data,0,f.data.length):C.bytes===Array?Array.prototype.slice.call(f.data):f.data,C.oneofs&&(A._data="data")),null!=f.seqno&&f.hasOwnProperty("seqno")&&(A.seqno=C.bytes===String?l.base64.encode(f.seqno,0,f.seqno.length):C.bytes===Array?Array.prototype.slice.call(f.seqno):f.seqno,C.oneofs&&(A._seqno="seqno")),null!=f.topic&&f.hasOwnProperty("topic")&&(A.topic=f.topic),null!=f.signature&&f.hasOwnProperty("signature")&&(A.signature=C.bytes===String?l.base64.encode(f.signature,0,f.signature.length):C.bytes===Array?Array.prototype.slice.call(f.signature):f.signature,C.oneofs&&(A._signature="signature")),null!=f.key&&f.hasOwnProperty("key")&&(A.key=C.bytes===String?l.base64.encode(f.key,0,f.key.length):C.bytes===Array?Array.prototype.slice.call(f.key):f.key,C.oneofs&&(A._key="key")),A},I.prototype.toJSON=function(){return this.constructor.toObject(this,b.util.toJSONOptions)},I}(),d.ControlMessage=function(){function I(E){if(this.ihave=[],this.iwant=[],this.graft=[],this.prune=[],E)for(var y=Object.keys(E),f=0;f>>3){case 1:A.ihave&&A.ihave.length||(A.ihave=[]),A.ihave.push(p.RPC.ControlIHave.decode(y,y.uint32()));break;case 2:A.iwant&&A.iwant.length||(A.iwant=[]),A.iwant.push(p.RPC.ControlIWant.decode(y,y.uint32()));break;case 3:A.graft&&A.graft.length||(A.graft=[]),A.graft.push(p.RPC.ControlGraft.decode(y,y.uint32()));break;case 4:A.prune&&A.prune.length||(A.prune=[]),A.prune.push(p.RPC.ControlPrune.decode(y,y.uint32()));break;default:y.skipType(7&P)}}return A},I.fromObject=function(y){if(y instanceof p.RPC.ControlMessage)return y;var f=new p.RPC.ControlMessage;if(y.ihave){if(!Array.isArray(y.ihave))throw TypeError(".RPC.ControlMessage.ihave: array expected");f.ihave=[];for(var C=0;C>>3){case 1:P.topicID=f.string();break;case 2:P.messageIDs&&P.messageIDs.length||(P.messageIDs=[]),P.messageIDs.push(f.bytes());break;default:f.skipType(7&D)}}return P},I.fromObject=function(f){if(f instanceof p.RPC.ControlIHave)return f;var C=new p.RPC.ControlIHave;if(null!=f.topicID&&(C.topicID=String(f.topicID)),f.messageIDs){if(!Array.isArray(f.messageIDs))throw TypeError(".RPC.ControlIHave.messageIDs: array expected");C.messageIDs=[];for(var A=0;A>>3==1?(A.messageIDs&&A.messageIDs.length||(A.messageIDs=[]),A.messageIDs.push(y.bytes())):y.skipType(7&P)}return A},I.fromObject=function(y){if(y instanceof p.RPC.ControlIWant)return y;var f=new p.RPC.ControlIWant;if(y.messageIDs){if(!Array.isArray(y.messageIDs))throw TypeError(".RPC.ControlIWant.messageIDs: array expected");f.messageIDs=[];for(var C=0;C>>3==1?P.topicID=f.string():f.skipType(7&D)}return P},I.fromObject=function(f){if(f instanceof p.RPC.ControlGraft)return f;var C=new p.RPC.ControlGraft;return null!=f.topicID&&(C.topicID=String(f.topicID)),C},I.toObject=function(f,C){C||(C={});var A={};return null!=f.topicID&&f.hasOwnProperty("topicID")&&(A.topicID=f.topicID,C.oneofs&&(A._topicID="topicID")),A},I.prototype.toJSON=function(){return this.constructor.toObject(this,b.util.toJSONOptions)},I}(),d.ControlPrune=function(){function I(y){if(this.peers=[],y)for(var f=Object.keys(y),C=0;C>>3){case 1:P.topicID=f.string();break;case 2:P.peers&&P.peers.length||(P.peers=[]),P.peers.push(p.RPC.PeerInfo.decode(f,f.uint32()));break;case 3:P.backoff=f.uint64();break;default:f.skipType(7&D)}}return P},I.fromObject=function(f){if(f instanceof p.RPC.ControlPrune)return f;var C=new p.RPC.ControlPrune;if(null!=f.topicID&&(C.topicID=String(f.topicID)),f.peers){if(!Array.isArray(f.peers))throw TypeError(".RPC.ControlPrune.peers: array expected");C.peers=[];for(var A=0;A>>0,f.backoff.high>>>0).toNumber(!0))),C},I.toObject=function(f,C){C||(C={});var A={};if((C.arrays||C.defaults)&&(A.peers=[]),null!=f.topicID&&f.hasOwnProperty("topicID")&&(A.topicID=f.topicID,C.oneofs&&(A._topicID="topicID")),f.peers&&f.peers.length){A.peers=[];for(var P=0;P>>0,f.backoff.high>>>0).toNumber(!0):f.backoff,C.oneofs&&(A._backoff="backoff")),A},I.prototype.toJSON=function(){return this.constructor.toObject(this,b.util.toJSONOptions)},I}(),d.PeerInfo=function(){function I(y){if(y)for(var f=Object.keys(y),C=0;C>>3){case 1:P.peerID=f.bytes();break;case 2:P.signedPeerRecord=f.bytes();break;default:f.skipType(7&D)}}return P},I.fromObject=function(f){if(f instanceof p.RPC.PeerInfo)return f;var C=new p.RPC.PeerInfo;return null!=f.peerID&&("string"==typeof f.peerID?l.base64.decode(f.peerID,C.peerID=l.newBuffer(l.base64.length(f.peerID)),0):f.peerID.length&&(C.peerID=f.peerID)),null!=f.signedPeerRecord&&("string"==typeof f.signedPeerRecord?l.base64.decode(f.signedPeerRecord,C.signedPeerRecord=l.newBuffer(l.base64.length(f.signedPeerRecord)),0):f.signedPeerRecord.length&&(C.signedPeerRecord=f.signedPeerRecord)),C},I.toObject=function(f,C){C||(C={});var A={};return null!=f.peerID&&f.hasOwnProperty("peerID")&&(A.peerID=C.bytes===String?l.base64.encode(f.peerID,0,f.peerID.length):C.bytes===Array?Array.prototype.slice.call(f.peerID):f.peerID,C.oneofs&&(A._peerID="peerID")),null!=f.signedPeerRecord&&f.hasOwnProperty("signedPeerRecord")&&(A.signedPeerRecord=C.bytes===String?l.base64.encode(f.signedPeerRecord,0,f.signedPeerRecord.length):C.bytes===Array?Array.prototype.slice.call(f.signedPeerRecord):f.signedPeerRecord,C.oneofs&&(A._signedPeerRecord="signedPeerRecord")),A},I.prototype.toJSON=function(){return this.constructor.toObject(this,b.util.toJSONOptions)},I}(),d}(),p}.apply(G,u))&&(J.exports=g)},4642:(J,G,N)=>{var h=N(9805);function u(g){var b,w;function l(d,_){try{var I=g[d](_),E=I.value,y=E instanceof h;Promise.resolve(y?E.wrapped:E).then(function(f){y?l("return"===d?"return":"next",f):p(I.done?"return":"normal",f)},function(f){l("throw",f)})}catch(f){p("throw",f)}}function p(d,_){switch(d){case"return":b.resolve({value:_,done:!0});break;case"throw":b.reject(_);break;default:b.resolve({value:_,done:!1})}(b=b.next)?l(b.key,b.arg):w=null}this._invoke=function v(d,_){return new Promise(function(I,E){var y={key:d,arg:_,resolve:I,reject:E,next:null};w?w=w.next=y:(b=w=y,l(d,_))})},"function"!=typeof g.return&&(this.return=void 0)}u.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},u.prototype.next=function(g){return this._invoke("next",g)},u.prototype.throw=function(g){return this._invoke("throw",g)},u.prototype.return=function(g){return this._invoke("return",g)},J.exports=u,J.exports.__esModule=!0,J.exports.default=J.exports},9805:J=>{J.exports=function G(N){this.wrapped=N},J.exports.__esModule=!0,J.exports.default=J.exports},8131:J=>{J.exports=function G(N,h){var u={},g=!1;function b(w,v){return g=!0,v=new Promise(function(l){l(N[w](v))}),{done:!1,value:h(v)}}return u[typeof Symbol<"u"&&Symbol.iterator||"@@iterator"]=function(){return this},u.next=function(w){return g?(g=!1,w):b("next",w)},"function"==typeof N.throw&&(u.throw=function(w){if(g)throw g=!1,w;return b("throw",w)}),"function"==typeof N.return&&(u.return=function(w){return g?(g=!1,w):b("return",w)}),u},J.exports.__esModule=!0,J.exports.default=J.exports},8237:J=>{function N(h){function u(g){if(Object(g)!==g)return Promise.reject(new TypeError(g+" is not an object."));var b=g.done;return Promise.resolve(g.value).then(function(w){return{value:w,done:b}})}return(N=function(b){this.s=b,this.n=b.next}).prototype={s:null,n:null,next:function(){return u(this.n.apply(this.s,arguments))},return:function(b){var w=this.s.return;return void 0===w?Promise.resolve({value:b,done:!0}):u(w.apply(this.s,arguments))},throw:function(b){var w=this.s.return;return void 0===w?Promise.reject(b):u(w.apply(this.s,arguments))}},new N(h)}J.exports=function G(h){var u,g,b,w=2;for(typeof Symbol<"u"&&(g=Symbol.asyncIterator,b=Symbol.iterator);w--;){if(g&&null!=(u=h[g]))return u.call(h);if(b&&null!=(u=h[b]))return new N(u.call(h));g="@@asyncIterator",b="@@iterator"}throw new TypeError("Object is not async iterable")},J.exports.__esModule=!0,J.exports.default=J.exports},7156:J=>{function G(h,u,g,b,w,v,l){try{var p=h[v](l),d=p.value}catch(_){return void g(_)}p.done?u(d):Promise.resolve(d).then(b,w)}J.exports=function N(h){return function(){var u=this,g=arguments;return new Promise(function(b,w){var v=h.apply(u,g);function l(d){G(v,b,w,l,p,"next",d)}function p(d){G(v,b,w,l,p,"throw",d)}l(void 0)})}},J.exports.__esModule=!0,J.exports.default=J.exports},6737:(J,G,N)=>{var h=N(9805);J.exports=function u(g){return new h(g)},J.exports.__esModule=!0,J.exports.default=J.exports},8186:(J,G,N)=>{var h=N(4642);J.exports=function u(g){return function(){return new h(g.apply(this,arguments))}},J.exports.__esModule=!0,J.exports.default=J.exports}},J=>{J(J.s=623)}]); \ No newline at end of file diff --git a/relay-angular-chat/runtime.85abfe8aa64fdd33.js b/relay-angular-chat/runtime.85abfe8aa64fdd33.js new file mode 100644 index 0000000..a7d90cf --- /dev/null +++ b/relay-angular-chat/runtime.85abfe8aa64fdd33.js @@ -0,0 +1 @@ +(()=>{"use strict";var e,u={},b={};function t(e){var f=b[e];if(void 0!==f)return f.exports;var r=b[e]={exports:{}};return u[e].call(r.exports,r,r.exports,t),r.exports}t.m=u,t.amdO={},e=[],t.O=(f,r,o,a)=>{if(!r){var l=1/0;for(n=0;n=a)&&Object.keys(t.O).every(h=>t.O[h](r[c]))?r.splice(c--,1):(i=!1,a0&&e[n-1][2]>a;n--)e[n]=e[n-1];e[n]=[r,o,a]},t.n=e=>{var f=e&&e.__esModule?()=>e.default:()=>e;return t.d(f,{a:f}),f},(()=>{var f,e=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__;t.t=function(r,o){if(1&o&&(r=this(r)),8&o||"object"==typeof r&&r&&(4&o&&r.__esModule||16&o&&"function"==typeof r.then))return r;var a=Object.create(null);t.r(a);var n={};f=f||[null,e({}),e([]),e(e)];for(var l=2&o&&r;"object"==typeof l&&!~f.indexOf(l);l=e(l))Object.getOwnPropertyNames(l).forEach(i=>n[i]=()=>r[i]);return n.default=()=>r,t.d(a,n),a}})(),t.d=(e,f)=>{for(var r in f)t.o(f,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:f[r]})},t.o=(e,f)=>Object.prototype.hasOwnProperty.call(e,f),t.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e={666:0};t.O.j=o=>0===e[o];var f=(o,a)=>{var c,_,[n,l,i]=a,s=0;if(n.some(d=>0!==e[d])){for(c in l)t.o(l,c)&&(t.m[c]=l[c]);if(i)var p=i(t)}for(o&&o(a);s + + + + + + JS-Waku Chat + + + + +

Waku Node Status

+
+ + + + +

Messages

+
+ + + + + + diff --git a/relay-reactjs-chat/asset-manifest.json b/relay-reactjs-chat/asset-manifest.json new file mode 100644 index 0000000..e5db531 --- /dev/null +++ b/relay-reactjs-chat/asset-manifest.json @@ -0,0 +1,13 @@ +{ + "files": { + "main.css": "/relay-reactjs-chat/static/css/main.e6c13ad2.css", + "main.js": "/relay-reactjs-chat/static/js/main.d422f314.js", + "index.html": "/relay-reactjs-chat/index.html", + "main.e6c13ad2.css.map": "/relay-reactjs-chat/static/css/main.e6c13ad2.css.map", + "main.d422f314.js.map": "/relay-reactjs-chat/static/js/main.d422f314.js.map" + }, + "entrypoints": [ + "static/css/main.e6c13ad2.css", + "static/js/main.d422f314.js" + ] +} \ No newline at end of file diff --git a/relay-reactjs-chat/favicon.ico b/relay-reactjs-chat/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..a11777cc471a4344702741ab1c8a588998b1311a GIT binary patch literal 3870 zcma);c{J4h9>;%nil|2-o+rCuEF-(I%-F}ijC~o(k~HKAkr0)!FCj~d>`RtpD?8b; zXOC1OD!V*IsqUwzbMF1)-gEDD=A573Z-&G7^LoAC9|WO7Xc0Cx1g^Zu0u_SjAPB3vGa^W|sj)80f#V0@M_CAZTIO(t--xg= z!sii`1giyH7EKL_+Wi0ab<)&E_0KD!3Rp2^HNB*K2@PHCs4PWSA32*-^7d{9nH2_E zmC{C*N*)(vEF1_aMamw2A{ZH5aIDqiabnFdJ|y0%aS|64E$`s2ccV~3lR!u<){eS` z#^Mx6o(iP1Ix%4dv`t@!&Za-K@mTm#vadc{0aWDV*_%EiGK7qMC_(`exc>-$Gb9~W!w_^{*pYRm~G zBN{nA;cm^w$VWg1O^^<6vY`1XCD|s_zv*g*5&V#wv&s#h$xlUilPe4U@I&UXZbL z0)%9Uj&@yd03n;!7do+bfixH^FeZ-Ema}s;DQX2gY+7g0s(9;`8GyvPY1*vxiF&|w z>!vA~GA<~JUqH}d;DfBSi^IT*#lrzXl$fNpq0_T1tA+`A$1?(gLb?e#0>UELvljtQ zK+*74m0jn&)5yk8mLBv;=@}c{t0ztT<v;Avck$S6D`Z)^c0(jiwKhQsn|LDRY&w(Fmi91I7H6S;b0XM{e zXp0~(T@k_r-!jkLwd1_Vre^v$G4|kh4}=Gi?$AaJ)3I+^m|Zyj#*?Kp@w(lQdJZf4 z#|IJW5z+S^e9@(6hW6N~{pj8|NO*>1)E=%?nNUAkmv~OY&ZV;m-%?pQ_11)hAr0oAwILrlsGawpxx4D43J&K=n+p3WLnlDsQ$b(9+4 z?mO^hmV^F8MV{4Lx>(Q=aHhQ1){0d*(e&s%G=i5rq3;t{JC zmgbn5Nkl)t@fPH$v;af26lyhH!k+#}_&aBK4baYPbZy$5aFx4}ka&qxl z$=Rh$W;U)>-=S-0=?7FH9dUAd2(q#4TCAHky!$^~;Dz^j|8_wuKc*YzfdAht@Q&ror?91Dm!N03=4=O!a)I*0q~p0g$Fm$pmr$ zb;wD;STDIi$@M%y1>p&_>%?UP($15gou_ue1u0!4(%81;qcIW8NyxFEvXpiJ|H4wz z*mFT(qVx1FKufG11hByuX%lPk4t#WZ{>8ka2efjY`~;AL6vWyQKpJun2nRiZYDij$ zP>4jQXPaP$UC$yIVgGa)jDV;F0l^n(V=HMRB5)20V7&r$jmk{UUIe zVjKroK}JAbD>B`2cwNQ&GDLx8{pg`7hbA~grk|W6LgiZ`8y`{Iq0i>t!3p2}MS6S+ zO_ruKyAElt)rdS>CtF7j{&6rP-#c=7evGMt7B6`7HG|-(WL`bDUAjyn+k$mx$CH;q2Dz4x;cPP$hW=`pFfLO)!jaCL@V2+F)So3}vg|%O*^T1j>C2lx zsURO-zIJC$^$g2byVbRIo^w>UxK}74^TqUiRR#7s_X$e)$6iYG1(PcW7un-va-S&u zHk9-6Zn&>T==A)lM^D~bk{&rFzCi35>UR!ZjQkdSiNX*-;l4z9j*7|q`TBl~Au`5& z+c)*8?#-tgUR$Zd%Q3bs96w6k7q@#tUn`5rj+r@_sAVVLqco|6O{ILX&U-&-cbVa3 zY?ngHR@%l{;`ri%H*0EhBWrGjv!LE4db?HEWb5mu*t@{kv|XwK8?npOshmzf=vZA@ zVSN9sL~!sn?r(AK)Q7Jk2(|M67Uy3I{eRy z_l&Y@A>;vjkWN5I2xvFFTLX0i+`{qz7C_@bo`ZUzDugfq4+>a3?1v%)O+YTd6@Ul7 zAfLfm=nhZ`)P~&v90$&UcF+yXm9sq!qCx3^9gzIcO|Y(js^Fj)Rvq>nQAHI92ap=P z10A4@prk+AGWCb`2)dQYFuR$|H6iDE8p}9a?#nV2}LBCoCf(Xi2@szia7#gY>b|l!-U`c}@ zLdhvQjc!BdLJvYvzzzngnw51yRYCqh4}$oRCy-z|v3Hc*d|?^Wj=l~18*E~*cR_kU z{XsxM1i{V*4GujHQ3DBpl2w4FgFR48Nma@HPgnyKoIEY-MqmMeY=I<%oG~l!f<+FN z1ZY^;10j4M4#HYXP zw5eJpA_y(>uLQ~OucgxDLuf}fVs272FaMxhn4xnDGIyLXnw>Xsd^J8XhcWIwIoQ9} z%FoSJTAGW(SRGwJwb=@pY7r$uQRK3Zd~XbxU)ts!4XsJrCycrWSI?e!IqwqIR8+Jh zlRjZ`UO1I!BtJR_2~7AbkbSm%XQqxEPkz6BTGWx8e}nQ=w7bZ|eVP4?*Tb!$(R)iC z9)&%bS*u(lXqzitAN)Oo=&Ytn>%Hzjc<5liuPi>zC_nw;Z0AE3Y$Jao_Q90R-gl~5 z_xAb2J%eArrC1CN4G$}-zVvCqF1;H;abAu6G*+PDHSYFx@Tdbfox*uEd3}BUyYY-l zTfEsOqsi#f9^FoLO;ChK<554qkri&Av~SIM*{fEYRE?vH7pTAOmu2pz3X?Wn*!ROX ztd54huAk&mFBemMooL33RV-*1f0Q3_(7hl$<#*|WF9P!;r;4_+X~k~uKEqdzZ$5Al zV63XN@)j$FN#cCD;ek1R#l zv%pGrhB~KWgoCj%GT?%{@@o(AJGt*PG#l3i>lhmb_twKH^EYvacVY-6bsCl5*^~L0 zonm@lk2UvvTKr2RS%}T>^~EYqdL1q4nD%0n&Xqr^cK^`J5W;lRRB^R-O8b&HENO||mo0xaD+S=I8RTlIfVgqN@SXDr2&-)we--K7w= zJVU8?Z+7k9dy;s;^gDkQa`0nz6N{T?(A&Iz)2!DEecLyRa&FI!id#5Z7B*O2=PsR0 zEvc|8{NS^)!d)MDX(97Xw}m&kEO@5jqRaDZ!+%`wYOI<23q|&js`&o4xvjP7D_xv@ z5hEwpsp{HezI9!~6O{~)lLR@oF7?J7i>1|5a~UuoN=q&6N}EJPV_GD`&M*v8Y`^2j zKII*d_@Fi$+i*YEW+Hbzn{iQk~yP z>7N{S4)r*!NwQ`(qcN#8SRQsNK6>{)X12nbF`*7#ecO7I)Q$uZsV+xS4E7aUn+U(K baj7?x%VD!5Cxk2YbYLNVeiXvvpMCWYo=by@ literal 0 HcmV?d00001 diff --git a/relay-reactjs-chat/index.html b/relay-reactjs-chat/index.html new file mode 100644 index 0000000..4d2ba14 --- /dev/null +++ b/relay-reactjs-chat/index.html @@ -0,0 +1 @@ +React App
\ No newline at end of file diff --git a/relay-reactjs-chat/logo192.png b/relay-reactjs-chat/logo192.png new file mode 100644 index 0000000000000000000000000000000000000000..fc44b0a3796c0e0a64c3d858ca038bd4570465d9 GIT binary patch literal 5347 zcmZWtbyO6NvR-oO24RV%BvuJ&=?+<7=`LvyB&A_#M7mSDYw1v6DJkiYl9XjT!%$dLEBTQ8R9|wd3008in6lFF3GV-6mLi?MoP_y~}QUnaDCHI#t z7w^m$@6DI)|C8_jrT?q=f8D?0AM?L)Z}xAo^e^W>t$*Y0KlT5=@bBjT9kxb%-KNdk zeOS1tKO#ChhG7%{ApNBzE2ZVNcxbrin#E1TiAw#BlUhXllzhN$qWez5l;h+t^q#Eav8PhR2|T}y5kkflaK`ba-eoE+Z2q@o6P$)=&` z+(8}+-McnNO>e#$Rr{32ngsZIAX>GH??tqgwUuUz6kjns|LjsB37zUEWd|(&O!)DY zQLrq%Y>)Y8G`yYbYCx&aVHi@-vZ3|ebG!f$sTQqMgi0hWRJ^Wc+Ibv!udh_r%2|U) zPi|E^PK?UE!>_4`f`1k4hqqj_$+d!EB_#IYt;f9)fBOumGNyglU(ofY`yHq4Y?B%- zp&G!MRY<~ajTgIHErMe(Z8JG*;D-PJhd@RX@QatggM7+G(Lz8eZ;73)72Hfx5KDOE zkT(m}i2;@X2AT5fW?qVp?@WgN$aT+f_6eo?IsLh;jscNRp|8H}Z9p_UBO^SJXpZew zEK8fz|0Th%(Wr|KZBGTM4yxkA5CFdAj8=QSrT$fKW#tweUFqr0TZ9D~a5lF{)%-tTGMK^2tz(y2v$i%V8XAxIywrZCp=)83p(zIk6@S5AWl|Oa2hF`~~^W zI;KeOSkw1O#TiQ8;U7OPXjZM|KrnN}9arP)m0v$c|L)lF`j_rpG(zW1Qjv$=^|p*f z>)Na{D&>n`jOWMwB^TM}slgTEcjxTlUby89j1)|6ydRfWERn3|7Zd2&e7?!K&5G$x z`5U3uFtn4~SZq|LjFVrz$3iln-+ucY4q$BC{CSm7Xe5c1J<=%Oagztj{ifpaZk_bQ z9Sb-LaQMKp-qJA*bP6DzgE3`}*i1o3GKmo2pn@dj0;He}F=BgINo};6gQF8!n0ULZ zL>kC0nPSFzlcB7p41doao2F7%6IUTi_+!L`MM4o*#Y#0v~WiO8uSeAUNp=vA2KaR&=jNR2iVwG>7t%sG2x_~yXzY)7K& zk3p+O0AFZ1eu^T3s};B%6TpJ6h-Y%B^*zT&SN7C=N;g|#dGIVMSOru3iv^SvO>h4M=t-N1GSLLDqVTcgurco6)3&XpU!FP6Hlrmj}f$ zp95;b)>M~`kxuZF3r~a!rMf4|&1=uMG$;h^g=Kl;H&Np-(pFT9FF@++MMEx3RBsK?AU0fPk-#mdR)Wdkj)`>ZMl#^<80kM87VvsI3r_c@_vX=fdQ`_9-d(xiI z4K;1y1TiPj_RPh*SpDI7U~^QQ?%0&!$Sh#?x_@;ag)P}ZkAik{_WPB4rHyW#%>|Gs zdbhyt=qQPA7`?h2_8T;-E6HI#im9K>au*(j4;kzwMSLgo6u*}-K`$_Gzgu&XE)udQ zmQ72^eZd|vzI)~!20JV-v-T|<4@7ruqrj|o4=JJPlybwMg;M$Ud7>h6g()CT@wXm` zbq=A(t;RJ^{Xxi*Ff~!|3!-l_PS{AyNAU~t{h;(N(PXMEf^R(B+ZVX3 z8y0;0A8hJYp@g+c*`>eTA|3Tgv9U8#BDTO9@a@gVMDxr(fVaEqL1tl?md{v^j8aUv zm&%PX4^|rX|?E4^CkplWWNv*OKM>DxPa z!RJ)U^0-WJMi)Ksc!^ixOtw^egoAZZ2Cg;X7(5xZG7yL_;UJ#yp*ZD-;I^Z9qkP`} zwCTs0*%rIVF1sgLervtnUo&brwz?6?PXRuOCS*JI-WL6GKy7-~yi0giTEMmDs_-UX zo=+nFrW_EfTg>oY72_4Z0*uG>MnXP=c0VpT&*|rvv1iStW;*^={rP1y?Hv+6R6bxFMkxpWkJ>m7Ba{>zc_q zEefC3jsXdyS5??Mz7IET$Kft|EMNJIv7Ny8ZOcKnzf`K5Cd)&`-fTY#W&jnV0l2vt z?Gqhic}l}mCv1yUEy$%DP}4AN;36$=7aNI^*AzV(eYGeJ(Px-j<^gSDp5dBAv2#?; zcMXv#aj>%;MiG^q^$0MSg-(uTl!xm49dH!{X0){Ew7ThWV~Gtj7h%ZD zVN-R-^7Cf0VH!8O)uUHPL2mO2tmE*cecwQv_5CzWeh)ykX8r5Hi`ehYo)d{Jnh&3p z9ndXT$OW51#H5cFKa76c<%nNkP~FU93b5h-|Cb}ScHs@4Q#|}byWg;KDMJ#|l zE=MKD*F@HDBcX@~QJH%56eh~jfPO-uKm}~t7VkHxHT;)4sd+?Wc4* z>CyR*{w@4(gnYRdFq=^(#-ytb^5ESD?x<0Skhb%Pt?npNW1m+Nv`tr9+qN<3H1f<% zZvNEqyK5FgPsQ`QIu9P0x_}wJR~^CotL|n zk?dn;tLRw9jJTur4uWoX6iMm914f0AJfB@C74a;_qRrAP4E7l890P&{v<}>_&GLrW z)klculcg`?zJO~4;BBAa=POU%aN|pmZJn2{hA!d!*lwO%YSIzv8bTJ}=nhC^n}g(ld^rn#kq9Z3)z`k9lvV>y#!F4e{5c$tnr9M{V)0m(Z< z#88vX6-AW7T2UUwW`g<;8I$Jb!R%z@rCcGT)-2k7&x9kZZT66}Ztid~6t0jKb&9mm zpa}LCb`bz`{MzpZR#E*QuBiZXI#<`5qxx=&LMr-UUf~@dRk}YI2hbMsAMWOmDzYtm zjof16D=mc`^B$+_bCG$$@R0t;e?~UkF?7<(vkb70*EQB1rfUWXh$j)R2)+dNAH5%R zEBs^?N;UMdy}V};59Gu#0$q53$}|+q7CIGg_w_WlvE}AdqoS<7DY1LWS9?TrfmcvT zaypmplwn=P4;a8-%l^e?f`OpGb}%(_mFsL&GywhyN(-VROj`4~V~9bGv%UhcA|YW% zs{;nh@aDX11y^HOFXB$a7#Sr3cEtNd4eLm@Y#fc&j)TGvbbMwze zXtekX_wJqxe4NhuW$r}cNy|L{V=t#$%SuWEW)YZTH|!iT79k#?632OFse{+BT_gau zJwQcbH{b}dzKO?^dV&3nTILYlGw{27UJ72ZN){BILd_HV_s$WfI2DC<9LIHFmtyw? zQ;?MuK7g%Ym+4e^W#5}WDLpko%jPOC=aN)3!=8)s#Rnercak&b3ESRX3z{xfKBF8L z5%CGkFmGO@x?_mPGlpEej!3!AMddChabyf~nJNZxx!D&{@xEb!TDyvqSj%Y5@A{}9 zRzoBn0?x}=krh{ok3Nn%e)#~uh;6jpezhA)ySb^b#E>73e*frBFu6IZ^D7Ii&rsiU z%jzygxT-n*joJpY4o&8UXr2s%j^Q{?e-voloX`4DQyEK+DmrZh8A$)iWL#NO9+Y@!sO2f@rI!@jN@>HOA< z?q2l{^%mY*PNx2FoX+A7X3N}(RV$B`g&N=e0uvAvEN1W^{*W?zT1i#fxuw10%~))J zjx#gxoVlXREWZf4hRkgdHx5V_S*;p-y%JtGgQ4}lnA~MBz-AFdxUxU1RIT$`sal|X zPB6sEVRjGbXIP0U+?rT|y5+ev&OMX*5C$n2SBPZr`jqzrmpVrNciR0e*Wm?fK6DY& zl(XQZ60yWXV-|Ps!A{EF;=_z(YAF=T(-MkJXUoX zI{UMQDAV2}Ya?EisdEW;@pE6dt;j0fg5oT2dxCi{wqWJ<)|SR6fxX~5CzblPGr8cb zUBVJ2CQd~3L?7yfTpLNbt)He1D>*KXI^GK%<`bq^cUq$Q@uJifG>p3LU(!H=C)aEL zenk7pVg}0{dKU}&l)Y2Y2eFMdS(JS0}oZUuVaf2+K*YFNGHB`^YGcIpnBlMhO7d4@vV zv(@N}(k#REdul8~fP+^F@ky*wt@~&|(&&meNO>rKDEnB{ykAZ}k>e@lad7to>Ao$B zz<1(L=#J*u4_LB=8w+*{KFK^u00NAmeNN7pr+Pf+N*Zl^dO{LM-hMHyP6N!~`24jd zXYP|Ze;dRXKdF2iJG$U{k=S86l@pytLx}$JFFs8e)*Vi?aVBtGJ3JZUj!~c{(rw5>vuRF$`^p!P8w1B=O!skwkO5yd4_XuG^QVF z`-r5K7(IPSiKQ2|U9+`@Js!g6sfJwAHVd|s?|mnC*q zp|B|z)(8+mxXyxQ{8Pg3F4|tdpgZZSoU4P&9I8)nHo1@)9_9u&NcT^FI)6|hsAZFk zZ+arl&@*>RXBf-OZxhZerOr&dN5LW9@gV=oGFbK*J+m#R-|e6(Loz(;g@T^*oO)0R zN`N=X46b{7yk5FZGr#5&n1!-@j@g02g|X>MOpF3#IjZ_4wg{dX+G9eqS+Es9@6nC7 zD9$NuVJI}6ZlwtUm5cCAiYv0(Yi{%eH+}t)!E^>^KxB5^L~a`4%1~5q6h>d;paC9c zTj0wTCKrhWf+F#5>EgX`sl%POl?oyCq0(w0xoL?L%)|Q7d|Hl92rUYAU#lc**I&^6p=4lNQPa0 znQ|A~i0ip@`B=FW-Q;zh?-wF;Wl5!+q3GXDu-x&}$gUO)NoO7^$BeEIrd~1Dh{Tr` z8s<(Bn@gZ(mkIGnmYh_ehXnq78QL$pNDi)|QcT*|GtS%nz1uKE+E{7jdEBp%h0}%r zD2|KmYGiPa4;md-t_m5YDz#c*oV_FqXd85d@eub?9N61QuYcb3CnVWpM(D-^|CmkL z(F}L&N7qhL2PCq)fRh}XO@U`Yn<?TNGR4L(mF7#4u29{i~@k;pLsgl({YW5`Mo+p=zZn3L*4{JU;++dG9 X@eDJUQo;Ye2mwlRs?y0|+_a0zY+Zo%Dkae}+MySoIppb75o?vUW_?)>@g{U2`ERQIXV zeY$JrWnMZ$QC<=ii4X|@0H8`si75jB(ElJb00HAB%>SlLR{!zO|C9P3zxw_U8?1d8uRZ=({Ga4shyN}3 zAK}WA(ds|``G4jA)9}Bt2Hy0+f3rV1E6b|@?hpGA=PI&r8)ah|)I2s(P5Ic*Ndhn^ z*T&j@gbCTv7+8rpYbR^Ty}1AY)YH;p!m948r#%7x^Z@_-w{pDl|1S4`EM3n_PaXvK z1JF)E3qy$qTj5Xs{jU9k=y%SQ0>8E$;x?p9ayU0bZZeo{5Z@&FKX>}s!0+^>C^D#z z>xsCPvxD3Z=dP}TTOSJhNTPyVt14VCQ9MQFN`rn!c&_p?&4<5_PGm4a;WS&1(!qKE z_H$;dDdiPQ!F_gsN`2>`X}$I=B;={R8%L~`>RyKcS$72ai$!2>d(YkciA^J0@X%G4 z4cu!%Ps~2JuJ8ex`&;Fa0NQOq_nDZ&X;^A=oc1&f#3P1(!5il>6?uK4QpEG8z0Rhu zvBJ+A9RV?z%v?!$=(vcH?*;vRs*+PPbOQ3cdPr5=tOcLqmfx@#hOqX0iN)wTTO21jH<>jpmwRIAGw7`a|sl?9y9zRBh>(_%| zF?h|P7}~RKj?HR+q|4U`CjRmV-$mLW>MScKnNXiv{vD3&2@*u)-6P@h0A`eeZ7}71 zK(w%@R<4lLt`O7fs1E)$5iGb~fPfJ?WxhY7c3Q>T-w#wT&zW522pH-B%r5v#5y^CF zcC30Se|`D2mY$hAlIULL%-PNXgbbpRHgn<&X3N9W!@BUk@9g*P5mz-YnZBb*-$zMM z7Qq}ic0mR8n{^L|=+diODdV}Q!gwr?y+2m=3HWwMq4z)DqYVg0J~^}-%7rMR@S1;9 z7GFj6K}i32X;3*$SmzB&HW{PJ55kT+EI#SsZf}bD7nW^Haf}_gXciYKX{QBxIPSx2Ma? zHQqgzZq!_{&zg{yxqv3xq8YV+`S}F6A>Gtl39_m;K4dA{pP$BW0oIXJ>jEQ!2V3A2 zdpoTxG&V=(?^q?ZTj2ZUpDUdMb)T?E$}CI>r@}PFPWD9@*%V6;4Ag>D#h>!s)=$0R zRXvdkZ%|c}ubej`jl?cS$onl9Tw52rBKT)kgyw~Xy%z62Lr%V6Y=f?2)J|bZJ5(Wx zmji`O;_B+*X@qe-#~`HFP<{8$w@z4@&`q^Q-Zk8JG3>WalhnW1cvnoVw>*R@c&|o8 zZ%w!{Z+MHeZ*OE4v*otkZqz11*s!#s^Gq>+o`8Z5 z^i-qzJLJh9!W-;SmFkR8HEZJWiXk$40i6)7 zZpr=k2lp}SasbM*Nbn3j$sn0;rUI;%EDbi7T1ZI4qL6PNNM2Y%6{LMIKW+FY_yF3) zSKQ2QSujzNMSL2r&bYs`|i2Dnn z=>}c0>a}>|uT!IiMOA~pVT~R@bGlm}Edf}Kq0?*Af6#mW9f9!}RjW7om0c9Qlp;yK z)=XQs(|6GCadQbWIhYF=rf{Y)sj%^Id-ARO0=O^Ad;Ph+ z0?$eE1xhH?{T$QI>0JP75`r)U_$#%K1^BQ8z#uciKf(C701&RyLQWBUp*Q7eyn76} z6JHpC9}R$J#(R0cDCkXoFSp;j6{x{b&0yE@P7{;pCEpKjS(+1RQy38`=&Yxo%F=3y zCPeefABp34U-s?WmU#JJw23dcC{sPPFc2#J$ZgEN%zod}J~8dLm*fx9f6SpO zn^Ww3bt9-r0XaT2a@Wpw;C23XM}7_14#%QpubrIw5aZtP+CqIFmsG4`Cm6rfxl9n5 z7=r2C-+lM2AB9X0T_`?EW&Byv&K?HS4QLoylJ|OAF z`8atBNTzJ&AQ!>sOo$?^0xj~D(;kS$`9zbEGd>f6r`NC3X`tX)sWgWUUOQ7w=$TO&*j;=u%25ay-%>3@81tGe^_z*C7pb9y*Ed^H3t$BIKH2o+olp#$q;)_ zfpjCb_^VFg5fU~K)nf*d*r@BCC>UZ!0&b?AGk_jTPXaSnCuW110wjHPPe^9R^;jo3 zwvzTl)C`Zl5}O2}3lec=hZ*$JnkW#7enKKc)(pM${_$9Hc=Sr_A9Biwe*Y=T?~1CK z6eZ9uPICjy-sMGbZl$yQmpB&`ouS8v{58__t0$JP%i3R&%QR3ianbZqDs<2#5FdN@n5bCn^ZtH992~5k(eA|8|@G9u`wdn7bnpg|@{m z^d6Y`*$Zf2Xr&|g%sai#5}Syvv(>Jnx&EM7-|Jr7!M~zdAyjt*xl;OLhvW-a%H1m0 z*x5*nb=R5u><7lyVpNAR?q@1U59 zO+)QWwL8t zyip?u_nI+K$uh{y)~}qj?(w0&=SE^8`_WMM zTybjG=999h38Yes7}-4*LJ7H)UE8{mE(6;8voE+TYY%33A>S6`G_95^5QHNTo_;Ao ztIQIZ_}49%{8|=O;isBZ?=7kfdF8_@azfoTd+hEJKWE!)$)N%HIe2cplaK`ry#=pV z0q{9w-`i0h@!R8K3GC{ivt{70IWG`EP|(1g7i_Q<>aEAT{5(yD z=!O?kq61VegV+st@XCw475j6vS)_z@efuqQgHQR1T4;|-#OLZNQJPV4k$AX1Uk8Lm z{N*b*ia=I+MB}kWpupJ~>!C@xEN#Wa7V+7{m4j8c?)ChV=D?o~sjT?0C_AQ7B-vxqX30s0I_`2$in86#`mAsT-w?j{&AL@B3$;P z31G4(lV|b}uSDCIrjk+M1R!X7s4Aabn<)zpgT}#gE|mIvV38^ODy@<&yflpCwS#fRf9ZX3lPV_?8@C5)A;T zqmouFLFk;qIs4rA=hh=GL~sCFsXHsqO6_y~*AFt939UYVBSx1s(=Kb&5;j7cSowdE;7()CC2|-i9Zz+_BIw8#ll~-tyH?F3{%`QCsYa*b#s*9iCc`1P1oC26?`g<9))EJ3%xz+O!B3 zZ7$j~To)C@PquR>a1+Dh>-a%IvH_Y7^ys|4o?E%3`I&ADXfC8++hAdZfzIT#%C+Jz z1lU~K_vAm0m8Qk}K$F>|>RPK%<1SI0(G+8q~H zAsjezyP+u!Se4q3GW)`h`NPSRlMoBjCzNPesWJwVTY!o@G8=(6I%4XHGaSiS3MEBK zhgGFv6Jc>L$4jVE!I?TQuwvz_%CyO!bLh94nqK11C2W$*aa2ueGopG8DnBICVUORP zgytv#)49fVXDaR$SukloYC3u7#5H)}1K21=?DKj^U)8G;MS)&Op)g^zR2($<>C*zW z;X7`hLxiIO#J`ANdyAOJle4V%ppa*(+0i3w;8i*BA_;u8gOO6)MY`ueq7stBMJTB; z-a0R>hT*}>z|Gg}@^zDL1MrH+2hsR8 zHc}*9IvuQC^Ju)^#Y{fOr(96rQNPNhxc;mH@W*m206>Lo<*SaaH?~8zg&f&%YiOEG zGiz?*CP>Bci}!WiS=zj#K5I}>DtpregpP_tfZtPa(N<%vo^#WCQ5BTv0vr%Z{)0q+ z)RbfHktUm|lg&U3YM%lMUM(fu}i#kjX9h>GYctkx9Mt_8{@s%!K_EI zScgwy6%_fR?CGJQtmgNAj^h9B#zmaMDWgH55pGuY1Gv7D z;8Psm(vEPiwn#MgJYu4Ty9D|h!?Rj0ddE|&L3S{IP%H4^N!m`60ZwZw^;eg4sk6K{ ziA^`Sbl_4~f&Oo%n;8Ye(tiAdlZKI!Z=|j$5hS|D$bDJ}p{gh$KN&JZYLUjv4h{NY zBJ>X9z!xfDGY z+oh_Z&_e#Q(-}>ssZfm=j$D&4W4FNy&-kAO1~#3Im;F)Nwe{(*75(p=P^VI?X0GFakfh+X-px4a%Uw@fSbmp9hM1_~R>?Z8+ ziy|e9>8V*`OP}4x5JjdWp}7eX;lVxp5qS}0YZek;SNmm7tEeSF*-dI)6U-A%m6YvCgM(}_=k#a6o^%-K4{`B1+}O4x zztDT%hVb;v#?j`lTvlFQ3aV#zkX=7;YFLS$uIzb0E3lozs5`Xy zi~vF+%{z9uLjKvKPhP%x5f~7-Gj+%5N`%^=yk*Qn{`> z;xj&ROY6g`iy2a@{O)V(jk&8#hHACVDXey5a+KDod_Z&}kHM}xt7}Md@pil{2x7E~ zL$k^d2@Ec2XskjrN+IILw;#7((abu;OJii&v3?60x>d_Ma(onIPtcVnX@ELF0aL?T zSmWiL3(dOFkt!x=1O!_0n(cAzZW+3nHJ{2S>tgSK?~cFha^y(l@-Mr2W$%MN{#af8J;V*>hdq!gx=d0h$T7l}>91Wh07)9CTX zh2_ZdQCyFOQ)l(}gft0UZG`Sh2`x-w`5vC2UD}lZs*5 zG76$akzn}Xi))L3oGJ75#pcN=cX3!=57$Ha=hQ2^lwdyU#a}4JJOz6ddR%zae%#4& za)bFj)z=YQela(F#Y|Q#dp}PJghITwXouVaMq$BM?K%cXn9^Y@g43$=O)F&ZlOUom zJiad#dea;-eywBA@e&D6Pdso1?2^(pXiN91?jvcaUyYoKUmvl5G9e$W!okWe*@a<^ z8cQQ6cNSf+UPDx%?_G4aIiybZHHagF{;IcD(dPO!#=u zWfqLcPc^+7Uu#l(Bpxft{*4lv#*u7X9AOzDO z1D9?^jIo}?%iz(_dwLa{ex#T}76ZfN_Z-hwpus9y+4xaUu9cX}&P{XrZVWE{1^0yw zO;YhLEW!pJcbCt3L8~a7>jsaN{V3>tz6_7`&pi%GxZ=V3?3K^U+*ryLSb)8^IblJ0 zSRLNDvIxt)S}g30?s_3NX>F?NKIGrG_zB9@Z>uSW3k2es_H2kU;Rnn%j5qP)!XHKE zPB2mHP~tLCg4K_vH$xv`HbRsJwbZMUV(t=ez;Ec(vyHH)FbfLg`c61I$W_uBB>i^r z&{_P;369-&>23R%qNIULe=1~T$(DA`ev*EWZ6j(B$(te}x1WvmIll21zvygkS%vwG zzkR6Z#RKA2!z!C%M!O>!=Gr0(J0FP=-MN=5t-Ir)of50y10W}j`GtRCsXBakrKtG& zazmITDJMA0C51&BnLY)SY9r)NVTMs);1<=oosS9g31l{4ztjD3#+2H7u_|66b|_*O z;Qk6nalpqdHOjx|K&vUS_6ITgGll;TdaN*ta=M_YtyC)I9Tmr~VaPrH2qb6sd~=AcIxV+%z{E&0@y=DPArw zdV7z(G1hBx7hd{>(cr43^WF%4Y@PXZ?wPpj{OQ#tvc$pABJbvPGvdR`cAtHn)cSEV zrpu}1tJwQ3y!mSmH*uz*x0o|CS<^w%&KJzsj~DU0cLQUxk5B!hWE>aBkjJle8z~;s z-!A=($+}Jq_BTK5^B!`R>!MulZN)F=iXXeUd0w5lUsE5VP*H*oCy(;?S$p*TVvTxwAeWFB$jHyb0593)$zqalVlDX=GcCN1gU0 zlgU)I$LcXZ8Oyc2TZYTPu@-;7<4YYB-``Qa;IDcvydIA$%kHhJKV^m*-zxcvU4viy&Kr5GVM{IT>WRywKQ9;>SEiQD*NqplK-KK4YR`p0@JW)n_{TU3bt0 zim%;(m1=#v2}zTps=?fU5w^(*y)xT%1vtQH&}50ZF!9YxW=&7*W($2kgKyz1mUgfs zfV<*XVVIFnohW=|j+@Kfo!#liQR^x>2yQdrG;2o8WZR+XzU_nG=Ed2rK?ntA;K5B{ z>M8+*A4!Jm^Bg}aW?R?6;@QG@uQ8&oJ{hFixcfEnJ4QH?A4>P=q29oDGW;L;= z9-a0;g%c`C+Ai!UmK$NC*4#;Jp<1=TioL=t^YM)<<%u#hnnfSS`nq63QKGO1L8RzX z@MFDqs1z ztYmxDl@LU)5acvHk)~Z`RW7=aJ_nGD!mOSYD>5Odjn@TK#LY{jf?+piB5AM-CAoT_ z?S-*q7}wyLJzK>N%eMPuFgN)Q_otKP;aqy=D5f!7<=n(lNkYRXVpkB{TAYLYg{|(jtRqYmg$xH zjmq?B(RE4 zQx^~Pt}gxC2~l=K$$-sYy_r$CO(d=+b3H1MB*y_5g6WLaWTXn+TKQ|hNY^>Mp6k*$ zwkovomhu776vQATqT4blf~g;TY(MWCrf^^yfWJvSAB$p5l;jm@o#=!lqw+Lqfq>X= z$6~kxfm7`3q4zUEB;u4qa#BdJxO!;xGm)wwuisj{0y2x{R(IGMrsIzDY9LW>m!Y`= z04sx3IjnYvL<4JqxQ8f7qYd0s2Ig%`ytYPEMKI)s(LD}D@EY>x`VFtqvnADNBdeao zC96X+MxnwKmjpg{U&gP3HE}1=s!lv&D{6(g_lzyF3A`7Jn*&d_kL<;dAFx!UZ>hB8 z5A*%LsAn;VLp>3${0>M?PSQ)9s3}|h2e?TG4_F{}{Cs>#3Q*t$(CUc}M)I}8cPF6% z=+h(Kh^8)}gj(0}#e7O^FQ6`~fd1#8#!}LMuo3A0bN`o}PYsm!Y}sdOz$+Tegc=qT z8x`PH$7lvnhJp{kHWb22l;@7B7|4yL4UOOVM0MP_>P%S1Lnid)+k9{+3D+JFa#Pyf zhVc#&df87APl4W9X)F3pGS>@etfl=_E5tBcVoOfrD4hmVeTY-cj((pkn%n@EgN{0f zwb_^Rk0I#iZuHK!l*lN`ceJn(sI{$Fq6nN& zE<-=0_2WN}m+*ivmIOxB@#~Q-cZ>l136w{#TIJe478`KE7@=a{>SzPHsKLzYAyBQO zAtuuF$-JSDy_S@6GW0MOE~R)b;+0f%_NMrW(+V#c_d&U8Z9+ec4=HmOHw?gdjF(Lu zzra83M_BoO-1b3;9`%&DHfuUY)6YDV21P$C!Rc?mv&{lx#f8oc6?0?x zK08{WP65?#>(vPfA-c=MCY|%*1_<3D4NX zeVTi-JGl2uP_2@0F{G({pxQOXt_d{g_CV6b?jNpfUG9;8yle-^4KHRvZs-_2siata zt+d_T@U$&t*xaD22(fH(W1r$Mo?3dc%Tncm=C6{V9y{v&VT#^1L04vDrLM9qBoZ4@ z6DBN#m57hX7$C(=#$Y5$bJmwA$T8jKD8+6A!-IJwA{WOfs%s}yxUw^?MRZjF$n_KN z6`_bGXcmE#5e4Ym)aQJ)xg3Pg0@k`iGuHe?f(5LtuzSq=nS^5z>vqU0EuZ&75V%Z{ zYyhRLN^)$c6Ds{f7*FBpE;n5iglx5PkHfWrj3`x^j^t z7ntuV`g!9Xg#^3!x)l*}IW=(Tz3>Y5l4uGaB&lz{GDjm2D5S$CExLT`I1#n^lBH7Y zDgpMag@`iETKAI=p<5E#LTkwzVR@=yY|uBVI1HG|8h+d;G-qfuj}-ZR6fN>EfCCW z9~wRQoAPEa#aO?3h?x{YvV*d+NtPkf&4V0k4|L=uj!U{L+oLa(z#&iuhJr3-PjO3R z5s?=nn_5^*^Rawr>>Nr@K(jwkB#JK-=+HqwfdO<+P5byeim)wvqGlP-P|~Nse8=XF zz`?RYB|D6SwS}C+YQv+;}k6$-%D(@+t14BL@vM z2q%q?f6D-A5s$_WY3{^G0F131bbh|g!}#BKw=HQ7mx;Dzg4Z*bTLQSfo{ed{4}NZW zfrRm^Ca$rlE{Ue~uYv>R9{3smwATcdM_6+yWIO z*ZRH~uXE@#p$XTbCt5j7j2=86e{9>HIB6xDzV+vAo&B?KUiMP|ttOElepnl%|DPqL b{|{}U^kRn2wo}j7|0ATu<;8xA7zX}7|B6mN literal 0 HcmV?d00001 diff --git a/relay-reactjs-chat/manifest.json b/relay-reactjs-chat/manifest.json new file mode 100644 index 0000000..080d6c7 --- /dev/null +++ b/relay-reactjs-chat/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/relay-reactjs-chat/robots.txt b/relay-reactjs-chat/robots.txt new file mode 100644 index 0000000..e9e57dc --- /dev/null +++ b/relay-reactjs-chat/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/relay-reactjs-chat/static/css/main.e6c13ad2.css b/relay-reactjs-chat/static/css/main.e6c13ad2.css new file mode 100644 index 0000000..50410fa --- /dev/null +++ b/relay-reactjs-chat/static/css/main.e6c13ad2.css @@ -0,0 +1,2 @@ +body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;margin:0}code{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace} +/*# sourceMappingURL=main.e6c13ad2.css.map*/ \ No newline at end of file diff --git a/relay-reactjs-chat/static/css/main.e6c13ad2.css.map b/relay-reactjs-chat/static/css/main.e6c13ad2.css.map new file mode 100644 index 0000000..5c4dfb9 --- /dev/null +++ b/relay-reactjs-chat/static/css/main.e6c13ad2.css.map @@ -0,0 +1 @@ +{"version":3,"file":"static/css/main.e6c13ad2.css","mappings":"AAAA,KAKE,kCAAmC,CACnC,iCAAkC,CAJlC,mIAEY,CAHZ,QAMF,CAEA,KACE,uEAEF","sources":["index.css"],"sourcesContent":["body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n monospace;\n}\n"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/relay-reactjs-chat/static/js/main.d422f314.js b/relay-reactjs-chat/static/js/main.d422f314.js new file mode 100644 index 0000000..b5cd041 --- /dev/null +++ b/relay-reactjs-chat/static/js/main.d422f314.js @@ -0,0 +1,3 @@ +/*! For license information please see main.d422f314.js.LICENSE.txt */ +(()=>{var __webpack_modules__={2001:(e,t,r)=>{"use strict";e.exports=r(6181)},6181:(e,t,r)=>{"use strict";var n=t;function i(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(9800),n.BufferWriter=r(6489),n.Reader=r(5684),n.BufferReader=r(1229),n.util=r(9584),n.rpc=r(1872),n.roots=r(9358),n.configure=i,i()},5684:(e,t,r)=>{"use strict";e.exports=c;var n,i=r(9584),s=i.LongBits,o=i.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l="undefined"!==typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},u=function(){return i.Buffer?function(e){return(c.create=function(e){return i.Buffer.isBuffer(e)?new n(e):l(e)})(e)}:l};function h(){var e=new s(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new s(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}c.create=u(),c.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return e}}(),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return d(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|d(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?new this.buf.constructor(0):this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length)},c.prototype.skip=function(e){if("number"===typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!==(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=u(),n._configure();var t=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return h.call(this)[t](!1)},uint64:function(){return h.call(this)[t](!0)},sint64:function(){return h.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},1229:(e,t,r)=>{"use strict";e.exports=s;var n=r(5684);(s.prototype=Object.create(n.prototype)).constructor=s;var i=r(9584);function s(e){n.call(this,e)}s._configure=function(){i.Buffer&&(s.prototype._slice=i.Buffer.prototype.slice)},s.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},s._configure()},9358:e=>{"use strict";e.exports={}},1872:(e,t,r)=>{"use strict";t.Service=r(4648)},4648:(e,t,r)=>{"use strict";e.exports=i;var n=r(9584);function i(e,t,r){if("function"!==typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function e(t,r,i,s,o){if(!s)throw TypeError("request must be specified");var a=this;if(!o)return n.asPromise(e,a,t,r,i,s);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](s).finish(),(function(e,r){if(e)return a.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof i))try{r=i[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),o(e)}return a.emit("data",r,t),o(null,r)}a.end(!0)}))}catch(c){return a.emit("error",c,t),void setTimeout((function(){o(c)}),0)}else setTimeout((function(){o(Error("already ended"))}),0)},i.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},6880:(e,t,r)=>{"use strict";e.exports=i;var n=r(9584);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var s=i.zero=new i(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var o=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(e){if(0===e)return s;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new i(r,n)},i.from=function(e){if("number"===typeof e)return i.fromNumber(e);if(n.isString(e)){if(!n.Long)return i.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):s},i.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;i.fromHash=function(e){return e===o?s:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},9584:function(e,t,r){"use strict";var n=t;function i(e,t,r){for(var n=Object.keys(t),i=0;i0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"===typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"===typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!==typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=i,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=s,n.ProtocolError=s("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r{"use strict";e.exports=h;var n,i=r(9584),s=i.LongBits,o=i.base64,a=i.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return i.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function f(e,t,r){t[r]=255&e}function p(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function y(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},p.prototype=Object.create(c.prototype),p.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,s.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=s.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=s.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(f,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(y,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=s.from(e);return this._push(y,4,t.lo)._push(y,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(i.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(i.float.writeDoubleLE,8,e)};var m=i.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(f,1,0);if(i.isString(e)){var r=h.alloc(t=o.length(e));o.decode(e,r,0),e=r}return this.uint32(t)._push(m,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(f,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},6489:(e,t,r)=>{"use strict";e.exports=s;var n=r(9800);(s.prototype=Object.create(n.prototype)).constructor=s;var i=r(9584);function s(){n.call(this)}function o(e,t,r){e.length<40?i.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}s._configure=function(){s.alloc=i._Buffer_allocUnsafe,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(s.writeBytesBuffer,t,e),this},s.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},s._configure()},7206:e=>{"use strict";e.exports=function(e,t){var r=new Array(arguments.length-1),n=0,i=2,s=!0;for(;i{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),i=new Array(123),s=0;s<64;)i[n[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;r.encode=function(e,t,r){for(var i,s=null,o=[],a=0,c=0;t>2],i=(3&l)<<4,c=1;break;case 1:o[a++]=n[i|l>>4],i=(15&l)<<2,c=2;break;case 2:o[a++]=n[i|l>>6],o[a++]=n[63&l],c=0}a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=n[i],o[a++]=61,1===c&&(o[a++]=61)),s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var o="invalid encoding";r.decode=function(e,t,r){for(var n,s=r,a=0,c=0;c1)break;if(void 0===(l=i[l]))throw Error(o);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(o);return r-s},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},3297:e=>{"use strict";function t(e,r){"string"===typeof e&&(r=e,e=void 0);var n=[];function i(e){if("string"!==typeof e){var r=s();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var o=Object.keys(e),a=new Array(o.length+1),c=new Array(o.length),l=0;l{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n{"use strict";e.exports=s;var n=r(7206),i=r(7172)("fs");function s(e,t,r){return"function"===typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&i&&i.readFile?i.readFile(e,(function(n,i){return n&&"undefined"!==typeof XMLHttpRequest?s.xhr(e,t,r):n?r(n):r(null,t.binary?i:i.toString("utf8"))})):s.xhr(e,t,r):n(s,this,e,t)}s.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var i=0;i{"use strict";function t(e){return"undefined"!==typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3]}function s(e,n,i){t[0]=e,n[i]=r[3],n[i+1]=r[2],n[i+2]=r[1],n[i+3]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?i:s,e.writeFloatBE=n?s:i,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():function(){function t(e,t,r,n){var i=t<0?1:0;if(i&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((i<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((i<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var s=Math.floor(Math.log(t)/Math.LN2);e((i<<31|s+127<<23|8388607&Math.round(t*Math.pow(2,-s)*8388608))>>>0,r,n)}}function o(e,t,r){var n=e(t,r),i=2*(n>>31)+1,s=n>>>23&255,o=8388607&n;return 255===s?o?NaN:i*(1/0):0===s?1401298464324817e-60*i*o:i*Math.pow(2,s-150)*(o+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=o.bind(null,i),e.readFloatBE=o.bind(null,s)}(),"undefined"!==typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3],n[i+4]=r[4],n[i+5]=r[5],n[i+6]=r[6],n[i+7]=r[7]}function s(e,n,i){t[0]=e,n[i]=r[7],n[i+1]=r[6],n[i+2]=r[5],n[i+3]=r[4],n[i+4]=r[3],n[i+5]=r[2],n[i+6]=r[1],n[i+7]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?i:s,e.writeDoubleBE=n?s:i,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function t(e,t,r,n,i,s){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,i,s+t),e(1/n>0?0:2147483648,i,s+r);else if(isNaN(n))e(0,i,s+t),e(2146959360,i,s+r);else if(n>17976931348623157e292)e(0,i,s+t),e((o<<31|2146435072)>>>0,i,s+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,i,s+t),e((o<<31|a/4294967296)>>>0,i,s+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,i,s+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,i,s+r)}}}function o(e,t,r,n,i){var s=e(n,i+t),o=e(n,i+r),a=2*(o>>31)+1,c=o>>>20&2047,l=4294967296*(1048575&o)+s;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=o.bind(null,i,0,4),e.readDoubleBE=o.bind(null,s,4,0)}(),e}function r(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},7172:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},7468:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},i=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),i="";r&&(i=t.shift()+"/");for(var s=0;s0&&".."!==t[s-1]?t.splice(--s,2):r?t.splice(s,1):++s:"."===t[s]?t.splice(s,1):++s;return i+t.join("/")};r.resolve=function(e,t,r){return r||(t=i(t)),n(t)?t:(r||(e=i(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?i(e+"/"+t):t)}},8236:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(r){if(r<1||r>i)return e(r);o+r>n&&(s=e(n),o=0);var a=t.call(s,o,o+=r);return 7&o&&(o=1+(7|o)),a}}},3861:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?s[o++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(n>>10),s[o++]=56320+(1023&n)):s[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0);return i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))},r.write=function(e,t,r){for(var n,i,s=r,o=0;o>6|192,t[r++]=63&n|128):55296===(64512&n)&&56320===(64512&(i=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&i),++o,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-s}},6232:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(5073);function i(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>8,t[r+1]=e>>>0,t}function s(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t}function o(e,t){return void 0===t&&(t=0),e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function a(e,t){return void 0===t&&(t=0),(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function c(e,t){return void 0===t&&(t=0),e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function l(e,t){return void 0===t&&(t=0),(e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t])>>>0}function u(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>24,t[r+1]=e>>>16,t[r+2]=e>>>8,t[r+3]=e>>>0,t}function h(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24,t}function d(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),u(e/4294967296>>>0,t,r),u(e>>>0,t,r+4),t}function f(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),h(e>>>0,t,r),h(e/4294967296>>>0,t,r+4),t}t.readInt16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])<<16>>16},t.readUint16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])>>>0},t.readInt16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])<<16>>16},t.readUint16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])>>>0},t.writeUint16BE=i,t.writeInt16BE=i,t.writeUint16LE=s,t.writeInt16LE=s,t.readInt32BE=o,t.readUint32BE=a,t.readInt32LE=c,t.readUint32LE=l,t.writeUint32BE=u,t.writeInt32BE=u,t.writeUint32LE=h,t.writeInt32LE=h,t.readInt64BE=function(e,t){void 0===t&&(t=0);var r=o(e,t),n=o(e,t+4);return 4294967296*r+n-4294967296*(n>>31)},t.readUint64BE=function(e,t){return void 0===t&&(t=0),4294967296*a(e,t)+a(e,t+4)},t.readInt64LE=function(e,t){void 0===t&&(t=0);var r=c(e,t);return 4294967296*c(e,t+4)+r-4294967296*(r>>31)},t.readUint64LE=function(e,t){void 0===t&&(t=0);var r=l(e,t);return 4294967296*l(e,t+4)+r},t.writeUint64BE=d,t.writeInt64BE=d,t.writeUint64LE=f,t.writeInt64LE=f,t.readUintBE=function(e,t,r){if(void 0===r&&(r=0),e%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=e/8+r-1;s>=r;s--)n+=t[s]*i,i*=256;return n},t.readUintLE=function(e,t,r){if(void 0===r&&(r=0),e%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=i;o--)r[o]=t/s&255,s*=256;return r},t.writeUintLE=function(e,t,r,i){if(void 0===r&&(r=new Uint8Array(e/8)),void 0===i&&(i=0),e%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!n.isSafeInteger(t))throw new Error("writeUintLE value must be an integer");for(var s=1,o=i;o{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(6232),i=r(9116);function s(e,t,r){for(var i=1634760805,s=857760878,o=2036477234,a=1797285236,c=r[3]<<24|r[2]<<16|r[1]<<8|r[0],l=r[7]<<24|r[6]<<16|r[5]<<8|r[4],u=r[11]<<24|r[10]<<16|r[9]<<8|r[8],h=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],f=r[23]<<24|r[22]<<16|r[21]<<8|r[20],p=r[27]<<24|r[26]<<16|r[25]<<8|r[24],g=r[31]<<24|r[30]<<16|r[29]<<8|r[28],y=t[3]<<24|t[2]<<16|t[1]<<8|t[0],m=t[7]<<24|t[6]<<16|t[5]<<8|t[4],v=t[11]<<24|t[10]<<16|t[9]<<8|t[8],w=t[15]<<24|t[14]<<16|t[13]<<8|t[12],b=i,E=s,S=o,_=a,I=c,A=l,C=u,T=h,R=d,k=f,P=p,D=g,N=y,O=m,L=v,B=w,x=0;x<20;x+=2)I=(I^=R=R+(N=(N^=b=b+I|0)>>>16|N<<16)|0)>>>20|I<<12,A=(A^=k=k+(O=(O^=E=E+A|0)>>>16|O<<16)|0)>>>20|A<<12,C=(C^=P=P+(L=(L^=S=S+C|0)>>>16|L<<16)|0)>>>20|C<<12,T=(T^=D=D+(B=(B^=_=_+T|0)>>>16|B<<16)|0)>>>20|T<<12,C=(C^=P=P+(L=(L^=S=S+C|0)>>>24|L<<8)|0)>>>25|C<<7,T=(T^=D=D+(B=(B^=_=_+T|0)>>>24|B<<8)|0)>>>25|T<<7,A=(A^=k=k+(O=(O^=E=E+A|0)>>>24|O<<8)|0)>>>25|A<<7,I=(I^=R=R+(N=(N^=b=b+I|0)>>>24|N<<8)|0)>>>25|I<<7,A=(A^=P=P+(B=(B^=b=b+A|0)>>>16|B<<16)|0)>>>20|A<<12,C=(C^=D=D+(N=(N^=E=E+C|0)>>>16|N<<16)|0)>>>20|C<<12,T=(T^=R=R+(O=(O^=S=S+T|0)>>>16|O<<16)|0)>>>20|T<<12,I=(I^=k=k+(L=(L^=_=_+I|0)>>>16|L<<16)|0)>>>20|I<<12,T=(T^=R=R+(O=(O^=S=S+T|0)>>>24|O<<8)|0)>>>25|T<<7,I=(I^=k=k+(L=(L^=_=_+I|0)>>>24|L<<8)|0)>>>25|I<<7,C=(C^=D=D+(N=(N^=E=E+C|0)>>>24|N<<8)|0)>>>25|C<<7,A=(A^=P=P+(B=(B^=b=b+A|0)>>>24|B<<8)|0)>>>25|A<<7;n.writeUint32LE(b+i|0,e,0),n.writeUint32LE(E+s|0,e,4),n.writeUint32LE(S+o|0,e,8),n.writeUint32LE(_+a|0,e,12),n.writeUint32LE(I+c|0,e,16),n.writeUint32LE(A+l|0,e,20),n.writeUint32LE(C+u|0,e,24),n.writeUint32LE(T+h|0,e,28),n.writeUint32LE(R+d|0,e,32),n.writeUint32LE(k+f|0,e,36),n.writeUint32LE(P+p|0,e,40),n.writeUint32LE(D+g|0,e,44),n.writeUint32LE(N+y|0,e,48),n.writeUint32LE(O+m|0,e,52),n.writeUint32LE(L+v|0,e,56),n.writeUint32LE(B+w|0,e,60)}function o(e,t,r,n,o){if(void 0===o&&(o=0),32!==e.length)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,t++;if(n>0)throw new Error("ChaCha: counter overflow")}t.streamXOR=o,t.stream=function(e,t,r,n){return void 0===n&&(n=0),i.wipe(r),o(e,t,r,r,n)}},3642:(e,t,r)=>{"use strict";var n=r(8284),i=r(5629),s=r(9116),o=r(6232),a=r(8770);t.Cv=32,t.WH=12,t.pg=16;var c=new Uint8Array(16),l=function(){function e(e){if(this.nonceLength=t.WH,this.tagLength=t.pg,e.length!==t.Cv)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return e.prototype.seal=function(e,t,r,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var o=new Uint8Array(16);o.set(e,o.length-e.length);var a=new Uint8Array(32);n.stream(this._key,o,a,4);var c,l=t.length+this.tagLength;if(i){if(i.length!==l)throw new Error("ChaCha20Poly1305: incorrect destination length");c=i}else c=new Uint8Array(l);return n.streamXOR(this._key,o,t,c,4),this._authenticate(c.subarray(c.length-this.tagLength,c.length),a,c.subarray(0,c.length-this.tagLength),r),s.wipe(o),c},e.prototype.open=function(e,t,r,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(t.length0&&a.update(c.subarray(n.length%16))),a.update(r),r.length%16>0&&a.update(c.subarray(r.length%16));var l=new Uint8Array(8);n&&o.writeUint64LE(n.length,l),a.update(l),o.writeUint64LE(r.length,l),a.update(l);for(var u=a.digest(),h=0;h{"use strict";function r(e,t){if(e.length!==t.length)return 0;for(var r=0,n=0;n>>8}Object.defineProperty(t,"__esModule",{value:!0}),t.select=function(e,t,r){return~(e-1)&t|e-1&r},t.lessOrEqual=function(e,t){return(0|e)-(0|t)-1>>>31&1},t.compare=r,t.equal=function(e,t){return 0!==e.length&&0!==t.length&&0!==r(e,t)}},1412:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSerializableHash=function(e){return"undefined"!==typeof e.saveState&&"undefined"!==typeof e.restoreState&&"undefined"!==typeof e.cleanSavedState}},2497:(e,t,r)=>{"use strict";var n=r(5499),i=r(9116),s=function(){function e(e,t,r,i){void 0===r&&(r=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=n.hmac(this._hash,r,t);this._hmac=new n.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return e.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(0===e)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},e.prototype.expand=function(e){for(var t=new Uint8Array(e),r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(1412),i=r(8770),s=r(9116),o=function(){function e(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var r=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(r).clean():r.set(t);for(var i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mul=Math.imul||function(e,t){var r=65535&e,n=65535&t;return r*n+((e>>>16&65535)*n+r*(t>>>16&65535)<<16>>>0)|0},t.add=function(e,t){return e+t|0},t.sub=function(e,t){return e-t|0},t.rotl=function(e,t){return e<>>32-t},t.rotr=function(e,t){return e<<32-t|e>>>t},t.isInteger=Number.isInteger||function(e){return"number"===typeof e&&isFinite(e)&&Math.floor(e)===e},t.MAX_SAFE_INTEGER=9007199254740991,t.isSafeInteger=function(e){return t.isInteger(e)&&e>=-t.MAX_SAFE_INTEGER&&e<=t.MAX_SAFE_INTEGER}},5629:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8770),i=r(9116);t.DIGEST_LENGTH=16;var s=function(){function e(e){this.digestLength=t.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=8191&r;var n=e[2]|e[3]<<8;this._r[1]=8191&(r>>>13|n<<3);var i=e[4]|e[5]<<8;this._r[2]=7939&(n>>>10|i<<6);var s=e[6]|e[7]<<8;this._r[3]=8191&(i>>>7|s<<9);var o=e[8]|e[9]<<8;this._r[4]=255&(s>>>4|o<<12),this._r[5]=o>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=8191&(o>>>14|a<<2);var c=e[12]|e[13]<<8;this._r[7]=8065&(a>>>11|c<<5);var l=e[14]|e[15]<<8;this._r[8]=8191&(c>>>8|l<<8),this._r[9]=l>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return e.prototype._blocks=function(e,t,r){for(var n=this._fin?0:2048,i=this._h[0],s=this._h[1],o=this._h[2],a=this._h[3],c=this._h[4],l=this._h[5],u=this._h[6],h=this._h[7],d=this._h[8],f=this._h[9],p=this._r[0],g=this._r[1],y=this._r[2],m=this._r[3],v=this._r[4],w=this._r[5],b=this._r[6],E=this._r[7],S=this._r[8],_=this._r[9];r>=16;){var I=e[t+0]|e[t+1]<<8;i+=8191&I;var A=e[t+2]|e[t+3]<<8;s+=8191&(I>>>13|A<<3);var C=e[t+4]|e[t+5]<<8;o+=8191&(A>>>10|C<<6);var T=e[t+6]|e[t+7]<<8;a+=8191&(C>>>7|T<<9);var R=e[t+8]|e[t+9]<<8;c+=8191&(T>>>4|R<<12),l+=R>>>1&8191;var k=e[t+10]|e[t+11]<<8;u+=8191&(R>>>14|k<<2);var P=e[t+12]|e[t+13]<<8;h+=8191&(k>>>11|P<<5);var D=e[t+14]|e[t+15]<<8,N=0,O=N;O+=i*p,O+=s*(5*_),O+=o*(5*S),O+=a*(5*E),N=(O+=c*(5*b))>>>13,O&=8191,O+=l*(5*w),O+=u*(5*v),O+=h*(5*m),O+=(d+=8191&(P>>>8|D<<8))*(5*y);var L=N+=(O+=(f+=D>>>5|n)*(5*g))>>>13;L+=i*g,L+=s*p,L+=o*(5*_),L+=a*(5*S),N=(L+=c*(5*E))>>>13,L&=8191,L+=l*(5*b),L+=u*(5*w),L+=h*(5*v),L+=d*(5*m),N+=(L+=f*(5*y))>>>13,L&=8191;var B=N;B+=i*y,B+=s*g,B+=o*p,B+=a*(5*_),N=(B+=c*(5*S))>>>13,B&=8191,B+=l*(5*E),B+=u*(5*b),B+=h*(5*w),B+=d*(5*v);var x=N+=(B+=f*(5*m))>>>13;x+=i*m,x+=s*y,x+=o*g,x+=a*p,N=(x+=c*(5*_))>>>13,x&=8191,x+=l*(5*S),x+=u*(5*E),x+=h*(5*b),x+=d*(5*w);var M=N+=(x+=f*(5*v))>>>13;M+=i*v,M+=s*m,M+=o*y,M+=a*g,N=(M+=c*p)>>>13,M&=8191,M+=l*(5*_),M+=u*(5*S),M+=h*(5*E),M+=d*(5*b);var U=N+=(M+=f*(5*w))>>>13;U+=i*w,U+=s*v,U+=o*m,U+=a*y,N=(U+=c*g)>>>13,U&=8191,U+=l*p,U+=u*(5*_),U+=h*(5*S),U+=d*(5*E);var F=N+=(U+=f*(5*b))>>>13;F+=i*b,F+=s*w,F+=o*v,F+=a*m,N=(F+=c*y)>>>13,F&=8191,F+=l*g,F+=u*p,F+=h*(5*_),F+=d*(5*S);var V=N+=(F+=f*(5*E))>>>13;V+=i*E,V+=s*b,V+=o*w,V+=a*v,N=(V+=c*m)>>>13,V&=8191,V+=l*y,V+=u*g,V+=h*p,V+=d*(5*_);var K=N+=(V+=f*(5*S))>>>13;K+=i*S,K+=s*E,K+=o*b,K+=a*w,N=(K+=c*v)>>>13,K&=8191,K+=l*m,K+=u*y,K+=h*g,K+=d*p;var j=N+=(K+=f*(5*_))>>>13;j+=i*_,j+=s*S,j+=o*E,j+=a*b,N=(j+=c*w)>>>13,j&=8191,j+=l*v,j+=u*m,j+=h*y,j+=d*g,i=O=8191&(N=(N=((N+=(j+=f*p)>>>13)<<2)+N|0)+(O&=8191)|0),s=L+=N>>>=13,o=B&=8191,a=x&=8191,c=M&=8191,l=U&=8191,u=F&=8191,h=V&=8191,d=K&=8191,f=j&=8191,t+=16,r-=16}this._h[0]=i,this._h[1]=s,this._h[2]=o,this._h[3]=a,this._h[4]=c,this._h[5]=l,this._h[6]=u,this._h[7]=h,this._h[8]=d,this._h[9]=f},e.prototype.finish=function(e,t){void 0===t&&(t=0);var r,n,i,s,o=new Uint16Array(10);if(this._leftover){for(s=this._leftover,this._buffer[s++]=1;s<16;s++)this._buffer[s]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(r=this._h[1]>>>13,this._h[1]&=8191,s=2;s<10;s++)this._h[s]+=r,r=this._h[s]>>>13,this._h[s]&=8191;for(this._h[0]+=5*r,r=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=r,r=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=r,o[0]=this._h[0]+5,r=o[0]>>>13,o[0]&=8191,s=1;s<10;s++)o[s]=this._h[s]+r,r=o[s]>>>13,o[s]&=8191;for(o[9]-=8192,n=(1^r)-1,s=0;s<10;s++)o[s]&=n;for(n=~n,s=0;s<10;s++)this._h[s]=this._h[s]&n|o[s];for(this._h[0]=65535&(this._h[0]|this._h[1]<<13),this._h[1]=65535&(this._h[1]>>>3|this._h[2]<<10),this._h[2]=65535&(this._h[2]>>>6|this._h[3]<<7),this._h[3]=65535&(this._h[3]>>>9|this._h[4]<<4),this._h[4]=65535&(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14),this._h[5]=65535&(this._h[6]>>>2|this._h[7]<<11),this._h[6]=65535&(this._h[7]>>>5|this._h[8]<<8),this._h[7]=65535&(this._h[8]>>>8|this._h[9]<<5),i=this._h[0]+this._pad[0],this._h[0]=65535&i,s=1;s<8;s++)i=(this._h[s]+this._pad[s]|0)+(i>>>16)|0,this._h[s]=65535&i;return e[t+0]=this._h[0]>>>0,e[t+1]=this._h[0]>>>8,e[t+2]=this._h[1]>>>0,e[t+3]=this._h[1]>>>8,e[t+4]=this._h[2]>>>0,e[t+5]=this._h[2]>>>8,e[t+6]=this._h[3]>>>0,e[t+7]=this._h[3]>>>8,e[t+8]=this._h[4]>>>0,e[t+9]=this._h[4]>>>8,e[t+10]=this._h[5]>>>0,e[t+11]=this._h[5]>>>8,e[t+12]=this._h[6]>>>0,e[t+13]=this._h[6]>>>8,e[t+14]=this._h[7]>>>0,e[t+15]=this._h[7]>>>8,this._finished=!0,this},e.prototype.update=function(e){var t,r=0,n=e.length;if(this._leftover){(t=16-this._leftover)>n&&(t=n);for(var i=0;i=16&&(t=n-n%16,this._blocks(e,r,t),r+=t,n-=t),n){for(i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.randomStringForEntropy=t.randomString=t.randomUint32=t.randomBytes=t.defaultRandomSource=void 0;const n=r(933),i=r(6232),s=r(9116);function o(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.defaultRandomSource;return r.randomBytes(e)}t.defaultRandomSource=new n.SystemRandomSource,t.randomBytes=o,t.randomUint32=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t.defaultRandomSource;const r=o(4,e),n=(0,i.readUint32LE)(r);return(0,s.wipe)(r),n};const a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function c(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.defaultRandomSource;if(r.length<2)throw new Error("randomString charset is too short");if(r.length>256)throw new Error("randomString charset is too long");let i="";const c=r.length,l=256-256%c;for(;e>0;){const t=o(Math.ceil(256*e/l),n);for(let n=0;n0;n++){const s=t[n];s1&&void 0!==arguments[1]?arguments[1]:a,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.defaultRandomSource;const i=Math.ceil(e/(Math.log(r.length)/Math.LN2));return c(i,r,n)}},8136:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserRandomSource=void 0;t.BrowserRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;const e="undefined"!==typeof self?self.crypto||self.msCrypto:null;e&&void 0!==e.getRandomValues&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");const t=new Uint8Array(e);for(let r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NodeRandomSource=void 0;const n=r(9116);t.NodeRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;{const e=r(5883);e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");const r=new Uint8Array(e);for(let n=0;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemRandomSource=void 0;const n=r(8136),i=r(8188);t.SystemRandomSource=class{constructor(){return this.isAvailable=!1,this.name="",this._source=new n.BrowserRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Browser")):(this._source=new i.NodeRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Node")):void 0)}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}}},4888:(e,t,r)=>{"use strict";var n=r(6232),i=r(9116);t.k=32,t.cn=64;var s=function(){function e(){this.digestLength=t.k,this.blockSize=t.cn,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return e.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},e.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},e.prototype.clean=function(){i.wipe(this._buffer),i.wipe(this._temp),this.reset()},e.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var r=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[r++],t--;this._bufferLength===this.blockSize&&(a(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(r=a(this._temp,this._state,e,r,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[r++],t--;return this},e.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,r=this._bufferLength,i=t/536870912|0,s=t<<3,o=t%64<56?64:128;this._buffer[r]=128;for(var c=r+1;c0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},e.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},e.prototype.cleanSavedState=function(e){i.wipe(e.state),e.buffer&&i.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},e}();t.mE=s;var o=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function a(e,t,r,i,s){for(;s>=64;){for(var a=t[0],c=t[1],l=t[2],u=t[3],h=t[4],d=t[5],f=t[6],p=t[7],g=0;g<16;g++){var y=i+4*g;e[g]=n.readUint32BE(r,y)}for(g=16;g<64;g++){var m=e[g-2],v=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,w=((m=e[g-15])>>>7|m<<25)^(m>>>18|m<<14)^m>>>3;e[g]=(v+e[g-7]|0)+(w+e[g-16]|0)}for(g=0;g<64;g++){v=(((h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(h&d^~h&f)|0)+(p+(o[g]+e[g]|0)|0)|0,w=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&c^a&l^c&l)|0;p=f,f=d,d=h,h=u+v|0,u=l,l=c,c=a,a=v+w|0}t[0]+=a,t[1]+=c,t[2]+=l,t[3]+=u,t[4]+=h,t[5]+=d,t[6]+=f,t[7]+=p,i+=64,s-=64}return i}t.vp=function(e){var t=new s;t.update(e);var r=t.digest();return t.clean(),r}},9116:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wipe=function(e){for(var t=0;t{"use strict";t.gi=t.Au=t._w=t.KS=t.kz=void 0;const n=r(6271),i=r(9116);function s(e){const t=new Float64Array(16);if(e)for(let r=0;r=0;--s){const e=r[s>>>3]>>>(7&s)&1;l(i,o,e),l(p,g,e),u(y,i,p),h(i,i,p),u(p,o,g),h(o,o,g),f(g,y),f(m,i),d(i,p,i),d(p,o,y),u(y,i,p),h(i,i,p),f(o,i),h(p,g,m),d(i,p,a),u(i,i,g),d(p,p,i),d(i,g,m),d(g,o,n),f(o,y),l(i,o,e),l(p,g,e)}for(let s=0;s<16;s++)n[s+16]=i[s],n[s+32]=p[s],n[s+48]=o[s],n[s+64]=g[s];const v=n.subarray(32),w=n.subarray(16);!function(e,t){const r=s();for(let n=0;n<16;n++)r[n]=t[n];for(let n=253;n>=0;n--)f(r,r),2!==n&&4!==n&&d(r,r,t);for(let n=0;n<16;n++)e[n]=r[n]}(v,v),d(w,w,v);const b=new Uint8Array(32);return function(e,t){const r=s(),n=s();for(let i=0;i<16;i++)n[i]=t[i];c(n),c(n),c(n);for(let i=0;i<2;i++){r[0]=n[0]-65517;for(let t=1;t<15;t++)r[t]=n[t]-65535-(r[t-1]>>16&1),r[t-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);const e=r[15]>>16&1;r[14]&=65535,l(n,r,1-e)}for(let i=0;i<16;i++)e[2*i]=255&n[i],e[2*i+1]=n[i]>>8}(b,w),b}function g(e){return p(e,o)}function y(e){if(e.length!==t.KS)throw new Error("x25519: seed must be ".concat(t.KS," bytes"));const r=new Uint8Array(e);return{publicKey:g(r),secretKey:r}}t._w=y,t.Au=function(e){const t=(0,n.randomBytes)(32,e),r=y(t);return(0,i.wipe)(t),r},t.gi=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(e.length!==t.kz)throw new Error("X25519: incorrect secret key length");if(r.length!==t.kz)throw new Error("X25519: incorrect public key length");const i=p(e,r);if(n){let e=0;for(let t=0;t{function t(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)t&&t.removeEventListener&&t.removeEventListener("abort",r)}for(const n of e)if(n&&n.addEventListener){if(n.aborted){r();break}n.addEventListener("abort",r)}return t.signal}e.exports=t,e.exports.anySignal=t},312:e=>{var t=1e3,r=60*t,n=60*r,i=24*n,s=7*i,o=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var s=Math.abs(e);if(s>=i)return a(e,s,i,"day");if(s>=n)return a(e,s,n,"hour");if(s>=r)return a(e,s,r,"minute");if(s>=t)return a(e,s,t,"second");return e+" ms"}(e):function(e){var s=Math.abs(e);if(s>=i)return Math.round(e/i)+"d";if(s>=n)return Math.round(e/n)+"h";if(s>=r)return Math.round(e/r)+"m";if(s>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},8392:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(r){}!e&&"undefined"!==typeof process&&"env"in process&&(e={NODE_ENV:"production",PUBLIC_URL:"/relay-reactjs-chat",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.DEBUG);return e},t.useColors=function(){if("undefined"!==typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!==typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!==typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(8472)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}},8472:(e,t,r)=>{e.exports=function(e){function t(e){let r,i,s,o=null;function a(){for(var e=arguments.length,n=new Array(e),i=0;i{if("%%"===e)return"%";l++;const i=t.formatters[r];if("function"===typeof i){const t=n[l];e=i.call(s,t),n.splice(l,1),l--}return e})),t.formatArgs.call(s,n);const u=s.log||t.log;u.apply(s,n)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"===typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+("undefined"===typeof r?":":r)+e);return n.log=this.log,n}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"===typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";function t(e,t){t=t||{};this._head=0,this._tail=0,this._capacity=t.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}t.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}},t.prototype.get=function(e){return this.peekAt(e)},t.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},t.prototype.peekFront=function(){return this.peek()},t.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(t.prototype,"length",{get:function(){return this.size()}}),t.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},t.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var i,s=this._list[t];if(e0;i--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(i=r-1-e;i>0;i--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return s}}},t.prototype.remove=function(e,t){var r,n=e,i=t;if(n===(0|n)&&this._head!==this._tail){var s=this.size(),o=this._list.length;if(!(n>=s||n<-s||t<1)){if(n<0&&(n+=s),1===t||!t)return(r=new Array(1))[0]=this.removeOne(n),r;if(0===n&&n+t>=s)return r=this.toArray(),this.clear(),r;var a;for(n+t>s&&(t=s-n),r=new Array(t),a=0;a0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+o&this._capacityMask,a=t-1;a>0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(n0;a--)this.unshift(this._list[n=n-1+o&this._capacityMask]);for(n=this._head-1+o&this._capacityMask;i>0;)this._list[n=n-1+o&this._capacityMask]=void 0,i--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+o&this._capacityMask,a=s-(t+e);a>0;a--)this.push(this._list[n++]);for(n=this._tail;i>0;)this._list[n=n+1+o&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=o>>>2&&this._shrinkArray(),r}}},t.prototype.splice=function(e,t){var r=e;if(r===(0|r)){var n=this.size();if(r<0&&(r+=n),!(r>n)){if(arguments.length>2){var i,s,o,a=arguments.length,c=this._list.length,l=2;if(!n||r0&&(this._head=this._head+r+c&this._capacityMask)):(o=this.remove(r,t),this._head=this._head+r+c&this._capacityMask);a>l;)this.unshift(arguments[--a]);for(i=r;i>0;i--)this.unshift(s[i-1])}else{var u=(s=new Array(n-(r+t))).length;for(i=0;ithis._tail){for(t=this._head;t>>=1,this._capacityMask>>>=1},e.exports=t},7963:e=>{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,n){if(!e||"string"===typeof e)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"===typeof r&&(n=r,r=""),r&&(n.code=r);try{return t(e,n)}catch(i){n.message=e.message,n.stack=e.stack;const r=function(){};r.prototype=Object.create(Object.getPrototypeOf(e));return t(new r,n)}}},3634:(e,t,r)=>{"use strict";const n=r(5413);t.zN=n.EventIterator,n.EventIterator},5413:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn("EventIterator queue reached ".concat(this.pushQueue.length," items")))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e){let{highWaterMark:t=100,lowWaterMark:n=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new r;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},7143:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,o){if("function"!==typeof n)throw new TypeError("The listener must be a function");var a=new i(n,s||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i{"use strict";var t,r="object"===typeof Reflect?Reflect:null,n=r&&"function"===typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"===typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"===typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}g(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"===typeof e.on&&g(e,"error",t,r)}(e,i,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!==typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function l(e,t,r,n){var i,s,o,l;if(a(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"===typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=c(e))>0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,l=u,console&&console.warn&&console.warn(l)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=u.bind(n);return i.listener=r,n.wrapFn=i,i}function d(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"===typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return!1;if("function"===typeof c)n(c,this,t);else{var l=c.length,u=p(c,l);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return d(this,e,!0)},s.prototype.rawListeners=function(e){return d(this,e,!1)},s.listenerCount=function(e,t){return"function"===typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},1167:e=>{e.exports=class{constructor(e){if(!(e>0)||0!==(e-1&e))throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}}},5125:(e,t,r)=>{const n=r(1167);e.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head}push(e){if(!this.head.push(e)){const t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){const e=this.tail.shift();if(void 0===e&&this.tail.next){const e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}},4737:e=>{e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,s){r[i]=s,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},8974:e=>{"use strict";const t="[a-fA-F\\d:]",r=e=>e&&e.includeBoundaries?"(?:(?<=\\s|^)(?=".concat(t,")|(?<=").concat(t,")(?=\\s|$))"):"",n="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",i="[a-fA-F\\d]{1,4}",s="\n(?:\n(?:".concat(i,":){7}(?:").concat(i,"|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:").concat(i,":){6}(?:").concat(n,"|:").concat(i,"|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:").concat(i,":){5}(?::").concat(n,"|(?::").concat(i,"){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:").concat(i,":){4}(?:(?::").concat(i,"){0,1}:").concat(n,"|(?::").concat(i,"){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:").concat(i,":){3}(?:(?::").concat(i,"){0,2}:").concat(n,"|(?::").concat(i,"){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:").concat(i,":){2}(?:(?::").concat(i,"){0,3}:").concat(n,"|(?::").concat(i,"){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:").concat(i,":){1}(?:(?::").concat(i,"){0,4}:").concat(n,"|(?::").concat(i,"){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::").concat(i,"){0,5}:").concat(n,"|(?::").concat(i,"){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n").replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),o=new RegExp("(?:^".concat(n,"$)|(?:^").concat(s,"$)")),a=new RegExp("^".concat(n,"$")),c=new RegExp("^".concat(s,"$")),l=e=>e&&e.exact?o:new RegExp("(?:".concat(r(e)).concat(n).concat(r(e),")|(?:").concat(r(e)).concat(s).concat(r(e),")"),"g");l.v4=e=>e&&e.exact?a:new RegExp("".concat(r(e)).concat(n).concat(r(e)),"g"),l.v6=e=>e&&e.exact?c:new RegExp("".concat(r(e)).concat(s).concat(r(e)),"g"),e.exports=l},7201:function(e){!function(t){"use strict";const r="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^".concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"$"),"i"),threeOctet:new RegExp("^".concat(r,"\\.").concat(r,"\\.").concat(r,"$"),"i"),twoOctet:new RegExp("^".concat(r,"\\.").concat(r,"$"),"i"),longValue:new RegExp("^".concat(r,"$"),"i")},i=new RegExp("^0[0-7]+$","i"),s=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",a="(?:[0-9a-f]+::?)+",c={zoneIndex:new RegExp(o,"i"),native:new RegExp("^(::)?(".concat(a,")?([0-9a-f]+)?(::)?(").concat(o,")?$"),"i"),deprecatedTransitional:new RegExp("^(?:::)(".concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"(").concat(o,")?)$"),"i"),transitional:new RegExp("^((?:".concat(a,")|(?:::)(?:").concat(a,")?)").concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"(").concat(o,")?$"),"i")};function l(e,t){if(e.indexOf("::")!==e.lastIndexOf("::"))return null;let r,n,i=0,s=-1,o=(e.match(c.zoneIndex)||[])[0];for(o&&(o=o.substring(1),e=e.replace(/%.+$/,""));(s=e.indexOf(":",s+1))>=0;)i++;if("::"===e.substr(0,2)&&i--,"::"===e.substr(-2,2)&&i--,i>t)return null;for(n=t-i,r=":";n--;)r+="0:";return":"===(e=e.replace("::",r))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){const t=e.split(":"),r=[];for(let e=0;e0;){if(i=r-n,i<0&&(i=0),e[s]>>i!==t[s]>>i)return!1;n-=r,s+=1}return!0}function h(e){if(s.test(e))return parseInt(e,16);if("0"===e[0]&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw new Error("ipaddr: cannot parse ".concat(e," as octal"))}return parseInt(e,10)}function d(e,t){for(;e.length=0;n-=1){if(i=this.octets[n],!(i in r))return null;if(s=r[i],t&&0!==s)return null;8!==s&&(t=!0),e+=s}return 32-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return f.IPv6.parse("::ffff:".concat(this.toString()))},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(".")},e}(),f.IPv4.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let s=0;for(;s<4;)i.push(parseInt(r[s],10)|255^parseInt(n[s],10)),s++;return new this(i)}catch(t){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.isIPv4=function(e){return null!==this.parser(e)},f.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(t){return!1}},f.IPv4.isValidFourPartDecimal=function(e){return!(!f.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},f.IPv4.networkAddressFromCIDR=function(e){let t,r,n,i,s;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(o){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.parse=function(e){const t=this.parser(e);if(null===t)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(t)},f.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){const e=parseInt(t[2]);if(e>=0&&e<=32){const r=[this.parse(t[1]),e];return Object.defineProperty(r,"toString",{value:function(){return this.join("/")}}),r}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},f.IPv4.parser=function(e){let t,r,i;if(t=e.match(n.fourOctet))return function(){const e=t.slice(1,6),n=[];for(let t=0;t4294967295||i<0)throw new Error("ipaddr: address outside defined range");return function(){const e=[];let t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e}().reverse()}return(t=e.match(n.twoOctet))?function(){const e=t.slice(1,4),r=[];if(i=h(e[1]),i>16777215||i<0)throw new Error("ipaddr: address outside defined range");return r.push(h(e[0])),r.push(i>>16&255),r.push(i>>8&255),r.push(255&i),r}():(t=e.match(n.threeOctet))?function(){const e=t.slice(1,5),r=[];if(i=h(e[2]),i>65535||i<0)throw new Error("ipaddr: address outside defined range");return r.push(h(e[0])),r.push(h(e[1])),r.push(i>>8&255),r.push(255&i),r}():null},f.IPv4.subnetMaskFromPrefixLength=function(e){if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");const t=[0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r=0;s-=1){if(n=this.parts[s],!(n in r))return null;if(i=r[n],t&&0!==i)return null;16!==i&&(t=!0),e+=i}return 128-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e;const t=[],r=this.parts;for(let n=0;n>8),t.push(255&e);return t},e.prototype.toFixedLengthString=function(){const e=function(){const e=[];for(let t=0;t>8,255&t,r>>8,255&r])},e.prototype.toNormalizedString=function(){const e=function(){const e=[];for(let t=0;ti&&(n=r.index,i=r[0].length);return i<0?t:"".concat(t.substring(0,n),"::").concat(t.substring(n+i))},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e}(),f.IPv6.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let s=0;for(;s<16;)i.push(parseInt(r[s],10)|255^parseInt(n[s],10)),s++;return new this(i)}catch(t){throw new Error("ipaddr: the address does not have IPv6 CIDR format (".concat(t,")"))}},f.IPv6.isIPv6=function(e){return null!==this.parser(e)},f.IPv6.isValid=function(e){if("string"===typeof e&&-1===e.indexOf(":"))return!1;try{const t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch(t){return!1}},f.IPv6.networkAddressFromCIDR=function(e){let t,r,n,i,s;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<16;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(o){throw new Error("ipaddr: the address does not have IPv6 CIDR format (".concat(o,")"))}},f.IPv6.parse=function(e){const t=this.parser(e);if(null===t.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(t.parts,t.zoneId)},f.IPv6.parseCIDR=function(e){let t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]),t>=0&&t<=128))return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},f.IPv6.parser=function(e){let t,r,n,i,s,o;if(n=e.match(c.deprecatedTransitional))return this.parser("::ffff:".concat(n[1]));if(c.native.test(e))return l(e,8);if((n=e.match(c.transitional))&&(o=n[6]||"",t=l(n[1].slice(0,-1)+o,6),t.parts)){for(s=[parseInt(n[2]),parseInt(n[3]),parseInt(n[4]),parseInt(n[5])],r=0;r128)throw new Error("ipaddr: invalid IPv6 prefix length");const t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r{e.exports=function(){return"undefined"!==typeof window&&"object"===typeof window.process&&"renderer"===window.process.type||(!("undefined"===typeof process||"object"!==typeof process.versions||!process.versions.electron)||"object"===typeof navigator&&"string"===typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}},2795:(e,t,r)=>{"use strict";const n=r(8974),i=e=>n({exact:!0}).test(e);i.v4=e=>n.v4({exact:!0}).test(e),i.v6=e=>n.v6({exact:!0}).test(e),i.version=e=>i(e)?i.v4(e)?4:6:void 0,e.exports=i},887:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},6791:(e,t,r)=>{"use strict";const{URLWithLegacySupport:n,format:i,URLSearchParams:s,defaultBase:o}=r(5732),a=r(9640);e.exports={URL:n,URLSearchParams:s,format:i,relative:a,defaultBase:o}},9640:(e,t,r)=>{"use strict";const{URLWithLegacySupport:n,format:i}=r(5732);e.exports=function(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3?arguments[3]:void 0,a=r.protocol?r.protocol.replace(":",""):"http";a=(s[a]||o||a)+":";try{t=new n(e)}catch(l){t={}}const c=Object.assign({},r,{protocol:a||t.protocol,host:r.host||t.host});return new n(e,i(c)).toString()}},5732:e=>{"use strict";const t="undefined"!==typeof navigator&&"ReactNative"===navigator.product;const r=self.URL,n=t?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:"";e.exports={URLWithLegacySupport:class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;this.super=new r(e,t),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(e){this.super.hash=e}set host(e){this.super.host=e}set hostname(e){this.super.hostname=e}set href(e){this.super.href=e}set password(e){this.super.password=e}set pathname(e){this.super.pathname=e}set port(e){this.super.port=e}set protocol(e){this.super.protocol=e}set search(e){this.super.search=e}set username(e){this.super.username=e}static createObjectURL(e){return r.createObjectURL(e)}static revokeObjectURL(e){r.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}},URLSearchParams:self.URLSearchParams,defaultBase:n,format:function(e){if("string"===typeof e){return new r(e).toString()}if(!(e instanceof r)){const t=e.username&&e.password?"".concat(e.username,":").concat(e.password,"@"):"",r=e.auth?e.auth+"@":"",n=e.port?":"+e.port:"",i=e.protocol?e.protocol+"//":"",s=e.host||"",o=e.hostname||"",a=e.search||(e.query?"?"+e.query:""),c=e.hash||"",l=e.pathname||"",u=e.path||l+a;return"".concat(i).concat(t||r).concat(s||o+n).concat(u).concat(c)}}}},464:e=>{"use strict";e.exports=async e=>{const t=[];for await(const r of e)t.push(r);return t}},9272:e=>{"use strict";e.exports=async e=>{for await(const t of e);}},2393:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)await t(r)&&(yield r)}},4744:e=>{"use strict";e.exports=async e=>{for await(const t of e)return t}},1309:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)await t(r),yield r}},7889:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)yield t(r)}},6155:(e,t,r)=>{"use strict";const n=r(9202);e.exports=async function*(){for(var e=arguments.length,t=new Array(e),r=0;r{try{await Promise.all(t.map((async e=>{for await(const t of e)i.push(t)}))),i.end()}catch(e){i.end(e)}}),0),yield*i}},9202:(e,t,r)=>{const n=r(5125);e.exports=e=>{let t;"function"===typeof(e=e||{})?(t=e,e={}):t=e.onEnd;let r,i,s,o=new n;const a=e=>i?i(e):(o.push(e),r),c=e=>s?r:a({done:!1,value:e}),l=e=>s?r:(s=!0,e?(e=>(o=new n,i?i({error:e}):(o.push({error:e}),r)))(e):a({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:()=>{if(!o.isEmpty()){if(e.writev){let e;const t=[];for(;!o.isEmpty();){if(e=o.shift(),e.error)throw e.error;t.push(e.value)}return{done:e.done,value:t}}const t=o.shift();if(t.error)throw t.error;return t}return s?{done:!0}:new Promise(((t,n)=>{i=s=>(i=null,s.error?n(s.error):e.writev&&!s.done?t({done:s.done,value:[s.value]}):t(s),r)}))},return:()=>(o=new n,l(),{done:!0}),throw:e=>(l(e),{done:!0}),push:c,end:l},!t)return r;const u=r;return r={[Symbol.asyncIterator](){return this},next:()=>u.next(),throw:e=>(u.throw(e),t&&(t(e),t=null),{done:!0}),return:()=>(u.return(),t&&(t(),t=null),{done:!0}),push:c,end:e=>(u.end(e),t&&(t(e),t=null),r)},r}},2035:(e,t,r)=>{"use strict";const n=r(464);e.exports=async function*(e,t){const r=await n(e);yield*r.sort(t)}},5959:e=>{"use strict";e.exports=async function*(e,t){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}},7898:(e,t,r)=>{var n;!function(){"use strict";var i="input is invalid type",s="object"===typeof window,o=s?window:{};o.JS_SHA3_NO_WINDOW&&(s=!1);var a=!s&&"object"===typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"===typeof process&&process.versions&&process.versions.node?o=r.g:a&&(o=self);var c=!o.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!==typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],f=[0,8,16,24],p=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],v={128:168,256:136};!o.JS_SHA3_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!u||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"===typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});for(var w=function(e,t,r){return function(n){return new L(e,t,e).update(n)[r]()}},b=function(e,t,r){return function(n,i){return new L(e,t,i).update(n)[r]()}},E=function(e,t,r){return function(t,n,i,s){return C["cshake"+e].update(t,n,i,s)[r]()}},S=function(e,t,r){return function(t,n,i,s){return C["kmac"+e].update(t,n,i,s)[r]()}},_=function(e,t,r,n){for(var i=0;i>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function B(e,t,r){L.call(this,e,t,r)}L.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(i);if(null===e)throw new Error(i);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!u||!ArrayBuffer.isView(e)))throw new Error(i);t=!0}for(var n,s,o=this.blocks,a=this.byteCount,c=e.length,l=this.blockCount,h=0,d=this.s;h>2]|=e[h]<>2]|=s<>2]|=(192|s>>6)<>2]|=(128|63&s)<=57344?(o[n>>2]|=(224|s>>12)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<>2]|=(240|s>>18)<>2]|=(128|s>>12&63)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<=a){for(this.start=n-a,this.block=o[l],n=0;n>=8);r>0;)i.unshift(r),r=255&(e>>=8),++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},L.prototype.encodeString=function(e){var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(i);if(null===e)throw new Error(i);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!u||!ArrayBuffer.isView(e)))throw new Error(i);t=!0}var n=0,s=e.length;if(t)n=s;else for(var o=0;o=57344?n+=3:(a=65536+((1023&a)<<10|1023&e.charCodeAt(++o)),n+=4)}return n+=this.encode(8*n),this.update(e),n},L.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];o%t===0&&(x(r),s=0)}return i&&(e=r[s],a+=h[e>>4&15]+h[15&e],i>1&&(a+=h[e>>12&15]+h[e>>8&15]),i>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},L.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r===0&&x(n)}return s&&(e=a<<2,t=n[o],c[e]=255&t,s>1&&(c[e+1]=t>>8&255),s>2&&(c[e+2]=t>>16&255)),c},B.prototype=new L,B.prototype.finalize=function(){return this.encode(this.outputBits,!0),L.prototype.finalize.call(this)};var x=function(e){var t,r,n,i,s,o,a,c,l,u,h,d,f,g,y,m,v,w,b,E,S,_,I,A,C,T,R,k,P,D,N,O,L,B,x,M,U,F,V,K,j,z,q,H,G,W,Q,Y,$,X,J,Z,ee,te,re,ne,ie,se,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|l>>>31),r=s^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(u<<1|h>>>31),r=a^(h<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|f>>>31),r=l^(f<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(i<<1|s>>>31),r=h^(s<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Q=e[10]<<4|e[11]>>>28,k=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,q=e[41]<<18|e[40]>>>14,B=e[2]<<1|e[3]>>>31,x=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,$=e[23]<<10|e[22]>>>22,D=e[33]<<13|e[32]>>>19,N=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,M=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,b=e[24]<<11|e[25]>>>21,X=e[34]<<15|e[35]>>>17,J=e[35]<<15|e[34]>>>17,O=e[45]<<29|e[44]>>>3,L=e[44]<<29|e[45]>>>3,A=e[6]<<28|e[7]>>>4,C=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,V=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,H=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,T=e[18]<<20|e[19]>>>12,R=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,K=e[38]<<8|e[39]>>>24,j=e[39]<<8|e[38]>>>24,_=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~v&b,e[10]=A^~T&k,e[11]=C^~R&P,e[20]=B^~M&F,e[21]=x^~U&V,e[30]=H^~W&Y,e[31]=G^~Q&$,e[40]=te^~ne&se,e[41]=re^~ie&oe,e[2]=m^~w&E,e[3]=v^~b&S,e[12]=T^~k&D,e[13]=R^~P&N,e[22]=M^~F&K,e[23]=U^~V&j,e[32]=W^~Y&X,e[33]=Q^~$&J,e[42]=ne^~se&ae,e[43]=ie^~oe&ce,e[4]=w^~E&_,e[5]=b^~S&I,e[14]=k^~D&O,e[15]=P^~N&L,e[24]=F^~K&z,e[25]=V^~j&q,e[34]=Y^~X&Z,e[35]=$^~J&ee,e[44]=se^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~_&g,e[7]=S^~I&y,e[16]=D^~O&A,e[17]=N^~L&C,e[26]=K^~z&B,e[27]=j^~q&x,e[36]=X^~Z&H,e[37]=J^~ee&G,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=_^~g&m,e[9]=I^~y&v,e[18]=O^~A&T,e[19]=L^~C&R,e[28]=z^~B&M,e[29]=q^~x&U,e[38]=Z^~H&W,e[39]=ee^~G&Q,e[48]=le^~te&ne,e[49]=ue^~re&ie,e[0]^=p[n],e[1]^=p[n+1]};if(c)e.exports=C;else{for(R=0;RObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},l=e=>{const t=[];for(const r in e)i.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)s.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{o(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{o(t,r,u(e[r]))})),t}(e):e}const h=(e,t,r,n)=>(r.forEach((r=>{"undefined"===typeof t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?o(e,r,d(e[r],t[r],n)):o(e,r,u(t[r])))})),e);function d(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?((e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!a.includes(e))),r)})),n})(e,t,r):n(t)&&n(e)?h(e,t,l(t),r):u(t)}e.exports=function(){const e=d(u(c),this!==a&&this||{},c);let t={_:{}};for(var r=arguments.length,i=new Array(r),s=0;s{var t=1e3,r=60*t,n=60*r,i=24*n,s=7*i,o=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var s=Math.abs(e);if(s>=i)return a(e,s,i,"day");if(s>=n)return a(e,s,n,"hour");if(s>=r)return a(e,s,r,"minute");if(s>=t)return a(e,s,t,"second");return e+" ms"}(e):function(e){var s=Math.abs(e);if(s>=i)return Math.round(e/i)+"d";if(s>=n)return Math.round(e/n)+"h";if(s>=r)return Math.round(e/r)+"m";if(s>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},486:e=>{"use strict";function t(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,i,s,o,a;for(t=[],i=s=0;s<=3&&0!==e.length;i=++s){if(i>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}o=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(o)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},i=(n=function(e){return e.charCodeAt(0)})("0"),o=n("a"),s=n("A"),r=function(e){var t,r,a,c,l;for(c=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),l=a;a>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-s)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,i;if("string"!==typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"===typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(s){throw s,new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(s){throw s,new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"===typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},8605:(e,t,r)=>{var n=r(392);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(3397),r(4533),r(3877),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!1,mode:n});return i.start(t),i},n.aes.createEncryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!0,mode:n});return i.start(t),i},n.aes.createDecryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){u||h();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return f(r._w,e,t,!1)},decrypt:function(e,t){return f(r._w,e,t,!0)}}}),r._init=!1},n.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!==typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var i=0;i>>=2;for(i=0;i>8^255&h^99,s[g]=h,o[h]=g,f=(d=e[h])<<24^h<<16^h<<8^h^d,p=((r=e[g])^(n=e[r])^(i=e[n]))<<24^(g^i)<<16^(g^n^i)<<8^g^r^i;for(var m=0;m<4;++m)c[m][g]=f,l[m][h]=p,f=f<<24|f>>>8,p=p<<24|p>>>8;0===g?g=y=1:(g=r^e[e[e[r^i]]],y^=e[e[y]])}}function d(e,t){for(var r,n=e.slice(0),i=1,o=n.length,c=4*(o+6+1),u=o;u>>16&255]<<24^s[r>>>8&255]<<16^s[255&r]<<8^s[r>>>24]^a[i]<<24,i++):o>6&&u%o===4&&(r=s[r>>>24]<<24^s[r>>>16&255]<<16^s[r>>>8&255]<<8^s[255&r]),n[u]=n[u-o]^r;if(t){for(var h,d=l[0],f=l[1],p=l[2],g=l[3],y=n.slice(0),m=(u=0,(c=n.length)-4);u>>24]]^f[s[h>>>16&255]]^p[s[h>>>8&255]]^g[s[255&h]];n=y}return n}function f(e,t,r,n){var i,a,u,h,d,f,p,g,y,m,v,w,b=e.length/4-1;n?(i=l[0],a=l[1],u=l[2],h=l[3],d=o):(i=c[0],a=c[1],u=c[2],h=c[3],d=s),f=t[0]^e[0],p=t[n?3:1]^e[1],g=t[2]^e[2],y=t[n?1:3]^e[3];for(var E=3,S=1;S>>24]^a[p>>>16&255]^u[g>>>8&255]^h[255&y]^e[++E],v=i[p>>>24]^a[g>>>16&255]^u[y>>>8&255]^h[255&f]^e[++E],w=i[g>>>24]^a[y>>>16&255]^u[f>>>8&255]^h[255&p]^e[++E],y=i[y>>>24]^a[f>>>16&255]^u[p>>>8&255]^h[255&g]^e[++E],f=m,p=v,g=w;r[0]=d[f>>>24]<<24^d[p>>>16&255]<<16^d[g>>>8&255]<<8^d[255&y]^e[++E],r[n?3:1]=d[p>>>24]<<24^d[g>>>16&255]<<16^d[y>>>8&255]<<8^d[255&f]^e[++E],r[2]=d[g>>>24]<<24^d[y>>>16&255]<<16^d[f>>>8&255]<<8^d[255&p]^e[++E],r[n?1:3]=d[y>>>24]<<24^d[f>>>16&255]<<16^d[p>>>8&255]<<8^d[255&g]^e[++E]}function p(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var s=null;r instanceof n.util.ByteBuffer&&(s=r,r={}),(r=r||{}).output=s,r.iv=e,i.call(t,r)},t}},5049:(e,t,r)=>{var n=r(392);r(3877),r(2886);var i=e.exports=n.asn1=n.asn1||{};function s(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}i.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},i.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},i.create=function(e,t,r,s,o){if(n.util.isArray(s)){for(var a=[],c=0;ct){if(n.strict){var p=new Error("Too few bytes to read ASN.1 value.");throw p.available=e.length(),p.remaining=t,p.requested=f,p}f=t}var g=32===(32&c);if(g)if(h=[],void 0===f)for(;;){if(s(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}a=e.length(),h.push(o(e,t,r+1,n)),t-=a-e.length()}else for(;f>0;)a=e.length(),h.push(o(e,f,r+1,n)),t-=a-e.length(),f-=a-e.length();if(void 0===h&&l===i.Class.UNIVERSAL&&u===i.Type.BITSTRING&&(d=e.bytes(f)),void 0===h&&n.decodeBitStrings&&l===i.Class.UNIVERSAL&&u===i.Type.BITSTRING&&f>1){var y=e.read,m=t,v=0;if(u===i.Type.BITSTRING&&(s(e,t,1),v=e.getByte(),t--),0===v)try{a=e.length();var w=o(e,t,r+1,{strict:!0,decodeBitStrings:!0}),b=a-e.length();t-=b,u==i.Type.BITSTRING&&b++;var E=w.tagClass;b!==f||E!==i.Class.UNIVERSAL&&E!==i.Class.CONTEXT_SPECIFIC||(h=[w])}catch(_){}void 0===h&&(e.read=y,t=m)}if(void 0===h){if(void 0===f){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");f=t}if(u===i.Type.BMPSTRING)for(h="";f>0;f-=2)s(e,t,2),h+=String.fromCharCode(e.getInt16()),t-=2;else h=e.getBytes(f),t-=f}var S=void 0===d?null:{bitStringContents:d};return i.create(l,u,g,h,S)}i.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"===typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.length(),i=o(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var s=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw s.byteCount=r,s.remaining=e.length(),s}return i},i.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,s=n.util.createBuffer(),o=!1;if("bitStringContents"in e&&(o=!0,e.original&&(o=i.equals(e,e.original))),o)s.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:s.putByte(0);for(var a=0;a1&&(0===e.value.charCodeAt(0)&&0===(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128===(128&e.value.charCodeAt(1)))?s.putBytes(e.value.substr(1)):s.putBytes(e.value);if(t.putByte(r),s.length()<=127)t.putByte(127&s.length());else{var c=s.length(),l="";do{l+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|l.length);for(a=l.length-1;a>=0;--a)t.putByte(l.charCodeAt(a))}return t.putBuffer(s),t},i.oidToDer=function(e){var t,r,i,s,o=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(o[0],10)+parseInt(o[1],10));for(var c=2;c>>=7,t||(s|=128),r.push(s),t=!1}while(i>0);for(var l=r.length-1;l>=0;--l)a.putByte(r[l])}return a},i.derToOid=function(e){var t;"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var i=0;e.length()>0;)i<<=7,128&(r=e.getByte())?i+=127&r:(t+="."+(i+r),i=0);return t},i.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),s=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),l=10;"+"!==c&&"-"!==c&&(a=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,0),l&&("+"===(c=e.charAt(l))||"-"===c)){var u=60*parseInt(e.substr(l+1,2),10)+parseInt(e.substr(l+4,2),10);u*=6e4,"+"===c?t.setTime(+t-u):t.setTime(+t+u)}return t},i.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,l=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var h=e.length-5,d=e.charAt(h);"+"!==d&&"-"!==d||(l=60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10),l*=6e4,"+"===d&&(l*=-1),u=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,c),t.setTime(+t+l)):(t.setFullYear(r,n,i),t.setHours(s,o,a,c)),t},i.dateToUtcTime=function(e){if("string"===typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},i.derToInteger=function(e){"string"===typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},i.validate=function(e,t,r,s){var o=!1;if(e.tagClass!==t.tagClass&&"undefined"!==typeof t.tagClass||e.type!==t.type&&"undefined"!==typeof t.type)s&&(e.tagClass!==t.tagClass&&s.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&s.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||"undefined"===typeof t.constructed){if(o=!0,t.value&&n.util.isArray(t.value))for(var a=0,c=0;o&&c0&&(s+="\n");for(var o="",c=0;c1?s+="0x"+n.util.bytesToHex(e.value.slice(1)):s+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?s+=" (1 unused bit shown)":d>1&&(s+=" ("+d+" unused bits shown)")}}else if(e.type===i.Type.OCTETSTRING)a.test(e.value)||(s+="("+e.value+") "),s+="0x"+n.util.bytesToHex(e.value);else if(e.type===i.Type.UTF8)try{s+=n.util.decodeUtf8(e.value)}catch(p){if("URI malformed"!==p.message)throw p;s+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===i.Type.PRINTABLESTRING||e.type===i.Type.IA5String?s+=e.value:a.test(e.value)?s+="0x"+n.util.bytesToHex(e.value):0===e.value.length?s+="[null]":s+=e.value}return s}},5754:e=>{var t={};e.exports=t;var r={};t.encode=function(e,t,r){if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!==typeof r)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var i=0,s=t.length,o=t.charAt(0),a=[0];for(i=0;i0;)a.push(l%s),l=l/s|0}for(i=0;0===e[i]&&i=0;--i)n+=t[a[i]]}else n=function(e,t){var r=0,n=t.length,i=t.charAt(0),s=[0];for(r=0;r0;)s.push(a%n),a=a/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[s[r]];return c}(e,t);if(r){var u=new RegExp(".{1,"+r+"}","g");n=n.match(u).join("\r\n")}return n},t.decode=function(e,t){if("string"!==typeof e)throw new TypeError('"input" must be a string.');if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');var n=r[t];if(!n){n=r[t]=[];for(var i=0;i>=8;for(;u>0;)a.push(255&u),u>>=8}for(var h=0;e[h]===o&&h{var n=r(392);r(3877),e.exports=n.cipher=n.cipher||{},n.cipher.algorithms=n.cipher.algorithms||{},n.cipher.createCipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})},n.cipher.createDecipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})},n.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),n.cipher.algorithms[e]=t},n.cipher.getAlgorithm=function(e){return(e=e.toUpperCase())in n.cipher.algorithms?n.cipher.algorithms[e]:null};var i=n.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};i.prototype.start=function(e){e=e||{};var t={};for(var r in e)t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=n.util.createBuffer(),this.output=e.output||n.util.createBuffer(),this.mode.start(t)},i.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},i.prototype.finish=function(e){!e||"ECB"!==this.mode.name&&"CBC"!==this.mode.name||(this.mode.pad=function(t){return e(this.blockSize,t,!1)},this.mode.unpad=function(t){return e(this.blockSize,t,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t))&&(this._finish=!0,this.update(),!(this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))&&!(this.mode.afterFinish&&!this.mode.afterFinish(this.output,t)))}},4533:(e,t,r)=>{var n=r(392);r(3877),n.cipher=n.cipher||{};var i=e.exports=n.cipher.modes=n.cipher.modes||{};function s(e,t){if("string"===typeof e&&(e=n.util.createBuffer(e)),n.util.isArray(e)&&e.length>4){var r=e;e=n.util.createBuffer();for(var i=0;i0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},i.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},i.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb.prototype.decrypt=i.ofb.prototype.encrypt,i.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}o(this._inBlock)},i.ctr.prototype.decrypt=i.ctr.prototype.encrypt,i.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},i.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var i=r.length();if(12===i)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(a(8*i)))}this._inBlock=this._j0.slice(0),o(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var s=t.length()%this.blockSize;for(s&&t.fillWithByte(0,this.blockSize-s),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},i.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),o(this._inBlock)},i.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),o(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},i.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,i=this._m[r][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},i.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},i.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,i=16*r,s=new Array(i),o=0;o>>1,i=new Array(r);i[n]=e.slice(0);for(var s=n>>>1;s>0;)this.pow(i[2*s],i[s]=[]),s>>=1;for(s=2;s{var n=r(392);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.des.Algorithm(e,t)}))}r(3397),r(4533),r(3877),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createEncryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!1,mode:t})},n.des.startDecrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createDecryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!0,mode:t})},n.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return f(r._keys,e,t,!1)},decrypt:function(e,t){return f(r._keys,e,t,!0)}}}),r._init=!1},n.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=n.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=function(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],s=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],p=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length()>8?3:1,m=[],v=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],w=0,b=0;b>>4^S))<<4,E^=t=65535&((S^=t)>>>-16^E),E^=(t=858993459&(E>>>2^(S^=t<<-16)))<<2,E^=t=65535&((S^=t)>>>-16^E),E^=(t=1431655765&(E>>>1^(S^=t<<-16)))<<1,E^=t=16711935&((S^=t)>>>8^E),t=(E^=(t=1431655765&(E>>>1^(S^=t<<8)))<<1)<<8|(S^=t)>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var _=0;_>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27),S&=-15;var I=r[(E&=-15)>>>28]|n[E>>>24&15]|i[E>>>20&15]|s[E>>>16&15]|o[E>>>12&15]|a[E>>>8&15]|c[E>>>4&15],A=l[S>>>28]|u[S>>>24&15]|h[S>>>20&15]|d[S>>>16&15]|f[S>>>12&15]|p[S>>>8&15]|g[S>>>4&15];t=65535&(A>>>16^I),m[w++]=I^t,m[w++]=A^t<<16}}return m}(t),this._init=!0}},i("DES-ECB",n.cipher.modes.ecb),i("DES-CBC",n.cipher.modes.cbc),i("DES-CFB",n.cipher.modes.cfb),i("DES-OFB",n.cipher.modes.ofb),i("DES-CTR",n.cipher.modes.ctr),i("3DES-ECB",n.cipher.modes.ecb),i("3DES-CBC",n.cipher.modes.cbc),i("3DES-CFB",n.cipher.modes.cfb),i("3DES-OFB",n.cipher.modes.ofb),i("3DES-CTR",n.cipher.modes.ctr);var s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],a=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],c=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],l=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],u=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],h=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],d=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function f(e,t,r,n){var i,f,p=32===e.length?3:9;i=3===p?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],y=t[1];g^=(f=252645135&(g>>>4^y))<<4,g^=(f=65535&(g>>>16^(y^=f)))<<16,g^=f=858993459&((y^=f)>>>2^g),g^=f=16711935&((y^=f<<2)>>>8^g),g=(g^=(f=1431655765&(g>>>1^(y^=f<<8)))<<1)<<1|g>>>31,y=(y^=f)<<1|y>>>31;for(var m=0;m>>4|y<<28)^e[b+1];f=g,g=y,y=f^(o[E>>>24&63]|c[E>>>16&63]|u[E>>>8&63]|d[63&E]|s[S>>>24&63]|a[S>>>16&63]|l[S>>>8&63]|h[63&S])}f=g,g=y,y=f}y=y>>>1|y<<31,y^=f=1431655765&((g=g>>>1|g<<31)>>>1^y),y^=(f=16711935&(y>>>8^(g^=f<<1)))<<8,y^=(f=858993459&(y>>>2^(g^=f)))<<2,y^=f=65535&((g^=f)>>>16^y),y^=f=252645135&((g^=f<<16)>>>4^y),g^=f<<4,r[0]=g,r[1]=y}function p(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var s=null;r instanceof n.util.ByteBuffer&&(s=r,r={}),(r=r||{}).output=s,r.iv=e,i.call(t,r)},t}},392:e=>{e.exports={options:{usePureJavaScript:!1}}},878:(e,t,r)=>{var n=r(392);r(29),r(3877),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,i=null,s={start:function(s,o){if(null!==s)if("string"===typeof s){if(!((s=s.toLowerCase())in n.md.algorithms))throw new Error('Unknown hash algorithm "'+s+'"');t=n.md.algorithms[s].create()}else t=s;if(null===o)o=e;else{if("string"===typeof o)o=n.util.createBuffer(o);else if(n.util.isArray(o)){var a=o;o=n.util.createBuffer();for(var c=0;ct.blockLength&&(t.start(),t.update(o.bytes()),o=t.digest()),r=n.util.createBuffer(),i=n.util.createBuffer(),l=o.length();for(c=0;c{var n,i=r(392);e.exports=i.jsbn=i.jsbn||{};function s(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function o(){return new s(null)}function a(e,t,r,n,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this.data[e],l=this.data[e++]>>14,u=a*c+l*o;i=((c=o*c+((16383&u)<<14)+r.data[n]+i)>>28)+(u>>14)+a*l,r.data[n++]=268435455&c}return i}i.jsbn.BigInteger=s,"undefined"===typeof navigator?(s.prototype.am=a,n=28):"Microsoft Internet Explorer"==navigator.appName?(s.prototype.am=function(e,t,r,n,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this.data[e],l=this.data[e++]>>15,u=a*c+l*o;i=((c=o*c+((32767&u)<<15)+r.data[n]+(1073741823&i))>>>30)+(u>>>15)+a*l+(i>>>30),r.data[n++]=1073741823&c}return i},n=30):"Netscape"!=navigator.appName?(s.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this.data[e++]+r.data[n]+i;i=Math.floor(o/67108864),r.data[n++]=67108863&o}return i},n=26):(s.prototype.am=a,n=28),s.prototype.DB=n,s.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function g(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function _(){}function I(e){return e}function A(e){this.r2=o(),this.q3=o(),s.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}g.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=o();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(s.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=o();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},s.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},s.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},s.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var a=8==r?255&e[n]:d(e,n);a<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==o?this.data[this.t++]=a:o+r>this.DB?(this.data[this.t-1]|=(a&(1<>this.DB-o):this.data[this.t-1]|=a<=this.DB&&(o-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},s.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},s.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+o+1]=this.data[r]>>i|a,a=(this.data[r]&s)<=0;--r)t.data[r]=0;t.data[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},s.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,s=(1<>n;for(var o=r+1;o>n;n>0&&(t.data[this.t-r-1]|=(this.s&s)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},s.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},s.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(u,a),i.lShiftTo(u,r)):(n.copyTo(a),i.copyTo(r));var h=a.t,d=a.data[h-1];if(0!=d){var f=d*(1<1?a.data[h-2]>>this.F2:0),g=this.FV/f,y=(1<=0&&(r.data[r.t++]=1,r.subTo(b,r)),s.ONE.dlShiftTo(h,b),b.subTo(a,a);a.t=0;){var E=r.data[--v]==d?this.DM:Math.floor(r.data[v]*g+(r.data[v-1]+m)*y);if((r.data[v]+=a.am(0,E,r,w,0,h))0&&r.rShiftTo(u,r),c<0&&s.ZERO.subTo(r,r)}}},s.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},s.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},s.prototype.exp=function(e,t){if(e>4294967295||e<1)return s.ONE;var r=o(),n=o(),i=t.convert(this),a=p(e)-1;for(i.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var c=r;r=n,n=c}return t.revert(r)},s.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,s=h(r));o>=0;)a>(a+=this.DB-t)):(r=this.data[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(i=!0),i&&(s+=h(r));return i?s:"0"},s.prototype.negate=function(){var e=o();return s.ZERO.subTo(this,e),e},s.prototype.abs=function(){return this.s<0?this.negate():this},s.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},s.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+p(this.data[this.t-1]^this.s&this.DM)},s.prototype.mod=function(e){var t=o();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(s.ZERO)>0&&e.subTo(t,t),t},s.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new g(t):new y(t),this.exp(e,r)},s.ZERO=f(0),s.ONE=f(1),_.prototype.convert=I,_.prototype.revert=I,_.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},_.prototype.sqrTo=function(e,t){e.squareTo(t)},A.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=o();return e.copyTo(t),this.reduce(t),t},A.prototype.revert=function(e){return e},A.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},A.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},A.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var C=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],T=(1<<26)/C[C.length-1];s.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},s.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=f(r),i=o(),s=o(),a="";for(this.divRemTo(n,i,s);i.signum()>0;)a=(r+s.intValue()).toString(e).substr(1)+a,i.divRemTo(n,i,s);return s.intValue().toString(e)+a},s.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,a=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(a,0)),i&&s.ZERO.subTo(this,this)},s.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(s.ONE.shiftLeft(e-1),v,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(s.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},s.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},s.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},s.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r.data[--i]=0;for(n=r.t-this.t;i=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r},s.prototype.millerRabin=function(e){var t=this.subtract(s.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,i=t.shiftRight(r),o={nextBytes:function(e){for(var t=0;t=0);var c=n.modPow(i,this);if(0!=c.compareTo(s.ONE)&&0!=c.compareTo(t)){for(var l=1;l++>24},s.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},s.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},s.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},s.prototype.equals=function(e){return 0==this.compareTo(e)},s.prototype.min=function(e){return this.compareTo(e)<0?this:e},s.prototype.max=function(e){return this.compareTo(e)>0?this:e},s.prototype.and=function(e){var t=o();return this.bitwiseTo(e,m,t),t},s.prototype.or=function(e){var t=o();return this.bitwiseTo(e,v,t),t},s.prototype.xor=function(e){var t=o();return this.bitwiseTo(e,w,t),t},s.prototype.andNot=function(e){var t=o();return this.bitwiseTo(e,b,t),t},s.prototype.not=function(){for(var e=o(),t=0;t=this.t?0!=this.s:0!=(this.data[t]&1<1){var h=o();for(n.sqrTo(a[1],h);c<=u;)a[c]=o(),n.mulTo(h,a[c-2],a[c]),c+=2}var d,m,v=e.t-1,w=!0,b=o();for(i=p(e.data[v])-1;v>=0;){for(i>=l?d=e.data[v]>>i-l&u:(d=(e.data[v]&(1<0&&(d|=e.data[v-1]>>this.DB+i-l)),c=r;0==(1&d);)d>>=1,--c;if((i-=c)<0&&(i+=this.DB,--v),w)a[d].copyTo(s),w=!1;else{for(;c>1;)n.sqrTo(s,b),n.sqrTo(b,s),c-=2;c>0?n.sqrTo(s,b):(m=s,s=b,b=m),n.mulTo(b,a[d],s)}for(;v>=0&&0==(e.data[v]&1<=0?(r.subTo(n,r),t&&i.subTo(a,i),o.subTo(c,o)):(n.subTo(r,n),t&&a.subTo(i,a),c.subTo(o,c))}return 0!=n.compareTo(s.ONE)?s.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},s.prototype.pow=function(e){return this.exp(e,new _)},s.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},s.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=C[C.length-1]){for(t=0;t{var n=r(392);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},1746:(e,t,r)=>{var n=r(392);r(7263),e.exports=n.mgf=n.mgf||{},n.mgf.mgf1=n.mgf1},7263:(e,t,r)=>{var n=r(392);r(3877),n.mgf=n.mgf||{},(e.exports=n.mgf.mgf1=n.mgf1=n.mgf1||{}).create=function(e){return{generate:function(t,r){for(var i=new n.util.ByteBuffer,s=Math.ceil(r/e.digestLength),o=0;o{var n=r(392);n.pki=n.pki||{};var i=e.exports=n.pki.oids=n.oids=n.oids||{};function s(e,t){i[e]=t,i[t]=e}function o(e,t){i[e]=t}s("1.2.840.113549.1.1.1","rsaEncryption"),s("1.2.840.113549.1.1.4","md5WithRSAEncryption"),s("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),s("1.2.840.113549.1.1.7","RSAES-OAEP"),s("1.2.840.113549.1.1.8","mgf1"),s("1.2.840.113549.1.1.9","pSpecified"),s("1.2.840.113549.1.1.10","RSASSA-PSS"),s("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),s("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),s("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),s("1.3.101.112","EdDSA25519"),s("1.2.840.10040.4.3","dsa-with-sha1"),s("1.3.14.3.2.7","desCBC"),s("1.3.14.3.2.26","sha1"),s("1.3.14.3.2.29","sha1WithRSASignature"),s("2.16.840.1.101.3.4.2.1","sha256"),s("2.16.840.1.101.3.4.2.2","sha384"),s("2.16.840.1.101.3.4.2.3","sha512"),s("2.16.840.1.101.3.4.2.4","sha224"),s("2.16.840.1.101.3.4.2.5","sha512-224"),s("2.16.840.1.101.3.4.2.6","sha512-256"),s("1.2.840.113549.2.2","md2"),s("1.2.840.113549.2.5","md5"),s("1.2.840.113549.1.7.1","data"),s("1.2.840.113549.1.7.2","signedData"),s("1.2.840.113549.1.7.3","envelopedData"),s("1.2.840.113549.1.7.4","signedAndEnvelopedData"),s("1.2.840.113549.1.7.5","digestedData"),s("1.2.840.113549.1.7.6","encryptedData"),s("1.2.840.113549.1.9.1","emailAddress"),s("1.2.840.113549.1.9.2","unstructuredName"),s("1.2.840.113549.1.9.3","contentType"),s("1.2.840.113549.1.9.4","messageDigest"),s("1.2.840.113549.1.9.5","signingTime"),s("1.2.840.113549.1.9.6","counterSignature"),s("1.2.840.113549.1.9.7","challengePassword"),s("1.2.840.113549.1.9.8","unstructuredAddress"),s("1.2.840.113549.1.9.14","extensionRequest"),s("1.2.840.113549.1.9.20","friendlyName"),s("1.2.840.113549.1.9.21","localKeyId"),s("1.2.840.113549.1.9.22.1","x509Certificate"),s("1.2.840.113549.1.12.10.1.1","keyBag"),s("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),s("1.2.840.113549.1.12.10.1.3","certBag"),s("1.2.840.113549.1.12.10.1.4","crlBag"),s("1.2.840.113549.1.12.10.1.5","secretBag"),s("1.2.840.113549.1.12.10.1.6","safeContentsBag"),s("1.2.840.113549.1.5.13","pkcs5PBES2"),s("1.2.840.113549.1.5.12","pkcs5PBKDF2"),s("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),s("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),s("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),s("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),s("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),s("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),s("1.2.840.113549.2.7","hmacWithSHA1"),s("1.2.840.113549.2.8","hmacWithSHA224"),s("1.2.840.113549.2.9","hmacWithSHA256"),s("1.2.840.113549.2.10","hmacWithSHA384"),s("1.2.840.113549.2.11","hmacWithSHA512"),s("1.2.840.113549.3.7","des-EDE3-CBC"),s("2.16.840.1.101.3.4.1.2","aes128-CBC"),s("2.16.840.1.101.3.4.1.22","aes192-CBC"),s("2.16.840.1.101.3.4.1.42","aes256-CBC"),s("2.5.4.3","commonName"),s("2.5.4.4","surname"),s("2.5.4.5","serialNumber"),s("2.5.4.6","countryName"),s("2.5.4.7","localityName"),s("2.5.4.8","stateOrProvinceName"),s("2.5.4.9","streetAddress"),s("2.5.4.10","organizationName"),s("2.5.4.11","organizationalUnitName"),s("2.5.4.12","title"),s("2.5.4.13","description"),s("2.5.4.15","businessCategory"),s("2.5.4.17","postalCode"),s("2.5.4.42","givenName"),s("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),s("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),s("2.16.840.1.113730.1.1","nsCertType"),s("2.16.840.1.113730.1.13","nsComment"),o("2.5.29.1","authorityKeyIdentifier"),o("2.5.29.2","keyAttributes"),o("2.5.29.3","certificatePolicies"),o("2.5.29.4","keyUsageRestriction"),o("2.5.29.5","policyMapping"),o("2.5.29.6","subtreesConstraint"),o("2.5.29.7","subjectAltName"),o("2.5.29.8","issuerAltName"),o("2.5.29.9","subjectDirectoryAttributes"),o("2.5.29.10","basicConstraints"),o("2.5.29.11","nameConstraints"),o("2.5.29.12","policyConstraints"),o("2.5.29.13","basicConstraints"),s("2.5.29.14","subjectKeyIdentifier"),s("2.5.29.15","keyUsage"),o("2.5.29.16","privateKeyUsagePeriod"),s("2.5.29.17","subjectAltName"),s("2.5.29.18","issuerAltName"),s("2.5.29.19","basicConstraints"),o("2.5.29.20","cRLNumber"),o("2.5.29.21","cRLReason"),o("2.5.29.22","expirationDate"),o("2.5.29.23","instructionCode"),o("2.5.29.24","invalidityDate"),o("2.5.29.25","cRLDistributionPoints"),o("2.5.29.26","issuingDistributionPoint"),o("2.5.29.27","deltaCRLIndicator"),o("2.5.29.28","issuingDistributionPoint"),o("2.5.29.29","certificateIssuer"),o("2.5.29.30","nameConstraints"),s("2.5.29.31","cRLDistributionPoints"),s("2.5.29.32","certificatePolicies"),o("2.5.29.33","policyMappings"),o("2.5.29.34","policyConstraints"),s("2.5.29.35","authorityKeyIdentifier"),o("2.5.29.36","policyConstraints"),s("2.5.29.37","extKeyUsage"),o("2.5.29.46","freshestCRL"),o("2.5.29.54","inhibitAnyPolicy"),s("1.3.6.1.4.1.11129.2.4.2","timestampList"),s("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),s("1.3.6.1.5.5.7.3.1","serverAuth"),s("1.3.6.1.5.5.7.3.2","clientAuth"),s("1.3.6.1.5.5.7.3.3","codeSigning"),s("1.3.6.1.5.5.7.3.4","emailProtection"),s("1.3.6.1.5.5.7.3.8","timeStamping")},9835:(e,t,r)=>{var n=r(392);if(r(8605),r(5049),r(1400),r(29),r(2886),r(6019),r(6193),r(3860),r(654),r(5493),r(3877),"undefined"===typeof i)var i=n.jsbn.BigInteger;var s=n.asn1,o=n.pki=n.pki||{};e.exports=o.pbe=n.pbe=n.pbe||{};var a=o.oids,c={name:"EncryptedPrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},l={name:"PBES2Algorithms",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},u={name:"pkcs-12PbeParams",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"iterations"}]};function h(e,t){return e.start().update(t).digest().getBytes()}function d(e){var t;if(e){if(!(t=o.oids[s.derToOid(e)])){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}}else t="hmacWithSHA1";return f(t)}function f(e){var t=n.md;switch(e){case"hmacWithSHA224":t=n.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}o.encryptPrivateKeyInfo=function(e,t,r){(r=r||{}).saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var i,c,l,u=n.random.getBytesSync(r.saltSize),h=r.count,d=s.integerToDer(h);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var p,g,y;switch(r.algorithm){case"aes128":i=16,p=16,g=a["aes128-CBC"],y=n.aes.createEncryptionCipher;break;case"aes192":i=24,p=16,g=a["aes192-CBC"],y=n.aes.createEncryptionCipher;break;case"aes256":i=32,p=16,g=a["aes256-CBC"],y=n.aes.createEncryptionCipher;break;case"des":i=8,p=8,g=a.desCBC,y=n.des.createEncryptionCipher;break;default:throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S}var m="hmacWith"+r.prfAlgorithm.toUpperCase(),v=f(m),w=n.pkcs5.pbkdf2(t,u,h,i,v),b=n.random.getBytesSync(p);(_=y(w)).start(b),_.update(s.toDer(e)),_.finish(),l=_.output.getBytes();var E=function(e,t,r,i){var a=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,e),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,t.getBytes())]);"hmacWithSHA1"!==i&&a.value.push(s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,n.util.hexToBytes(r.toString(16))),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(o.oids[i]).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]));return a}(u,d,i,m);c=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a.pkcs5PBES2).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a.pkcs5PBKDF2).getBytes()),E]),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(g).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,b)])])])}else{var S;if("3des"!==r.algorithm)throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S;i=24;var _,I=new n.util.ByteBuffer(u);w=o.pbe.generatePkcs12Key(t,I,1,h,i),b=o.pbe.generatePkcs12Key(t,I,2,h,i);(_=n.des.createEncryptionCipher(w)).start(b),_.update(s.toDer(e)),_.finish(),l=_.output.getBytes(),c=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,u),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,d.getBytes())])])}return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[c,s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,l)])},o.decryptPrivateKeyInfo=function(e,t){var r=null,i={},a=[];if(!s.validate(e,c,i,a)){var l=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=a,l}var u=s.derToOid(i.encryptionOid),h=o.pbe.getCipher(u,i.encryptionParams,t),d=n.util.createBuffer(i.encryptedData);return h.update(d),h.finish()&&(r=s.fromDer(h.output)),r},o.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:s.toDer(e).getBytes()};return n.pem.encode(r,{maxline:t})},o.encryptedPrivateKeyFromPem=function(e){var t=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==t.type){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return s.fromDer(t.body)},o.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var i=o.wrapRsaPrivateKey(o.privateKeyToAsn1(e));return i=o.encryptPrivateKeyInfo(i,t,r),o.encryptedPrivateKeyToPem(i)}var a,c,l,u;switch(r.algorithm){case"aes128":a="AES-128-CBC",l=16,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes192":a="AES-192-CBC",l=24,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes256":a="AES-256-CBC",l=32,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"3des":a="DES-EDE3-CBC",l=24,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;case"des":a="DES-CBC",l=8,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;default:var h=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw h.algorithm=r.algorithm,h}var d=u(n.pbe.opensslDeriveBytes(t,c.substr(0,8),l));d.start(c),d.update(s.toDer(o.privateKeyToAsn1(e))),d.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:a,parameters:n.util.bytesToHex(c).toUpperCase()},body:d.output.getBytes()};return n.pem.encode(f)},o.decryptRsaPrivateKey=function(e,t){var r=null,i=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==i.type&&"PRIVATE KEY"!==i.type&&"RSA PRIVATE KEY"!==i.type)throw(l=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=l,l;if(i.procType&&"ENCRYPTED"===i.procType.type){var a,c;switch(i.dekInfo.algorithm){case"DES-CBC":a=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":a=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":a=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var l;throw(l=new Error('Could not decrypt private key; unsupported encryption algorithm "'+i.dekInfo.algorithm+'".')).algorithm=i.dekInfo.algorithm,l}var u=n.util.hexToBytes(i.dekInfo.parameters),h=c(n.pbe.opensslDeriveBytes(t,u.substr(0,8),a));if(h.start(u),h.update(n.util.createBuffer(i.body)),!h.finish())return r;r=h.output.getBytes()}else r=i.body;return null!==(r="ENCRYPTED PRIVATE KEY"===i.type?o.decryptPrivateKeyInfo(s.fromDer(r),t):s.fromDer(r))&&(r=o.privateKeyFromAsn1(r)),r},o.pbe.generatePkcs12Key=function(e,t,r,i,s,o){var a,c;if("undefined"===typeof o||null===o){if(!("sha1"in n.md))throw new Error('"sha1" hash algorithm unavailable.');o=n.md.sha1.create()}var l=o.digestLength,u=o.blockLength,h=new n.util.ByteBuffer,d=new n.util.ByteBuffer;if(null!==e&&void 0!==e){for(c=0;c=0;c--)k>>=8,k+=A.at(c)+R.at(c),R.setAt(c,255&k);T.putBuffer(R)}b=T,h.putBuffer(_)}return h.truncate(h.length()-s),h},o.pbe.getCipher=function(e,t,r){switch(e){case o.oids.pkcs5PBES2:return o.pbe.getCipherForPBES2(e,t,r);case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case o.oids["pbewithSHAAnd40BitRC2-CBC"]:return o.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},o.pbe.getCipherForPBES2=function(e,t,r){var i,a={},c=[];if(!s.validate(t,l,a,c))throw(i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,i;if((e=s.derToOid(a.kdfOid))!==o.oids.pkcs5PBKDF2)throw(i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,i.supportedOids=["pkcs5PBKDF2"],i;if((e=s.derToOid(a.encOid))!==o.oids["aes128-CBC"]&&e!==o.oids["aes192-CBC"]&&e!==o.oids["aes256-CBC"]&&e!==o.oids["des-EDE3-CBC"]&&e!==o.oids.desCBC)throw(i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i;var u,h,f=a.kdfSalt,p=n.util.createBuffer(a.kdfIterationCount);switch(p=p.getInt(p.length()<<3),o.oids[e]){case"aes128-CBC":u=16,h=n.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,h=n.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,h=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,h=n.des.createDecryptionCipher;break;case"desCBC":u=8,h=n.des.createDecryptionCipher}var g=d(a.prfOid),y=n.pkcs5.pbkdf2(r,f,p,u,g),m=a.encIv,v=h(y);return v.start(m),v},o.pbe.getCipherForPKCS12PBE=function(e,t,r){var i={},a=[];if(!s.validate(t,u,i,a))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=a,g;var c,l,h,f=n.util.createBuffer(i.salt),p=n.util.createBuffer(i.iterations);switch(p=p.getInt(p.length()<<3),e){case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,l=8,h=n.des.startDecrypting;break;case o.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,l=8,h=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var y=d(i.prfOid),m=o.pbe.generatePkcs12Key(r,f,1,p,c,y);return y.start(),h(m,o.pbe.generatePkcs12Key(r,f,2,p,l,y))},o.pbe.opensslDeriveBytes=function(e,t,r,i){if("undefined"===typeof i||null===i){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');i=n.md.md5.create()}null===t&&(t="");for(var s=[h(i,e+t)],o=16,a=1;o{var n=r(392);r(878),r(29),r(3877);var i,s=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(i=r(5819)),e.exports=n.pbkdf2=s.pbkdf2=function(e,t,r,s,o,a){if("function"===typeof o&&(a=o,o=null),n.util.isNodejs&&!n.options.usePureJavaScript&&i.pbkdf2&&(null===o||"object"!==typeof o)&&(i.pbkdf2Sync.length>4||!o||"sha1"===o))return"string"!==typeof o&&(o="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),a?4===i.pbkdf2Sync.length?i.pbkdf2(e,t,r,s,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):i.pbkdf2(e,t,r,s,o,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):4===i.pbkdf2Sync.length?i.pbkdf2Sync(e,t,r,s).toString("binary"):i.pbkdf2Sync(e,t,r,s,o).toString("binary");if("undefined"!==typeof o&&null!==o||(o="sha1"),"string"===typeof o){if(!(o in n.md.algorithms))throw new Error("Unknown hash algorithm: "+o);o=n.md[o].create()}var c=o.digestLength;if(s>4294967295*c){var l=new Error("Derived key is too long.");if(a)return a(l);throw l}var u=Math.ceil(s/c),h=s-(u-1)*c,d=n.hmac.create();d.start(o,e);var f,p,g,y="";if(!a){for(var m=1;m<=u;++m){d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),f=g=d.digest().getBytes();for(var v=2;v<=r;++v)d.start(null,null),d.update(g),p=d.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p;y+=mu)return a(null,y);d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),f=g=d.digest().getBytes(),v=2,b()}function b(){if(v<=r)return d.start(null,null),d.update(g),p=d.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p,++v,n.util.setImmediate(b);y+=m{var n=r(392);r(3877);var i=e.exports=n.pem=n.pem||{};function s(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},i=0;i65&&-1!==o){var a=t[o];","===a?(++o,t=t.substr(0,o)+"\r\n "+t.substr(o)):t=t.substr(0,o)+"\r\n"+a+t.substr(o+1),s=i-o-1,o=-1,++i}else" "!==t[i]&&"\t"!==t[i]&&","!==t[i]||(o=i);return t}function o(e){return e.replace(/^\s+/,"")}i.encode=function(e,t){t=t||{};var r,i="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(i+=s(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(i+=s(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),i+=s(r)),e.headers)for(var o=0;o{var n=r(392);r(3877),r(3860),r(928);var i=e.exports=n.pkcs1=n.pkcs1||{};function s(e,t,r){r||(r=n.md.sha1.create());for(var i="",s=Math.ceil(t/r.digestLength),o=0;o>24&255,o>>16&255,o>>8&255,255&o);r.start(),r.update(e+a),i+=r.digest().getBytes()}return i.substring(0,t)}i.encode_rsa_oaep=function(e,t,r){var i,o,a,c;"string"===typeof r?(i=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(i=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),c||(c=a);var l=Math.ceil(e.n.bitLength()/8),u=l-2*a.digestLength-2;if(t.length>u)throw(y=new Error("RSAES-OAEP input message length is too long.")).length=t.length,y.maxLength=u,y;i||(i=""),a.update(i,"raw");for(var h=a.digest(),d="",f=u-t.length,p=0;p{var n=r(392);r(8605),r(5049),r(1400),r(2886),r(6193),r(4922),r(3860),r(3877),r(3391);var i=n.asn1,s=e.exports=n.pkcs7=n.pkcs7||{};function o(e){var t={},r=[];if(!i.validate(e,s.asn1.recipientInfoValidator,t,r)){var o=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw o.errors=r,o}return{version:t.version.charCodeAt(0),issuer:n.pki.RDNAttributesAsArray(t.issuer),serialNumber:n.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:i.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function a(e){for(var t,r=[],s=0;s0){for(var r=i.create(i.Class.CONTEXT_SPECIFIC,1,!0,[]),s=0;s=r&&o0&&o.value[0].value.push(i.create(i.Class.CONTEXT_SPECIFIC,0,!0,t)),s.length>0&&o.value[0].value.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,s)),o.value[0].value.push(i.create(i.Class.UNIVERSAL,i.Type.SET,!0,e.signerInfos)),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.type).getBytes()),o])},addSigner:function(t){var r=t.issuer,i=t.serialNumber;if(t.certificate){var s=t.certificate;"string"===typeof s&&(s=n.pki.certificateFromPem(s)),r=s.issuer.attributes,i=s.serialNumber}var o=t.key;if(!o)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"===typeof o&&(o=n.pki.privateKeyFromPem(o));var a=t.digestAlgorithm||n.pki.oids.sha1;switch(a){case n.pki.oids.sha1:case n.pki.oids.sha256:case n.pki.oids.sha384:case n.pki.oids.sha512:case n.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+a)}var c=t.authenticatedAttributes||[];if(c.length>0){for(var l=!1,u=!1,h=0;h{var n=r(392);r(5049),r(3877);var i=n.asn1,s=e.exports=n.pkcs7asn1=n.pkcs7asn1||{};n.pkcs7=n.pkcs7||{},n.pkcs7.asn1=s;var o={name:"ContentInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};s.contentInfoValidator=o;var a={name:"EncryptedContentInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};s.envelopedDataValidator={name:"EnvelopedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(a)},s.encryptedDataValidator={name:"EncryptedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"}].concat(a)};var c={name:"SignerInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};s.signedDataValidator={name:"SignedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},o,{name:"SignedData.Certificates",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,capture:"signerInfos",optional:!0,value:[c]}]},s.recipientInfoValidator={name:"RecipientInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},5132:(e,t,r)=>{var n=r(392);r(3877),r(3055),r(3860),function(){if(n.prime)e.exports=n.prime;else{var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,i=[6,4,2,4,2,4,6,2],s=new r(null);s.fromInt(30);var o=function(e,t){return e|t};t.generateProbablePrime=function(e,t,i){"function"===typeof t&&(i=t,t={});var s=(t=t||{}).algorithm||"PRIMEINC";"string"===typeof s&&(s={name:s}),s.options=s.options||{};var o=t.prng||n.random,c={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;re&&(o=l(e,t));var f=o.toString(16);i.target.postMessage({hex:f,workLoad:u}),o.dAddOffset(h,0)}}}f()}(e,t,i,s);return a(e,t,i,s)}(e,c,s.options,i);throw new Error("Invalid prime generation algorithm: "+s.name)}}function a(e,t,r,n){var i=l(e,t),s=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(i.bitLength());"millerRabinTests"in r&&(s=r.millerRabinTests);var o=10;"maxBlockTime"in r&&(o=r.maxBlockTime),c(i,e,t,0,s,o,n)}function c(e,t,r,s,o,a,u){var h=+new Date;do{if(e.bitLength()>t&&(e=l(t,r)),e.isProbablePrime(o))return u(null,e);e.dAddOffset(i[s++%8],0)}while(a<0||+new Date-h{var n=r(392);r(3877);var i=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(i=r(5819)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,s=new Array(32),o=0;o<32;++o)s[o]=r.create();function a(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r===0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var i=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(i),t.generated=0}function l(e){var t=null,r=n.util.globalScope,i=r.crypto||r.msCrypto;i&&i.getRandomValues&&(t=function(e){return i.getRandomValues(e)});var s=n.util.createBuffer();if(t)for(;s.length()>16)))<<16,d=4294967295&(u=(2147483647&(u+=l>>15))+(u>>31));for(c=0;c<3;++c)h=d>>>(c<<3),h^=Math.floor(256*Math.random()),s.putByte(255&h)}return s.getBytes(e)}return t.pools=s,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var i=t.plugin.cipher,s=t.plugin.increment,o=t.plugin.formatKey,a=t.plugin.formatSeed,l=n.util.createBuffer();t.key=null,function u(h){if(h)return r(h);if(l.length()>=e)return r(null,l.getBytes(e));t.generated>1048575&&(t.key=null);if(null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(u)}));var d=i(t.key,t.seed);t.generated+=d.length,l.putBytes(d),t.key=o(i(t.key,s(t.seed))),t.seed=a(i(t.key,t.seed)),n.util.setImmediate(u)}()},t.generateSync=function(e){var r=t.plugin.cipher,i=t.plugin.increment,s=t.plugin.formatKey,o=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&a();var l=r(t.key,t.seed);t.generated+=l.length,c.putBytes(l),t.key=s(r(t.key,i(t.seed))),t.seed=o(r(t.key,t.seed))}return c.getBytes(e)},i?(t.seedFile=function(e,t){i.randomBytes(e,(function(e,r){if(e)return t(e);t(null,r.toString())}))},t.seedFileSync=function(e){return i.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,l(e))}catch(r){t(r)}},t.seedFileSync=l),t.collect=function(e){for(var r=e.length,n=0;n>i&255);t.collect(n)},t.registerWorker=function(e){if(e===self)t.seedFile=function(e,t){self.addEventListener("message",(function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))})),self.postMessage({forge:{prng:{needed:e}}})};else{e.addEventListener("message",(function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,(function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})}))}))}},t}},325:(e,t,r)=>{var n=r(392);r(3860),r(3877),(e.exports=n.pss=n.pss||{}).create=function(e){3===arguments.length&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t,r=e.md,i=e.mgf,s=r.digestLength,o=e.salt||null;if("string"===typeof o&&(o=n.util.createBuffer(o)),"saltLength"in e)t=e.saltLength;else{if(null===o)throw new Error("Salt length not specified or specific salt not given.");t=o.length()}if(null!==o&&o.length()!==t)throw new Error("Given salt length does not match length of given salt.");var a=e.prng||n.random,c={encode:function(e,c){var l,u,h=c-1,d=Math.ceil(h/8),f=e.digest().getBytes();if(d>8*d-h&255;return(b=String.fromCharCode(b.charCodeAt(0)&~E)+b.substr(1))+g+String.fromCharCode(188)},verify:function(e,o,a){var c,l=a-1,u=Math.ceil(l/8);if(o=o.substr(-u),u>8*u-l&255;if(0!==(d.charCodeAt(0)&p))throw new Error("Bits beyond keysize not zero as expected.");var g=i.generate(f,h),y="";for(c=0;c{var n=r(392);r(8605),r(7404),r(6140),r(3877),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},i=new Array(4),s=n.util.createBuffer();function o(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,i,!1),s.putInt32(i[0]),s.putInt32(i[1]),s.putInt32(i[2]),s.putInt32(i[3]),s.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=o(),c=null,l=n.util.globalScope,u=l.crypto||l.msCrypto;if(u&&u.getRandomValues&&(c=function(e){return u.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){if("undefined"===typeof window||window.document,a.collectInt(+new Date,32),"undefined"!==typeof navigator){var h="";for(var d in navigator)try{"string"==typeof navigator[d]&&(h+=navigator[d])}catch(f){}a.collect(h),h=null}t&&(t().mousemove((function(e){a.collectInt(e.clientX,16),a.collectInt(e.clientY,16)})),t().keypress((function(e){a.collectInt(e.charCode,8)})))}if(n.random)for(var d in a)n.random[d]=a[d];else n.random=a;n.random.createInstance=o,e.exports=n.random}("undefined"!==typeof jQuery?jQuery:null)},654:(e,t,r)=>{var n=r(392);r(3877);var i=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],s=[1,2,3,5],o=function(e,t){return e<>16-t},a=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"===typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,s=e,o=e.length(),a=t,c=Math.ceil(a/8),l=255>>(7&a);for(r=o;r<128;r++)s.putByte(i[s.at(r-1)+s.at(r-o)&255]);for(s.setAt(128-c,i[s.at(128-c)&l]),r=127-c;r>=0;r--)s.setAt(r,i[s.at(r+1)^s.at(r+c)]);return s};var c=function(e,t,r){var i,c,l,u,h=!1,d=null,f=null,p=null,g=[];for(e=n.rc2.expandKey(e,t),l=0;l<64;l++)g.push(e.getInt16Le());r?(i=function(e){for(l=0;l<4;l++)e[l]+=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),e[l]=o(e[l],s[l]),u++},c=function(e){for(l=0;l<4;l++)e[l]+=g[63&e[(l+3)%4]]}):(i=function(e){for(l=3;l>=0;l--)e[l]=a(e[l],s[l]),e[l]-=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),u--},c=function(e){for(l=3;l>=0;l--)e[l]-=g[63&e[(l+3)%4]]});var y=function(e){var t=[];for(l=0;l<4;l++){var n=d.getInt16Le();null!==p&&(r?n^=p.getInt16Le():p.putInt16Le(n)),t.push(65535&n)}u=r?0:63;for(var i=0;i=8;)y([[5,i],[1,c],[6,i],[1,c],[5,i]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,d,!r);else{var n=8===d.length()?8:8-d.length();d.fillWithByte(n,n)}if(t&&(h=!0,m.update()),!r&&(t=0===d.length()))if(e)t=e(8,f,!r);else{var i=f.length(),s=f.at(i-1);s>i?t=!1:f.truncate(s)}return t}}};n.rc2.startEncrypting=function(e,t,r){var i=n.rc2.createEncryptionCipher(e,128);return i.start(t,r),i},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var i=n.rc2.createDecryptionCipher(e,128);return i.start(t,r),i},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},5493:(e,t,r)=>{var n=r(392);if(r(5049),r(3055),r(2886),r(2627),r(5132),r(3860),r(3877),"undefined"===typeof i)var i=n.jsbn.BigInteger;var s=n.util.isNodejs?r(5819):null,o=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,l=[6,4,2,4,2,4,6,2],u={name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},h={name:"RSAPrivateKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},d={name:"RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},f=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},p={name:"DigestInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:o.Class.UNIVERSAL,type:o.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=o.oidToDer(t).getBytes(),i=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]),s=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]);s.value.push(o.create(o.Class.UNIVERSAL,o.Type.OID,!1,n)),s.value.push(o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,""));var a=o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(s),i.value.push(a),o.toDer(i).getBytes()},y=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var s;t.dP||(t.dP=t.d.mod(t.p.subtract(i.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(i.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{s=new i(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(s.compareTo(t.n)>=0||!s.gcd(t.n).equals(i.ONE));for(var o=(e=e.multiply(s.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);o.compareTo(a)<0;)o=o.add(t.p);var c=o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return c=c.multiply(s.modInverse(t.n)).mod(t.n)};function m(e,t,r){var i=n.util.createBuffer(),s=Math.ceil(t.n.bitLength()/8);if(e.length>s-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=s-11,o}i.putByte(0),i.putByte(r);var a,c=s-3-e.length;if(0===r||1===r){a=0===r?0:255;for(var l=0;l0;){var u=0,h=n.random.getBytes(c);for(l=0;l1;){if(255!==o.getByte()){--o.read;break}++l}else if(2===c)for(l=0;o.length()>1;){if(0===o.getByte()){--o.read;break}++l}if(0!==o.getByte()||l!==s-3-o.length())throw new Error("Encryption block is invalid.");return o.getBytes()}function w(e,t,r){"function"===typeof t&&(r=t,t={});var s={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function o(){a(e.pBits,(function(t,n){return t?r(t):(e.p=n,null!==e.q?l(t,e.q):void a(e.qBits,l))}))}function a(e,t){n.prime.generateProbablePrime(e,s,t)}function l(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var s=e.p;e.p=e.q,e.q=s}if(0!==e.p.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.p=null,void o();if(0!==e.q.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.q=null,void a(e.qBits,l);if(e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(i.ONE))return e.p=e.q=null,void o();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,l);var u=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(s.prng=t.prng),o()}function b(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0===(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128===(128&r.charCodeAt(1)))?r.substr(1):r}function E(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function S(e){return n.util.isNodejs&&"function"===typeof s[e]}function _(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.crypto&&"object"===typeof a.globalScope.crypto.subtle&&"function"===typeof a.globalScope.crypto.subtle[e]}function I(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.msCrypto&&"object"===typeof a.globalScope.msCrypto.subtle&&"function"===typeof a.globalScope.msCrypto.subtle[e]}function A(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),i=0;i0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),u.getBytes()},c.rsa.decrypt=function(e,t,r,s){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var c=new i(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var l=y(c,t,r).toString(16),u=n.util.createBuffer(),h=o-Math.ceil(l.length/2);h>0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),!1!==s?v(u.getBytes(),t,r):u.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"===typeof e&&(e=parseInt(e,10)),e=e||2048;var s,o=(r=r||{}).prng||n.random,a={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(s.eInt),s},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new i(null);r.fromInt(30);for(var n,s=0,o=function(e,t){return e|t},a=+new Date,u=0;null===e.keys&&(t<=0||uh?e.pqState=0:e.num.isProbablePrime(E(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(l[s++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(i.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var f=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}u+=(n=+new Date)-a,a=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,i){if(1===arguments.length?"object"===typeof e?(r=e,e=void 0):"function"===typeof e&&(i=e,e=void 0):2===arguments.length?"number"===typeof e?"function"===typeof t?(i=t,t=void 0):"number"!==typeof t&&(r=t,t=void 0):(r=e,i=t,e=void 0,t=void 0):3===arguments.length&&("number"===typeof t?"function"===typeof r&&(i=r,r=void 0):(i=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(i){if(S("generateKeyPair"))return s.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return i(e);i(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(_("generateKey")&&_("exportKey"))return a.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then((function(e){return a.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)})).then(void 0,(function(e){i(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(e)));i(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(I("generateKey")&&I("exportKey")){var l=a.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return l.oncomplete=function(e){var t=e.target.result,r=a.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(t)));i(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){i(e)}},void(l.onerror=function(e){i(e)})}}else if(S("generateKeyPairSync")){var u=s.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(u.privateKey),publicKey:c.publicKeyFromPem(u.publicKey)}}var h=c.rsa.createKeyPairGenerationState(e,t,r);if(!i)return c.rsa.stepKeyPairGenerationState(h,0),h.keys;w(h,r,i)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,i){if("string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return m(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,i)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"===typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var s=t.encode(e,r,!0);return c.rsa.encrypt(s,r,!0)},verify:function(e,t,i,s){"string"===typeof i?i=i.toUpperCase():void 0===i&&(i="RSASSA-PKCS1-V1_5"),void 0===s&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===i?i={verify:function(e,t){t=v(t,r,!0);var i=o.fromDer(t,{parseAllBytes:s._parseAllDigestBytes}),a={},c=[];if(!o.validate(i,p,a,c))throw(l=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,l;var l,u=o.derToOid(a.algorithmIdentifier);if(u!==n.oids.md2&&u!==n.oids.md5&&u!==n.oids.sha1&&u!==n.oids.sha224&&u!==n.oids.sha256&&u!==n.oids.sha384&&u!==n.oids.sha512&&u!==n.oids["sha512-224"]&&u!==n.oids["sha512-256"])throw(l=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=u,l;if((u===n.oids.md2||u===n.oids.md5)&&!("parameters"in a))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return e===a.digest}}:"NONE"!==i&&"NULL"!==i&&null!==i||(i={verify:function(e,t){return e===(t=v(t,r,!0))}});var a=c.rsa.decrypt(t,r,!0,!1);return i.verify(e,a,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,i,s,o,a,l){var u={n:e,e:t,d:r,p:i,q:s,dP:o,dQ:a,qInv:l,decrypt:function(e,t,r){"string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var i=c.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:v};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(i,u,!1)},sign:function(e,t){var r=!1;"string"===typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var n=t.encode(e,u.n.bitLength());return c.rsa.encrypt(n,u,r)}};return u},c.wrapRsaPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,o.toDer(e).getBytes())])},c.privateKeyFromAsn1=function(e){var t,r,s,a,l,d,f,p,g={},y=[];if(o.validate(e,u,g,y)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},y=[],!o.validate(e,h,g,y)){var m=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw m.errors=y,m}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),s=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),l=n.util.createBuffer(g.privateKeyPrime2).toHex(),d=n.util.createBuffer(g.privateKeyExponent1).toHex(),f=n.util.createBuffer(g.privateKeyExponent2).toHex(),p=n.util.createBuffer(g.privateKeyCoefficient).toHex(),c.setRsaPrivateKey(new i(t,16),new i(r,16),new i(s,16),new i(a,16),new i(l,16),new i(d,16),new i(f,16),new i(p,16))},c.privateKeyToAsn1=c.privateKeyToRSAPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.e)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.d)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.p)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.q)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.dP)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.dQ)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.qInv))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(o.validate(e,f,t,r)){var s,a=o.derToOid(t.publicKeyOid);if(a!==c.oids.rsaEncryption)throw(s=new Error("Cannot read public key. Unknown OID.")).oid=a,s;e=t.rsaPublicKey}if(r=[],!o.validate(e,d,t,r))throw(s=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,s;var l=n.util.createBuffer(t.publicKeyModulus).toHex(),u=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new i(l,16),new i(u,16))},c.publicKeyToAsn1=c.publicKeyToSubjectPublicKeyInfo=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.publicKeyToRSAPublicKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.e))])}},928:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=i,i.create=function(){o||(s=String.fromCharCode(128),s+=n.util.fillString(String.fromCharCode(0),64),o=!0);var e=null,t=n.util.createBuffer(),r=new Array(80),i={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s>>0,c>>>0];for(var l=i.fullMessageLength.length-1;l>=0;--l)i.fullMessageLength[l]+=c[1],c[1]=c[0]+(i.fullMessageLength[l]/4294967296>>>0),i.fullMessageLength[l]=i.fullMessageLength[l]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(s),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var c,l=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;o.putBytes(s.substr(0,i.blockLength-l));for(var u=8*i.fullMessageLength[0],h=0;h>>0,o.putInt32(u>>>0),u=c>>>0;o.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,o);var f=n.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f},i};var s=null,o=!1;function a(e,t,r){for(var n,i,s,o,a,c,l,u=r.length();u>=64;){for(i=e.h0,s=e.h1,o=e.h2,a=e.h3,c=e.h4,l=0;l<16;++l)n=r.getInt32(),t[l]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<20;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<32;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(i<<5|i>>>27)+(s^o^a)+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<40;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(s^o^a)+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<60;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(s&o|a&(s^o))+c+2400959708+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<80;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(s^o^a)+c+3395469782+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+o|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,u-=64}}},7404:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=i,i.create=function(){o||(s=String.fromCharCode(128),s+=n.util.fillString(String.fromCharCode(0),64),a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],o=!0);var e=null,t=n.util.createBuffer(),r=new Array(64),i={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s>>0,a>>>0];for(var l=i.fullMessageLength.length-1;l>=0;--l)i.fullMessageLength[l]+=a[1],a[1]=a[0]+(i.fullMessageLength[l]/4294967296>>>0),i.fullMessageLength[l]=i.fullMessageLength[l]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(s),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var a,l=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;o.putBytes(s.substr(0,i.blockLength-l));for(var u=8*i.fullMessageLength[0],h=0;h>>0,o.putInt32(u>>>0),u=a>>>0;o.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};c(d,r,o);var f=n.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f.putInt32(d.h5),f.putInt32(d.h6),f.putInt32(d.h7),f},i};var s=null,o=!1,a=null;function c(e,t,r){for(var n,i,s,o,c,l,u,h,d,f,p,g,y,m=r.length();m>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=((i=t[c-15])>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[c]=n+t[c-7]+i+t[c-16]|0;for(l=e.h0,u=e.h1,h=e.h2,d=e.h3,f=e.h4,p=e.h5,g=e.h6,y=e.h7,c=0;c<64;++c)s=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),o=l&u|h&(l^u),n=y+((f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7))+(g^f&(p^g))+a[c]+t[c],y=g,g=p,p=f,f=d+n>>>0,d=h,h=u,u=l,l=n+(i=s+o)>>>0;e.h0=e.h0+l|0,e.h1=e.h1+u|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+f|0,e.h5=e.h5+p|0,e.h6=e.h6+g|0,e.h7=e.h7+y|0,m-=64}}},4770:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=i;var s=n.sha384=n.sha512.sha384=n.sha512.sha384||{};s.create=function(){return i.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=s,n.sha512.sha256=n.sha512.sha256||{create:function(){return i.create("SHA-512/256")}},n.md["sha512/256"]=n.md.algorithms["sha512/256"]=n.sha512.sha256,n.sha512.sha224=n.sha512.sha224||{create:function(){return i.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,i.create=function(e){if(a||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),128),c=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],(l={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],l["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],l["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],l["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],a=!0),"undefined"===typeof e&&(e="SHA-512"),!(e in l))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=l[e],r=null,i=n.util.createBuffer(),s=new Array(80),h=0;h<80;++h)s[h]=new Array(2);var d=64;switch(e){case"SHA-384":d=48;break;case"SHA-512/256":d=32;break;case"SHA-512/224":d=28}var f={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:d,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){f.messageLength=0,f.fullMessageLength=f.messageLength128=[];for(var e=f.messageLengthSize/4,s=0;s>>0,o>>>0];for(var a=f.fullMessageLength.length-1;a>=0;--a)f.fullMessageLength[a]+=o[1],o[1]=o[0]+(f.fullMessageLength[a]/4294967296>>>0),f.fullMessageLength[a]=f.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return i.putBytes(e),u(r,s,i),(i.read>2048||0===i.length())&&i.compact(),f},f.digest=function(){var t=n.util.createBuffer();t.putBytes(i.bytes());var a,c=f.fullMessageLength[f.fullMessageLength.length-1]+f.messageLengthSize&f.blockLength-1;t.putBytes(o.substr(0,f.blockLength-c));for(var l=8*f.fullMessageLength[0],h=0;h>>0,t.putInt32(l>>>0),l=a>>>0;t.putInt32(l);var d=new Array(r.length);for(h=0;h=128;){for(P=0;P<16;++P)t[P][0]=r.getInt32()>>>0,t[P][1]=r.getInt32()>>>0;for(;P<80;++P)n=(((D=(O=t[P-2])[0])>>>19|(N=O[1])<<13)^(N>>>29|D<<3)^D>>>6)>>>0,i=((D<<13|N>>>19)^(N<<3|D>>>29)^(D<<26|N>>>6))>>>0,s=(((D=(B=t[P-15])[0])>>>1|(N=B[1])<<31)^(D>>>8|N<<24)^D>>>7)>>>0,o=((D<<31|N>>>1)^(D<<24|N>>>8)^(D<<25|N>>>7))>>>0,L=t[P-7],x=t[P-16],N=i+L[1]+o+x[1],t[P][0]=n+L[0]+s+x[0]+(N/4294967296>>>0)>>>0,t[P][1]=N>>>0;for(p=e[0][0],g=e[0][1],y=e[1][0],m=e[1][1],v=e[2][0],w=e[2][1],b=e[3][0],E=e[3][1],S=e[4][0],_=e[4][1],I=e[5][0],A=e[5][1],C=e[6][0],T=e[6][1],R=e[7][0],k=e[7][1],P=0;P<80;++P)u=((S>>>14|_<<18)^(S>>>18|_<<14)^(_>>>9|S<<23))>>>0,h=(C^S&(I^C))>>>0,a=((p>>>28|g<<4)^(g>>>2|p<<30)^(g>>>7|p<<25))>>>0,l=((p<<4|g>>>28)^(g<<30|p>>>2)^(g<<25|p>>>7))>>>0,d=(p&y|v&(p^y))>>>0,f=(g&m|w&(g^m))>>>0,N=k+(((S<<18|_>>>14)^(S<<14|_>>>18)^(_<<23|S>>>9))>>>0)+((T^_&(A^T))>>>0)+c[P][1]+t[P][1],n=R+u+h+c[P][0]+t[P][0]+(N/4294967296>>>0)>>>0,i=N>>>0,s=a+d+((N=l+f)/4294967296>>>0)>>>0,o=N>>>0,R=C,k=T,C=I,T=A,I=S,A=_,S=b+n+((N=E+i)/4294967296>>>0)>>>0,_=N>>>0,b=v,E=w,v=y,w=m,y=p,m=g,p=n+s+((N=i+o)/4294967296>>>0)>>>0,g=N>>>0;N=e[0][1]+g,e[0][0]=e[0][0]+p+(N/4294967296>>>0)>>>0,e[0][1]=N>>>0,N=e[1][1]+m,e[1][0]=e[1][0]+y+(N/4294967296>>>0)>>>0,e[1][1]=N>>>0,N=e[2][1]+w,e[2][0]=e[2][0]+v+(N/4294967296>>>0)>>>0,e[2][1]=N>>>0,N=e[3][1]+E,e[3][0]=e[3][0]+b+(N/4294967296>>>0)>>>0,e[3][1]=N>>>0,N=e[4][1]+_,e[4][0]=e[4][0]+S+(N/4294967296>>>0)>>>0,e[4][1]=N>>>0,N=e[5][1]+A,e[5][0]=e[5][0]+I+(N/4294967296>>>0)>>>0,e[5][1]=N>>>0,N=e[6][1]+T,e[6][0]=e[6][0]+C+(N/4294967296>>>0)>>>0,e[6][1]=N>>>0,N=e[7][1]+k,e[7][0]=e[7][0]+R+(N/4294967296>>>0)>>>0,e[7][1]=N>>>0,M-=128}}},3877:(e,t,r)=>{var n=r(392),i=r(5754),s=e.exports=n.util=n.util||{};function o(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"===typeof e)this.data=e;else if(s.isArrayBuffer(e)||s.isArrayBufferView(e))if("undefined"!==typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(n){for(var r=0;r15?(r=Date.now(),o(e)):(t.push(e),1===t.length&&i.setAttribute("a",n=!n))}}s.nextTick=s.setImmediate}(),s.isNodejs="undefined"!==typeof process&&process.versions&&process.versions.node,s.globalScope=s.isNodejs?r.g:"undefined"===typeof self?window:self,s.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},s.isArrayBuffer=function(e){return"undefined"!==typeof ArrayBuffer&&e instanceof ArrayBuffer},s.isArrayBufferView=function(e){return e&&s.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},s.ByteBuffer=a,s.ByteStringBuffer=a;s.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},s.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},s.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},s.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},s.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},s.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},s.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(s.encodeUtf8(e))},s.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},s.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},s.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},s.ByteStringBuffer.prototype.putInt=function(e,t){o(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},s.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},s.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},s.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},s.ByteStringBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},s.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},s.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},s.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},s.ByteStringBuffer.prototype.copy=function(){var e=s.createBuffer(this.data);return e.read=this.read,e},s.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},s.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},s.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},s.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},s.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},s.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},s.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},s.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},s.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},s.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},s.DataBuffer.prototype.putInt=function(e,t){o(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},s.DataBuffer.prototype.putSignedInt=function(e,t){return o(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},s.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},s.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},s.DataBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},s.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},s.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},s.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},s.DataBuffer.prototype.copy=function(){return new s.DataBuffer(this)},s.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},s.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},s.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},s.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},s.xorBytes=function(e,t,r){for(var n="",i="",s="",o=0,a=0;r>0;--r,++o)i=e.charCodeAt(o)^t.charCodeAt(o),a>=10&&(n+=s,s="",a=0),s+=String.fromCharCode(i),++a;return n+=s},s.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],u="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";s.encode64=function(e,t){for(var r,n,i,s="",o="",a=0;a>2),s+=c.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":(s+=c.charAt((15&n)<<2|i>>6),s+=isNaN(i)?"=":c.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+=s},s.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,i,s="",o=0;o>4),64!==n&&(s+=String.fromCharCode((15&r)<<4|n>>2),64!==i&&(s+=String.fromCharCode((3&n)<<6|i)));return s},s.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},s.decodeUtf8=function(e){return decodeURIComponent(escape(e))},s.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:i.encode,decode:i.decode}},s.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},s.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s>2),s+=c.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":(s+=c.charAt((15&n)<<2|i>>6),s+=isNaN(i)?"=":c.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+=s},s.binary.base64.decode=function(e,t,r){var n,i,s,o,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,u=r=r||0;c>4,64!==s&&(a[u++]=(15&i)<<4|s>>2,64!==o&&(a[u++]=(3&s)<<6|o));return t?u-r:a.subarray(0,u)},s.binary.base58.encode=function(e,t){return s.binary.baseN.encode(e,u,t)},s.binary.base58.decode=function(e,t){return s.binary.baseN.decode(e,u,t)},s.text={utf8:{},utf16:{}},s.text.utf8.encode=function(e,t,r){e=s.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,o=0;o0&&s.push(r),o=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":s.push("%");break;default:s.push("<%"+a+"?>")}}return s.push(e.substring(o)),s.join("")},s.formatNumber=function(e,t,r,n){var i=e,s=isNaN(t=Math.abs(t))?2:t,o=void 0===r?",":r,a=void 0===n?".":n,c=i<0?"-":"",l=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",u=l.length>3?l.length%3:0;return c+(u?l.substr(0,u)+a:"")+l.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+a)+(s?o+Math.abs(i-l).toFixed(s).slice(2):"")},s.formatSize=function(e){return e=e>=1073741824?s.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?s.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?s.formatNumber(e/1024,0)+" KiB":s.formatNumber(e,0)+" bytes"},s.bytesFromIP=function(e){return-1!==e.indexOf(".")?s.bytesFromIPv4(e):-1!==e.indexOf(":")?s.bytesFromIPv6(e):null},s.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=s.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(o)}if(r.length>0){var l=r[n];l.end-l.start>0&&(t.splice(l.start,l.end-l.start+1,""),0===l.start&&t.unshift(""),7===l.end&&t.push(""))}return t.join(":")},s.estimateCores=function(e,t){if("function"===typeof e&&(t=e,e={}),e=e||{},"cores"in s&&!e.update)return t(null,s.cores);if("undefined"!==typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return s.cores=navigator.hardwareConcurrency,t(null,s.cores);if("undefined"===typeof Worker)return s.cores=1,t(null,s.cores);if("undefined"===typeof Blob)return s.cores=2,t(null,s.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()a.st&&i.sti.st&&a.st{var n=r(392);r(8605),r(5049),r(1400),r(29),r(1746),r(2886),r(6193),r(325),r(5493),r(3877);var i=n.asn1,s=e.exports=n.pki=n.pki||{},o=s.oids,a={};a.CN=o.commonName,a.commonName="CN",a.C=o.countryName,a.countryName="C",a.L=o.localityName,a.localityName="L",a.ST=o.stateOrProvinceName,a.stateOrProvinceName="ST",a.O=o.organizationName,a.organizationName="O",a.OU=o.organizationalUnitName,a.organizationalUnitName="OU",a.E=o.emailAddress,a.emailAddress="E";var c=n.pki.rsa.publicKeyValidator,l={name:"Certificate",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:i.Class.UNIVERSAL,type:i.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:i.Class.UNIVERSAL,type:i.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:i.Class.UNIVERSAL,type:i.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:i.Class.UNIVERSAL,type:i.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},c,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:i.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:i.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},u={name:"rsapss",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:i.Class.UNIVERSAL,type:i.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:i.Class.UNIVERSAL,type:i.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:i.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:i.Class.UNIVERSAL,type:i.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:i.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:i.Class.UNIVERSAL,type:i.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},h={name:"CertificationRequestInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},c,{name:"CertificationRequestInfo.attributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0}]}]}]},d={name:"CertificationRequest",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[h,{name:"CertificationRequest.signatureAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};function f(e,t){"string"===typeof t&&(t={shortName:t});for(var r,n=null,i=0;null===n&&i128)throw new Error('Invalid "nsComment" content.');e.value=i.create(i.Class.UNIVERSAL,i.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&t.cert){var f=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=f.toHex(),e.value=i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,f.getBytes())}else if("authorityKeyIdentifier"===e.name&&t.cert){e.value=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);u=e.value.value;if(e.keyIdentifier){var p=!0===e.keyIdentifier?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;u.push(i.create(i.Class.CONTEXT_SPECIFIC,0,!1,p))}if(e.authorityCertIssuer){var g=[i.create(i.Class.CONTEXT_SPECIFIC,4,!0,[m(!0===e.authorityCertIssuer?t.cert.issuer:e.authorityCertIssuer)])];u.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,g))}if(e.serialNumber){var y=n.util.hexToBytes(!0===e.serialNumber?t.cert.serialNumber:e.serialNumber);u.push(i.create(i.Class.CONTEXT_SPECIFIC,2,!1,y))}}else if("cRLDistributionPoints"===e.name){e.value=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);u=e.value.value;var v,w=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]),b=i.create(i.Class.CONTEXT_SPECIFIC,0,!0,[]);for(d=0;d2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(h.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(c.validity.notBefore=h[0],c.validity.notAfter=h[1],c.tbsCertificate=r.tbsCertificate,t){c.md=g({signatureOid:c.signatureOid,type:"certificate"});var d=i.toDer(c.tbsCertificate);c.md.update(d.getBytes())}var y=n.md.sha1.create(),m=i.toDer(r.certIssuer);y.update(m.getBytes()),c.issuer.getField=function(e){return f(c.issuer,e)},c.issuer.addField=function(e){v([e]),c.issuer.attributes.push(e)},c.issuer.attributes=s.RDNAttributesAsArray(r.certIssuer),r.certIssuerUniqueId&&(c.issuer.uniqueId=r.certIssuerUniqueId),c.issuer.hash=y.digest().toHex();var w=n.md.sha1.create(),b=i.toDer(r.certSubject);return w.update(b.getBytes()),c.subject.getField=function(e){return f(c.subject,e)},c.subject.addField=function(e){v([e]),c.subject.attributes.push(e)},c.subject.attributes=s.RDNAttributesAsArray(r.certSubject),r.certSubjectUniqueId&&(c.subject.uniqueId=r.certSubjectUniqueId),c.subject.hash=w.digest().toHex(),r.certExtensions?c.extensions=s.certificateExtensionsFromAsn1(r.certExtensions):c.extensions=[],c.publicKey=s.publicKeyFromAsn1(r.subjectPublicKeyInfo),c},s.certificateExtensionsFromAsn1=function(e){for(var t=[],r=0;r1&&(r=c.value.charCodeAt(1),s=c.value.length>2?c.value.charCodeAt(2):0),t.digitalSignature=128===(128&r),t.nonRepudiation=64===(64&r),t.keyEncipherment=32===(32&r),t.dataEncipherment=16===(16&r),t.keyAgreement=8===(8&r),t.keyCertSign=4===(4&r),t.cRLSign=2===(2&r),t.encipherOnly=1===(1&r),t.decipherOnly=128===(128&s)}else if("basicConstraints"===t.name){(c=i.fromDer(t.value)).value.length>0&&c.value[0].type===i.Type.BOOLEAN?t.cA=0!==c.value[0].value.charCodeAt(0):t.cA=!1;var a=null;c.value.length>0&&c.value[0].type===i.Type.INTEGER?a=c.value[0].value:c.value.length>1&&(a=c.value[1].value),null!==a&&(t.pathLenConstraint=i.derToInteger(a))}else if("extKeyUsage"===t.name)for(var c=i.fromDer(t.value),l=0;l1&&(r=c.value.charCodeAt(1)),t.client=128===(128&r),t.server=64===(64&r),t.email=32===(32&r),t.objsign=16===(16&r),t.reserved=8===(8&r),t.sslCA=4===(4&r),t.emailCA=2===(2&r),t.objCA=1===(1&r)}else if("subjectAltName"===t.name||"issuerAltName"===t.name){var h;t.altNames=[];c=i.fromDer(t.value);for(var d=0;d=S&&e<_?i.create(i.Class.UNIVERSAL,i.Type.UTCTIME,!1,i.dateToUtcTime(e)):i.create(i.Class.UNIVERSAL,i.Type.GENERALIZEDTIME,!1,i.dateToGeneralizedTime(e))}s.getTBSCertificate=function(e){var t=I(e.validity.notBefore),r=I(e.validity.notAfter),o=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.CONTEXT_SPECIFIC,0,!0,[i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,i.integerToDer(e.version).getBytes())]),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,n.util.hexToBytes(e.serialNumber)),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.siginfo.algorithmOid).getBytes()),b(e.siginfo.algorithmOid,e.siginfo.parameters)]),m(e.issuer),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[t,r]),m(e.subject),s.publicKeyToAsn1(e.publicKey)]);return e.issuer.uniqueId&&o.value.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,[i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)])),e.subject.uniqueId&&o.value.push(i.create(i.Class.CONTEXT_SPECIFIC,2,!0,[i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.subject.uniqueId)])),e.extensions.length>0&&o.value.push(s.certificateExtensionsToAsn1(e.extensions)),o},s.getCertificationRequestInfo=function(e){return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,i.integerToDer(e.version).getBytes()),m(e.subject),s.publicKeyToAsn1(e.publicKey),E(e)])},s.distinguishedNameToAsn1=function(e){return m(e)},s.certificateToAsn1=function(e){var t=e.tbsCertificate||s.getTBSCertificate(e);return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[t,i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.signatureOid).getBytes()),b(e.signatureOid,e.signatureParameters)]),i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},s.certificateExtensionsToAsn1=function(e){var t=i.create(i.Class.CONTEXT_SPECIFIC,3,!0,[]),r=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);t.value.push(r);for(var n=0;nu.validity.notAfter)&&(c={message:"Certificate is not valid yet or has expired.",error:s.certificateError.certificate_expired,notBefore:u.validity.notBefore,notAfter:u.validity.notAfter,now:o}),null===c){if(null===(h=t[0]||e.getIssuer(u))&&u.isIssuer(u)&&(d=!0,h=u),h){var f=h;n.util.isArray(f)||(f=[f]);for(var p=!1;!p&&f.length>0;){h=f.shift();try{p=h.verify(u)}catch(S){}}p||(c={message:"Certificate signature is invalid.",error:s.certificateError.bad_certificate})}null!==c||h&&!d||e.hasCertificate(u)||(c={message:"Certificate is not trusted.",error:s.certificateError.unknown_ca})}if(null===c&&h&&!u.isIssuer(h)&&(c={message:"Certificate issuer is invalid.",error:s.certificateError.bad_certificate}),null===c)for(var g={keyUsage:!0,basicConstraints:!0},y=0;null===c&&yv.pathLenConstraint&&(c={message:"Certificate basicConstraints pathLenConstraint violated.",error:s.certificateError.bad_certificate})}var b=null===c||c.error,E=r.verify?r.verify(b,l,i):b;if(!0!==E)throw!0===b&&(c={message:"The application rejected the certificate.",error:s.certificateError.bad_certificate}),(E||0===E)&&("object"!==typeof E||n.util.isArray(E)?"string"===typeof E&&(c.error=E):(E.message&&(c.message=E.message),E.error&&(c.error=E.error))),c;c=null,a=!1,++l}while(t.length>0);return!0}},9879:(e,t,r)=>{const n=r(5125),i=r(2673);e.exports=class{constructor(){this._buffer=new n,this._waitingConsumers=new n}push(e){const{promise:t,resolve:r}=i();return this._buffer.push({chunk:e,resolve:r}),this._consume(),t}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){const e=this._waitingConsumers.shift(),t=this._buffer.shift();e.resolve(t.chunk),t.resolve()}}shift(){const{promise:e,resolve:t}=i();return this._waitingConsumers.push({resolve:t}),this._consume(),e}isEmpty(){return this._buffer.isEmpty()}}},2673:e=>{"use strict";e.exports=()=>{const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}},3931:(e,t,r)=>{"use strict";e.exports=r(3794).default},3794:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(7922),s=n(r(8974)),o=n(r(2795)),a=r(7201),c=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new i.Netmask(e)));function l(e){return/^::$/.test(e)||/^::1$/.test(e)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}t.default=e=>{if((0,a.isValid)(e)){const t=(0,a.parse)(e);if("ipv4"===t.kind())return function(e){for(let t of c)if(t.contains(e))return!0;return!1}(t.toNormalizedString());if("ipv6"===t.kind())return l(e)}else if((0,o.default)(e)&&s.default.v6().test(e))return l(e)}},5368:(e,t,r)=>{"use strict";e.exports=r(8154)},1427:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},7276:(e,t,r)=>{"use strict";var n=t,i=r(222),s=r(2440);function o(e,t,r,n){if(t.resolvedType)if(t.resolvedType instanceof i){e("switch(d%s){",n);for(var s=t.resolvedType.values,o=Object.keys(s),a=0;a>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":c=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,c)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,c?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof i?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var s=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,s?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=s.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n{"use strict";e.exports=function(e){var t=s.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter((function(e){return e.map})).length?",k,value":""))("while(r.pos>>3){");for(var r=0;r>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===i.basic[c]?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",c),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==i.long[a.keyType]?t('%s[typeof k==="object"?util.longToHash(k):k]=value',l):t("%s[k]=value",l)):a.repeated?(t("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==i.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos{"use strict";e.exports=function(e){for(var t,r=s.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(s.compareFieldsById),c=0;c>>0,8|i.mapKey[l.keyType],l.keyType),void 0===d?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==i.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?o(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?o(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(222),i=r(8517),s=r(2440);function o(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},222:(e,t,r)=>{"use strict";e.exports=o;var n=r(5154);((o.prototype=Object.create(n.prototype)).constructor=o).className="Enum";var i=r(3452),s=r(2440);function o(e,t,r,i,s,o){if(n.call(this,e,r),t&&"object"!==typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=i,this.comments=s||{},this.valuesOptions=o,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c{"use strict";e.exports=l;var n=r(5154);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var i,s=r(222),o=r(8517),a=r(2440),c=/^required|optional|repeated$/;function l(e,t,r,i,s,l,u){if(a.isObject(i)?(u=s,l=i,i=s=void 0):a.isObject(s)&&(u=l,l=s,s=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==i&&!c.test(i=i.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==s&&!a.isString(s))throw TypeError("extend must be a string");"proto3_optional"===i&&(i="optional"),this.rule=i&&"optional"!==i?i:void 0,this.type=r,this.id=t,this.extend=s||void 0,this.required="required"===i,this.optional=!this.required,this.repeated="repeated"===i,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==o.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=o.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof i?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"===typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof s)||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"===typeof this.typeDefault){var e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof i&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.d=function(e,t,r,n){return"function"===typeof t?t=a.decorateType(t).name:t&&"object"===typeof t&&(t=a.decorateEnum(t).name),function(i,s){a.decorateType(i.constructor).add(new l(s,e,t,r,{default:n}))}},l._configure=function(e){i=e}},4582:(e,t,r)=>{"use strict";var n=e.exports=r(4722);n.build="light",n.load=function(e,t,r){return"function"===typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(6886),n.decoder=r(2715),n.verifier=r(709),n.converter=r(7276),n.ReflectionObject=r(5154),n.Namespace=r(3452),n.Root=r(8622),n.Enum=r(222),n.Type=r(8716),n.Field=r(6734),n.OneOf=r(9794),n.MapField=r(4479),n.Service=r(4173),n.Method=r(4865),n.Message=r(4486),n.wrappers=r(9025),n.types=r(8517),n.util=r(2440),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},4722:(e,t,r)=>{"use strict";var n=t;function i(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(7063),n.BufferWriter=r(2815),n.Reader=r(6216),n.BufferReader=r(3557),n.util=r(3097),n.rpc=r(9994),n.roots=r(7907),n.configure=i,i()},8154:(e,t,r)=>{"use strict";var n=e.exports=r(4582);n.build="full",n.tokenize=r(3077),n.parse=r(7781),n.common=r(1427),n.Root._configure(n.Type,n.parse,n.common)},4479:(e,t,r)=>{"use strict";e.exports=o;var n=r(6734);((o.prototype=Object.create(n.prototype)).constructor=o).className="MapField";var i=r(8517),s=r(2440);function o(e,t,r,i,o,a){if(n.call(this,e,t,i,void 0,void 0,o,a),!s.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}o.fromJSON=function(e,t){return new o(e,t.id,t.keyType,t.type,t.options,t.comment)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===i.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},o.d=function(e,t,r){return"function"===typeof r?r=s.decorateType(r).name:r&&"object"===typeof r&&(r=s.decorateEnum(r).name),function(n,i){s.decorateType(n.constructor).add(new o(i,e,t,r))}}},4486:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e){if(e)for(var t=Object.keys(e),r=0;r{"use strict";e.exports=s;var n=r(5154);((s.prototype=Object.create(n.prototype)).constructor=s).className="Method";var i=r(2440);function s(e,t,r,s,o,a,c,l,u){if(i.isObject(o)?(c=o,o=a=void 0):i.isObject(a)&&(c=a,a=void 0),void 0!==t&&!i.isString(t))throw TypeError("type must be a string");if(!i.isString(r))throw TypeError("requestType must be a string");if(!i.isString(s))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!o||void 0,this.responseType=s,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}s.fromJSON=function(e,t){return new s(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},s.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},3452:(e,t,r)=>{"use strict";e.exports=h;var n=r(5154);((h.prototype=Object.create(n.prototype)).constructor=h).className="Namespace";var i,s,o,a=r(6734),c=r(2440),l=r(9794);function u(e,t){if(e&&e.length){for(var r={},n=0;nt)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r0;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof h))throw Error("path conflicts with non-namespace objects")}else r.add(r=new h(n))}return t&&r.addJSON(t),r},h.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t-1)return n}else if(n instanceof h&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var i=0;i{"use strict";e.exports=s,s.className="ReflectionObject";var n,i=r(2440);function s(e,t){if(!i.isString(e))throw TypeError("name must be a string");if(t&&!i.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(s.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),s.prototype.toJSON=function(){throw Error()},s.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof n&&t._handleAdd(this)},s.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},s.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},s.prototype.getOption=function(e){if(this.options)return this.options[e]},s.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},s.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var s=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(s){var o=s[e];i.setProperty(o,r,t)}else(s={})[e]=i.setProperty({},r,t),n.push(s)}else{var a={};a[e]=t,n.push(a)}return this},s.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n{"use strict";e.exports=o;var n=r(5154);((o.prototype=Object.create(n.prototype)).constructor=o).className="OneOf";var i=r(6734),s=r(2440);function o(e,t,r,i){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=i}function a(e){if(e.parent)for(var t=0;t-1&&this.oneof.splice(t,1),e.partOf=null,this},o.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t{"use strict";e.exports=I,I.filename=null,I.defaults={keepCase:!1};var n=r(3077),i=r(8622),s=r(8716),o=r(6734),a=r(4479),c=r(9794),l=r(222),u=r(4173),h=r(4865),d=r(8517),f=r(2440),p=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,m=/^-?0[x][0-9a-fA-F]+$/,v=/^0[0-7]+$/,w=/^-?0[0-7]+$/,b=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,_=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function I(e,t,r){t instanceof i||(r=t,t=new i),r||(r=I.defaults);var A,C,T,R,k,P=r.preferTrailingComment||!1,D=n(e,r.alternateCommentMode||!1),N=D.next,O=D.push,L=D.peek,B=D.skip,x=D.cmnt,M=!0,U=!1,F=t,V=r.keepCase?function(e){return e}:f.camelCase;function K(e,t,r){var n=I.filename;return r||(I.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+D.line+")")}function j(){var e,t=[];do{if('"'!==(e=N())&&"'"!==e)throw K(e);t.push(N()),B(e),e=L()}while('"'===e||"'"===e);return t.join("")}function z(e){var t=N();switch(t){case"'":case'"':return O(t),j();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e,t){var r=1;"-"===e.charAt(0)&&(r=-1,e=e.substring(1));switch(e){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(p.test(e))return r*parseInt(e,10);if(y.test(e))return r*parseInt(e,16);if(v.test(e))return r*parseInt(e,8);if(b.test(e))return r*parseFloat(e);throw K(e,"number",t)}(t,!0)}catch(r){if(e&&S.test(t))return t;throw K(t,"value")}}function q(e,t){var r,n;do{!t||'"'!==(r=L())&&"'"!==r?e.push([n=H(N()),B("to",!0)?H(N()):n]):e.push(j())}while(B(",",!0));B(";")}function H(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw K(e,"id");if(g.test(e))return parseInt(e,10);if(m.test(e))return parseInt(e,16);if(w.test(e))return parseInt(e,8);throw K(e,"id")}function G(){if(void 0!==A)throw K("package");if(A=N(),!S.test(A))throw K(A,"name");F=F.define(A),B(";")}function W(){var e,t=L();switch(t){case"weak":e=T||(T=[]),N();break;case"public":N();default:e=C||(C=[])}t=j(),B(";"),e.push(t)}function Q(){if(B("="),R=j(),!(U="proto3"===R)&&"proto2"!==R)throw K(R,"syntax");B(";")}function Y(e,t){switch(t){case"option":return ee(e,t),B(";"),!0;case"message":return X(e,t),!0;case"enum":return Z(e,t),!0;case"service":return function(e,t){if(!E.test(t=N()))throw K(t,"service name");var r=new u(t);$(r,(function(e){if(!Y(r,e)){if("rpc"!==e)throw K(e);!function(e,t){var r=x(),n=t;if(!E.test(t=N()))throw K(t,"name");var i,s,o,a,c=t;B("("),B("stream",!0)&&(s=!0);if(!S.test(t=N()))throw K(t);i=t,B(")"),B("returns"),B("("),B("stream",!0)&&(a=!0);if(!S.test(t=N()))throw K(t);o=t,B(")");var l=new h(c,n,i,o,s,a);l.comment=r,$(l,(function(e){if("option"!==e)throw K(e);ee(l,e),B(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=N()))throw K(t,"reference");var r=t;$(null,(function(t){switch(t){case"required":case"repeated":J(e,t,r);break;case"optional":J(e,U?"proto3_optional":"optional",r);break;default:if(!U||!S.test(t))throw K(t);O(t),J(e,"optional",r)}}))}(e,t),!0}return!1}function $(e,t,r){var n=D.line;if(e&&("string"!==typeof e.comment&&(e.comment=x()),e.filename=I.filename),B("{",!0)){for(var i;"}"!==(i=N());)t(i);B(";",!0)}else r&&r(),B(";"),e&&("string"!==typeof e.comment||P)&&(e.comment=x(n)||e.comment)}function X(e,t){if(!E.test(t=N()))throw K(t,"type name");var r=new s(t);$(r,(function(e){if(!Y(r,e))switch(e){case"map":!function(e){B("<");var t=N();if(void 0===d.mapKey[t])throw K(t,"type");B(",");var r=N();if(!S.test(r))throw K(r,"type");B(">");var n=N();if(!E.test(n))throw K(n,"name");B("=");var i=new a(V(n),H(N()),t,r);$(i,(function(e){if("option"!==e)throw K(e);ee(i,e),B(";")}),(function(){ne(i)})),e.add(i)}(r);break;case"required":case"repeated":J(r,e);break;case"optional":J(r,U?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=N()))throw K(t,"name");var r=new c(V(t));$(r,(function(e){"option"===e?(ee(r,e),B(";")):(O(e),J(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":q(r.extensions||(r.extensions=[]));break;case"reserved":q(r.reserved||(r.reserved=[]),!0);break;default:if(!U||!S.test(e))throw K(e);O(e),J(r,"optional")}})),e.add(r)}function J(e,t,r){var n=N();if("group"!==n){if(!S.test(n))throw K(n,"type");var i=N();if(!E.test(i))throw K(i,"name");i=V(i),B("=");var a=new o(i,H(N()),n,t,r);if($(a,(function(e){if("option"!==e)throw K(e);ee(a,e),B(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+i);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);U||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=N();if(!E.test(r))throw K(r,"name");var n=f.lcFirst(r);r===n&&(r=f.ucFirst(r));B("=");var i=H(N()),a=new s(r);a.group=!0;var c=new o(n,i,r,t);c.filename=I.filename,$(a,(function(e){switch(e){case"option":ee(a,e),B(";");break;case"required":case"repeated":J(a,e);break;case"optional":J(a,U?"proto3_optional":"optional");break;case"message":X(a,e);break;case"enum":Z(a,e);break;default:throw K(e)}})),e.add(a).add(c)}(e,t)}function Z(e,t){if(!E.test(t=N()))throw K(t,"name");var r=new l(t);$(r,(function(e){switch(e){case"option":ee(r,e),B(";");break;case"reserved":q(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw K(t,"name");B("=");var r=H(N(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};$(n,(function(e){if("option"!==e)throw K(e);ee(n,e),B(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=B("(",!0);if(!S.test(t=N()))throw K(t,"name");var n,i=t,s=i;r&&(B(")"),s=i="("+i+")",t=L(),_.test(t)&&(n=t.slice(1),i+=t,N())),B("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,s,te(e,i),n)}function te(e,t){if(B("{",!0)){for(var r={};!B("}",!0);){if(!E.test(k=N()))throw K(k,"name");var n,i=k;if(B(":",!0),"{"===L())n=te(e,t+"."+k);else if("["===L()){var s;if(n=[],B("[",!0)){do{s=z(!0),n.push(s)}while(B(",",!0));B("]"),"undefined"!==typeof s&&re(e,t+"."+k,s)}}else n=z(!0),re(e,t+"."+k,n);var o=r[i];o&&(n=[].concat(o).concat(n)),r[i]=n,B(",",!0),B(";",!0)}return r}var a=z(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(B("[",!0)){do{ee(e,"option")}while(B(",",!0));B("]")}return e}for(;null!==(k=N());)switch(k){case"package":if(!M)throw K(k);G();break;case"import":if(!M)throw K(k);W();break;case"syntax":if(!M)throw K(k);Q();break;case"option":ee(F,k),B(";");break;default:if(Y(F,k)){M=!1;continue}throw K(k)}return I.filename=null,{package:A,imports:C,weakImports:T,syntax:R,root:t}}},6216:(e,t,r)=>{"use strict";e.exports=c;var n,i=r(3097),s=i.LongBits,o=i.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l="undefined"!==typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},u=function(){return i.Buffer?function(e){return(c.create=function(e){return i.Buffer.isBuffer(e)?new n(e):l(e)})(e)}:l};function h(){var e=new s(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new s(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}c.create=u(),c.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return e}}(),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return d(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|d(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?new this.buf.constructor(0):this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length)},c.prototype.skip=function(e){if("number"===typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!==(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=u(),n._configure();var t=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return h.call(this)[t](!1)},uint64:function(){return h.call(this)[t](!0)},sint64:function(){return h.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},3557:(e,t,r)=>{"use strict";e.exports=s;var n=r(6216);(s.prototype=Object.create(n.prototype)).constructor=s;var i=r(3097);function s(e){n.call(this,e)}s._configure=function(){i.Buffer&&(s.prototype._slice=i.Buffer.prototype.slice)},s.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},s._configure()},8622:(e,t,r)=>{"use strict";e.exports=h;var n=r(3452);((h.prototype=Object.create(n.prototype)).constructor=h).className="Root";var i,s,o,a=r(6734),c=r(222),l=r(9794),u=r(2440);function h(e){n.call(this,"",e),this.deferred=[],this.files=[]}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"===typeof r&&(n=r,r=void 0);var i=this;if(!n)return u.asPromise(e,i,t,r);var a=n===d;function c(e,t){if(n){var r=n;if(n=null,a)throw e;r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in o)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){s.filename=e;var n,o=s(t,i,r),h=0;if(o.imports)for(;h-1))if(i.files.push(e),e in o)a?h(e,o[e]):(++p,setTimeout((function(){--p,h(e,o[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(s){return void(t||c(s))}h(e,r)}else++p,i.fetch(e,(function(r,s){--p,n&&(r?t?p||c(null,i):c(r):h(e,s))}))}var p=0;u.isString(t)&&(t=[t]);for(var g,y=0;y-1&&this.deferred.splice(t,1)}}else if(e instanceof c)f.test(e.name)&&delete e.parent[e.name];else if(e instanceof n){for(var r=0;r{"use strict";e.exports={}},9994:(e,t,r)=>{"use strict";t.Service=r(4281)},4281:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e,t,r){if("function"!==typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function e(t,r,i,s,o){if(!s)throw TypeError("request must be specified");var a=this;if(!o)return n.asPromise(e,a,t,r,i,s);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](s).finish(),(function(e,r){if(e)return a.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof i))try{r=i[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),o(e)}return a.emit("data",r,t),o(null,r)}a.end(!0)}))}catch(c){return a.emit("error",c,t),void setTimeout((function(){o(c)}),0)}else setTimeout((function(){o(Error("already ended"))}),0)},i.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},4173:(e,t,r)=>{"use strict";e.exports=a;var n=r(3452);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var i=r(4865),s=r(2440),o=r(9994);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),s=0;s{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,i=/^ *[*/]+ */,s=/^\s*\*?\/*/,o=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,f=0,p={},g=[],y=null;function m(e){return Error("illegal "+e+" (line "+d+")")}function v(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(o),g=0;g0)return g.shift();if(y)return function(){var t="'"===y?n:r;t.lastIndex=l-1;var i=t.exec(e);if(!i)throw m("string");return l=t.lastIndex,_(y),y=null,u(i[1])}();var i,s,o,f,p,S=0===l;do{if(l===h)return null;for(i=!1;a.test(o=v(l));)if("\n"===o&&(S=!0,++d),++l===h)return null;if("/"===v(l)){if(++l===h)throw m("comment");if("/"===v(l))if(c){if(f=l,p=!1,b(l)){p=!0;do{if((l=E(l))===h)break;if(l++,!S)break}while(b(l))}else l=Math.min(h,E(l)+1);p&&(w(f,l,S),S=!0),d++,i=!0}else{for(p="/"===v(f=l+1);"\n"!==v(++l);)if(l===h)return null;++l,p&&(w(f,l-1,S),S=!0),++d,i=!0}else{if("*"!==(o=v(l)))return"/";f=l+1,p=c||"*"===v(f);do{if("\n"===o&&++d,++l===h)throw m("comment");s=o,o=v(l)}while("*"!==s||"/"!==o);++l,p&&(w(f,l-2,S),S=!0),i=!0}}}while(i);var I=l;if(t.lastIndex=0,!t.test(v(I++)))for(;I{"use strict";e.exports=v;var n=r(3452);((v.prototype=Object.create(n.prototype)).constructor=v).className="Type";var i=r(222),s=r(9794),o=r(6734),a=r(4479),c=r(4173),l=r(4486),u=r(6216),h=r(7063),d=r(2440),f=r(6886),p=r(2715),g=r(709),y=r(7276),m=r(9025);function v(e,t){n.call(this,e,t),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function w(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(v.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t{"use strict";var n=t,i=r(2440),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function o(e,t){var r=0,n={};for(t|=0;r{"use strict";var n,i,s=e.exports=r(3097),o=r(7907);s.codegen=r(3297),s.fetch=r(7635),s.path=r(7468),s.fs=s.inquire("fs"),s.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n0)t[i]=e(t[i]||{},r,n);else{var s=t[i];s&&(n=[].concat(s).concat(n)),t[i]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(s,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(r(8622)))}})},9351:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var s=i.zero=new i(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var o=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(e){if(0===e)return s;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new i(r,n)},i.from=function(e){if("number"===typeof e)return i.fromNumber(e);if(n.isString(e)){if(!n.Long)return i.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):s},i.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;i.fromHash=function(e){return e===o?s:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},3097:function(e,t,r){"use strict";var n=t;function i(e,t,r){for(var n=Object.keys(t),i=0;ie,set:void 0,enumerable:!1,configurable:!0},toString:{value(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}n.asPromise=r(7206),n.base64=r(1),n.EventEmitter=r(7111),n.float=r(802),n.inquire=r(7172),n.utf8=r(3861),n.pool=r(8236),n.LongBits=r(9351),n.isNode=Boolean("undefined"!==typeof r.g&&r.g&&r.g.process&&r.g.process.versions&&r.g.process.versions.node),n.global=n.isNode&&r.g||"undefined"!==typeof window&&window||"undefined"!==typeof self&&self||this,n.emptyArray=Object.freeze?Object.freeze([]):[],n.emptyObject=Object.freeze?Object.freeze({}):{},n.isInteger=Number.isInteger||function(e){return"number"===typeof e&&isFinite(e)&&Math.floor(e)===e},n.isString=function(e){return"string"===typeof e||e instanceof String},n.isObject=function(e){return e&&"object"===typeof e},n.isset=n.isSet=function(e,t){var r=e[t];return!(null==r||!e.hasOwnProperty(t))&&("object"!==typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"===typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"===typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!==typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=i,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=s,n.ProtocolError=s("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r{"use strict";e.exports=function(e){var t=i.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r=e.oneofsArray,n={};r.length&&t("var p={}");for(var c=0;c{"use strict";var n=t,i=r(4486);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var s=this.lookup(n);s&&(e=s.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof i){var o=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),o["@type"]=n,o}return this.toObject(e,t)}}},7063:(e,t,r)=>{"use strict";e.exports=h;var n,i=r(3097),s=i.LongBits,o=i.base64,a=i.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return i.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function f(e,t,r){t[r]=255&e}function p(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function y(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},p.prototype=Object.create(c.prototype),p.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,s.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=s.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=s.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(f,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(y,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=s.from(e);return this._push(y,4,t.lo)._push(y,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(i.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(i.float.writeDoubleLE,8,e)};var m=i.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(f,1,0);if(i.isString(e)){var r=h.alloc(t=o.length(e));o.decode(e,r,0),e=r}return this.uint32(t)._push(m,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(f,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},2815:(e,t,r)=>{"use strict";e.exports=s;var n=r(7063);(s.prototype=Object.create(n.prototype)).constructor=s;var i=r(3097);function s(){n.call(this)}function o(e,t,r){e.length<40?i.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}s._configure=function(){s.alloc=i._Buffer_allocUnsafe,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(s.writeBytesBuffer,t,e),this},s.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},s._configure()},4463:(e,t,r)=>{"use strict";var n=r(2791),i=r(5296);function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r
= it.Source | (() => it.Source) | it.Duplex\nexport type Transform = it.Transform | it.Duplex\nexport type Sink = it.Sink | it.Duplex\n\nexport function pipe (\n first: Source\n): it.Source\n\nexport function pipe (\n first: Source,\n second: Sink\n): B\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Sink\n): C\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Sink\n): D\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Sink\n): E\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Sink\n): F\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Sink\n): G\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Sink\n): H\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Sink\n): I\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Transform,\n tenth: Sink\n): J\n\nexport function pipe (first: any, ...rest: any[]): any {\n // Duplex at start: wrap in function and return duplex source\n if (isDuplex(first)) {\n const duplex = first\n first = () => duplex.source\n // Iterable at start: wrap in function\n } else if (isIterable(first)) {\n const source = first\n first = () => source\n }\n\n const fns = [first, ...rest]\n\n if (fns.length > 1) {\n // Duplex at end: use duplex sink\n if (isDuplex(fns[fns.length - 1])) {\n fns[fns.length - 1] = fns[fns.length - 1].sink\n }\n }\n\n if (fns.length > 2) {\n // Duplex in the middle, consume source with duplex sink and return duplex source\n for (let i = 1; i < fns.length - 1; i++) {\n if (isDuplex(fns[i])) {\n fns[i] = duplexPipelineFn(fns[i])\n }\n }\n }\n\n return rawPipe(...fns)\n}\n","import { Peer } from \"@libp2p/interface-peer-store\";\nimport { Libp2p } from \"libp2p\";\n\n/**\n * Returns a pseudo-random peer that supports the given protocol.\n * Useful for protocols such as store and light push\n */\nexport async function selectRandomPeer(\n peers: Peer[]\n): Promise {\n if (peers.length === 0) return;\n\n const index = Math.round(Math.random() * (peers.length - 1));\n return peers[index];\n}\n\n/**\n * Returns the list of peers that supports the given protocol.\n */\nexport async function getPeersForProtocol(\n libp2p: Libp2p,\n protocols: string[]\n): Promise {\n const peers: Peer[] = [];\n await libp2p.peerStore.forEach((peer) => {\n for (let i = 0; i < protocols.length; i++) {\n if (peer.protocols.includes(protocols[i])) {\n peers.push(peer);\n break;\n }\n }\n });\n return peers;\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport default function accessor (buf: Uint8Array | Uint8ArrayList) {\n if (buf instanceof Uint8Array) {\n return {\n get (index: number) {\n return buf[index]\n },\n\n set (index: number, value: number) {\n buf[index] = value\n }\n }\n }\n\n return {\n get (index: number) {\n return buf.get(index)\n },\n\n set (index: number, value: number) {\n buf.set(index, value)\n }\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\n\nconst TWO_32 = 4294967296\n\nexport class LongBits {\n public hi: number\n public lo: number\n\n constructor (hi: number = 0, lo: number = 0) {\n this.hi = hi\n this.lo = lo\n }\n\n toBigInt (unsigned: boolean): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n zzDecode () {\n const mask = -(this.lo & 1)\n const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n const hi = (this.hi >>> 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n zzEncode () {\n const mask = this.hi >> 31\n const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n const lo = (this.lo << 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n toBytes (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n const access = accessor(buf)\n\n while (this.hi > 0) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0\n this.hi >>>= 7\n }\n\n while (this.lo > 127) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = this.lo >>> 7\n }\n\n access.set(offset++, this.lo)\n }\n\n static fromBigInt (value: bigint) {\n if (value === 0n) {\n return new LongBits()\n }\n\n const negative = value < 0\n\n if (negative) {\n value = -value\n }\n\n let hi = Number(value >> 32n) | 0\n let lo = Number(value - (BigInt(hi) << 32n)) | 0\n\n if (negative) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > TWO_32) {\n lo = 0\n\n if (++hi > TWO_32) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n static fromNumber (value: number) {\n if (value === 0) {\n return new LongBits()\n }\n\n const sign = value < 0\n\n if (sign) {\n value = -value\n }\n\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > 4294967295) {\n lo = 0\n\n if (++hi > 4294967295) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n static fromBytes (buf: Uint8ArrayList | Uint8Array, offset: number) {\n const access = accessor(buf)\n\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits()\n let i = 0\n\n if (buf.length - offset > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0\n bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0\n if (access.get(offset++) < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 1st..3th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (access.get(offset++) & 127) << i * 7) >>> 0\n return bits\n }\n if (buf.length - offset > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n /* istanbul ignore next */\n throw Error('invalid varint encoding')\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\nimport { LongBits } from './long-bits.js'\n\nconst MSB = 0x80\nconst REST = 0x7F\nconst MSBALL = ~REST\nconst INT = Math.pow(2, 31)\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\nexport const unsigned = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array) {\n let offset = 0\n const access = accessor(buf)\n\n while (value >= INT) {\n access.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n\n while ((value & MSBALL) > 0) {\n access.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n\n access.set(offset, value | 0)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0) {\n const access = accessor(buf)\n let value = 4294967295 // optimizer type-hint, tends to deopt otherwise (?!)\n\n value = (access.get(offset) & 127) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 14) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 21) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 15) << 28) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n if ((offset += 5) > buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n return value\n }\n}\n\nexport const signed = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array) {\n if (value < 0) {\n let offset = 0\n const access = accessor(buf)\n const bits = LongBits.fromNumber(value)\n\n while (bits.hi > 0) {\n access.set(offset++, bits.lo & 127 | 128)\n bits.lo = (bits.lo >>> 7 | bits.hi << 25) >>> 0\n bits.hi >>>= 7\n }\n\n while (bits.lo > 127) {\n access.set(offset++, bits.lo & 127 | 128)\n bits.lo = bits.lo >>> 7\n }\n\n access.set(offset++, bits.lo)\n\n return\n }\n\n unsigned.encode(value, buf)\n },\n\n decode (data: Uint8ArrayList | Uint8Array, offset = 0) {\n return unsigned.decode(data, offset) | 0\n }\n}\n\nexport const zigzag = {\n encodingLength (value: number): number {\n value = (value << 1 ^ value >> 31) >>> 0\n return unsigned.encodingLength(value)\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n value = (value << 1 ^ value >> 31) >>> 0\n return unsigned.encode(value, buf)\n },\n\n decode (data: Uint8ArrayList | Uint8Array, offset = 0) {\n const value = unsigned.decode(data, offset)\n return value >>> 1 ^ -(value & 1) | 0\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from './utils/varint.js'\nimport type { Codec } from './codec.js'\n\nexport function decodeMessage (buf: Uint8Array, codec: Codec) {\n // wrap root message\n const prefix = new Uint8Array(unsigned.encodingLength(buf.length))\n unsigned.encode(buf.length, prefix)\n\n return codec.decode(new Uint8ArrayList(prefix, buf), 0)\n}\n","import type { Codec } from './codec.js'\nimport { unsigned } from './utils/varint.js'\n\nexport function encodeMessage (message: T, codec: Codec) {\n // unwrap root message\n const encoded = codec.encode(message)\n const skip = unsigned.encodingLength(unsigned.decode(encoded))\n\n return encoded.slice(skip)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeFunction {\n (value: T): Uint8Array | Uint8ArrayList\n}\n\nexport interface DecodeFunction {\n (buf: Uint8ArrayList, offset: number): T\n}\n\nexport interface EncodingLengthFunction {\n (value: T): number\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n encodingLength: EncodingLengthFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction, encodingLength: EncodingLengthFunction): Codec {\n return {\n name,\n type,\n encode,\n decode,\n encodingLength\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function boolEncodingLength () {\n return 1\n}\n\nconst encode: EncodeFunction = function boolEncode (value) {\n return Uint8Array.from([value ? 1 : 0])\n}\n\nconst decode: DecodeFunction = function boolDecode (buffer, offset) {\n return buffer.get(offset) > 0\n}\n\nexport const bool = createCodec('bool', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function bytesEncodingLength (val) {\n const len = val.byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function bytesEncode (val) {\n const prefix = new Uint8Array(unsigned.encodingLength(val.byteLength))\n\n unsigned.encode(val.byteLength, prefix)\n\n return new Uint8ArrayList(prefix, val)\n}\n\nconst decode: DecodeFunction = function bytesDecode (buf, offset) {\n const byteLength = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(byteLength)\n\n return buf.slice(offset, offset + byteLength)\n}\n\nexport const bytes = createCodec('bytes', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function doubleEncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function doubleEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setFloat64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function doubleDecode (buf, offset) {\n return buf.getFloat64(offset, true)\n}\n\nexport const double = createCodec('double', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","\nimport { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n if (typeof val === 'number') {\n return val\n }\n\n return v[val]\n }\n\n const encodingLength: EncodingLengthFunction = function enumEncodingLength (val) {\n return unsigned.encodingLength(findValue(val))\n }\n\n const encode: EncodeFunction = function enumEncode (val) {\n const enumValue = findValue(val)\n\n const buf = new Uint8Array(unsigned.encodingLength(enumValue))\n unsigned.encode(enumValue, buf)\n\n return buf\n }\n\n const decode: DecodeFunction = function enumDecode (buf, offset) {\n const value = unsigned.decode(buf, offset)\n const strValue = value.toString()\n\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[strValue] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[strValue]\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function fixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function fixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function fixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const fixed32 = createCodec('fixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return 8\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const fixed64 = createCodec('fixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function floatEncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function floatEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(1)))\n buf.setFloat32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function floatDecode (buf, offset) {\n return buf.getFloat32(offset, true)\n}\n\nexport const float = createCodec('float', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { signed } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int32EncodingLength (val) {\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int32Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n signed.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int32Decode (buf, offset) {\n return signed.decode(buf, offset)\n}\n\nexport const int32 = createCodec('int32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\nimport { LongBits } from './long-bits.js'\n\nconst LIMIT = 0x7fn\n\n// https://github.com/joeltg/big-varint/blob/main/src/unsigned.ts\nexport const unsigned = {\n encodingLength (value: bigint): number {\n let i = 0\n for (; value >= 0x80n; i++) {\n value >>= 7n\n }\n return i + 1\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array) {\n const access = accessor(buf)\n\n let offset = 0\n while (LIMIT < value) {\n access.set(offset++, Number(value & LIMIT) | 0x80)\n value >>= 7n\n }\n\n access.set(offset, Number(value))\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(true)\n }\n}\n\nexport const signed = {\n encodingLength (value: bigint): number {\n if (value < 0n) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n if (value < 0n) {\n LongBits.fromBigInt(value).toBytes(buf, offset)\n\n return\n }\n\n return unsigned.encode(value, buf)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(false)\n }\n}\n\nexport const zigzag = {\n encodingLength (value: bigint): number {\n return unsigned.encodingLength(value >= 0 ? value * 2n : value * -2n - 1n)\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n LongBits.fromBigInt(value).zzEncode().toBytes(buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).zzDecode().toBigInt(false)\n }\n}\n","import { signed } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n signed.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return signed.decode(buf, offset) | 0n\n}\n\nexport const int64 = createCodec('int64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction, Codec } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { FieldDefs, FieldDef } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (fieldDefs: FieldDefs): Codec {\n const encodingLength: EncodingLengthFunction = function messageEncodingLength (val: Record) {\n let length = 0\n\n for (const fieldDef of Object.values(fieldDefs)) {\n length += fieldDef.codec.encodingLength(val[fieldDef.name])\n }\n\n return unsigned.encodingLength(length) + length\n }\n\n const encode: EncodeFunction> = function messageEncode (val) {\n const bytes = new Uint8ArrayList()\n\n function encodeValue (value: any, fieldNumber: number, fieldDef: FieldDef) {\n if (value == null) {\n if (fieldDef.optional === true) {\n return\n }\n\n throw new Error(`Non optional field \"${fieldDef.name}\" was ${value === null ? 'null' : 'undefined'}`)\n }\n\n const key = (fieldNumber << 3) | fieldDef.codec.type\n const prefix = new Uint8Array(unsigned.encodingLength(key))\n unsigned.encode(key, prefix)\n const encoded = fieldDef.codec.encode(value)\n\n bytes.append(prefix)\n bytes.append(encoded)\n }\n\n for (const [fieldNumberStr, fieldDef] of Object.entries(fieldDefs)) {\n const fieldNumber = parseInt(fieldNumberStr)\n\n if (fieldDef.repeats === true) {\n if (!Array.isArray(val[fieldDef.name])) {\n throw new Error(`Repeating field \"${fieldDef.name}\" was not an array`)\n }\n\n for (const value of val[fieldDef.name]) {\n encodeValue(value, fieldNumber, fieldDef)\n }\n } else {\n encodeValue(val[fieldDef.name], fieldNumber, fieldDef)\n }\n }\n\n const prefix = new Uint8Array(unsigned.encodingLength(bytes.length))\n unsigned.encode(bytes.length, prefix)\n\n return new Uint8ArrayList(prefix, bytes)\n }\n\n const decode: DecodeFunction = function messageDecode (buffer, offset) {\n const length = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(length)\n const end = offset + length\n const fields: any = {}\n\n while (offset < end) {\n const key = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(key)\n\n const wireType = key & 0x7\n const fieldNumber = key >> 3\n const fieldDef = fieldDefs[fieldNumber]\n let fieldLength = 0\n\n if (wireType === CODEC_TYPES.VARINT) {\n if (fieldDef != null) {\n // use the codec if it is available as this could be a bigint\n const value = fieldDef.codec.decode(buffer, offset)\n fieldLength = fieldDef.codec.encodingLength(value)\n } else {\n const value = unsigned.decode(buffer, offset)\n fieldLength = unsigned.encodingLength(value)\n }\n } else if (wireType === CODEC_TYPES.BIT64) {\n fieldLength = 8\n } else if (wireType === CODEC_TYPES.LENGTH_DELIMITED) {\n const valueLength = unsigned.decode(buffer, offset)\n fieldLength = valueLength + unsigned.encodingLength(valueLength)\n } else if (wireType === CODEC_TYPES.BIT32) {\n fieldLength = 4\n } else if (wireType === CODEC_TYPES.START_GROUP) {\n throw new Error('Unsupported wire type START_GROUP')\n } else if (wireType === CODEC_TYPES.END_GROUP) {\n throw new Error('Unsupported wire type END_GROUP')\n }\n\n if (fieldDef != null) {\n const value = fieldDef.codec.decode(buffer, offset)\n\n if (fieldDef.repeats === true) {\n if (fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n\n fields[fieldDef.name].push(value)\n } else {\n fields[fieldDef.name] = value\n }\n }\n\n offset += fieldLength\n }\n\n // make sure repeated fields have an array if not set\n for (const fieldDef of Object.values(fieldDefs)) {\n if (fieldDef.repeats === true && fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n }\n\n return fields\n }\n\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function sfixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const sfixed32 = createCodec('sfixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed64EncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function sfixed64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const sfixed64 = createCodec('sfixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { zigzag } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sint32EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function svarintEncode (val) {\n const buf = new Uint8Array(encodingLength(val))\n\n zigzag.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function svarintDecode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint32 = createCodec('sint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { zigzag } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n zigzag.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint64 = createCodec('sint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\n\nconst encodingLength: EncodingLengthFunction = function stringEncodingLength (val) {\n const len = uint8ArrayFromString(val).byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function stringEncode (val) {\n const asBuf = uint8ArrayFromString(val)\n const prefix = new Uint8Array(unsigned.encodingLength(asBuf.byteLength))\n\n unsigned.encode(asBuf.length, prefix)\n\n return new Uint8ArrayList(prefix, asBuf)\n}\n\nconst decode: DecodeFunction = function stringDecode (buf, offset) {\n const strLen = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(strLen)\n\n return uint8ArrayToString(buf.slice(offset, offset + strLen))\n}\n\nexport const string = createCodec('string', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint32EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint32Encode (val) {\n // val = val < 0 ? val + 4294967296 : val\n\n const buf = new Uint8Array(encodingLength(val))\n\n unsigned.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function uint32Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n\n // return value > 2147483647 ? value - 4294967296 : value\n}\n\nexport const uint32 = createCodec('uint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint64EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint64Encode (val) {\n const buf = new Uint8Array(unsigned.encodingLength(val))\n\n unsigned.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function uint64Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n}\n\nexport const uint64 = createCodec('uint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n bytes,\n string,\n uint32,\n double,\n sint64,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","import * as secp from \"@noble/secp256k1\";\nimport { concat } from \"uint8arrays/concat\";\n\nimport { getSubtle, randomBytes, sha256 } from \"../crypto\";\nimport { hexToBytes } from \"../utils\";\n/**\n * HKDF as implemented in go-ethereum.\n */\nfunction kdf(secret: Uint8Array, outputLength: number): Promise {\n let ctr = 1;\n let written = 0;\n let willBeResult = Promise.resolve(new Uint8Array());\n while (written < outputLength) {\n const counters = new Uint8Array([ctr >> 24, ctr >> 16, ctr >> 8, ctr]);\n const countersSecret = concat(\n [counters, secret],\n counters.length + secret.length\n );\n const willBeHashResult = sha256(countersSecret);\n willBeResult = willBeResult.then((result) =>\n willBeHashResult.then((hashResult) => {\n const _hashResult = new Uint8Array(hashResult);\n return concat(\n [result, _hashResult],\n result.length + _hashResult.length\n );\n })\n );\n written += 32;\n ctr += 1;\n }\n return willBeResult;\n}\n\nfunction aesCtrEncrypt(\n counter: Uint8Array,\n key: ArrayBufferLike,\n data: ArrayBufferLike\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, \"AES-CTR\", false, [\"encrypt\"])\n .then((cryptoKey) =>\n getSubtle().encrypt(\n { name: \"AES-CTR\", counter: counter, length: 128 },\n cryptoKey,\n data\n )\n )\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction aesCtrDecrypt(\n counter: Uint8Array,\n key: ArrayBufferLike,\n data: ArrayBufferLike\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, \"AES-CTR\", false, [\"decrypt\"])\n .then((cryptoKey) =>\n getSubtle().decrypt(\n { name: \"AES-CTR\", counter: counter, length: 128 },\n cryptoKey,\n data\n )\n )\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction hmacSha256Sign(\n key: ArrayBufferLike,\n msg: ArrayBufferLike\n): PromiseLike {\n const algorithm = { name: \"HMAC\", hash: { name: \"SHA-256\" } };\n return getSubtle()\n .importKey(\"raw\", key, algorithm, false, [\"sign\"])\n .then((cryptoKey) => getSubtle().sign(algorithm, cryptoKey, msg))\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction hmacSha256Verify(\n key: ArrayBufferLike,\n msg: ArrayBufferLike,\n sig: ArrayBufferLike\n): Promise {\n const algorithm = { name: \"HMAC\", hash: { name: \"SHA-256\" } };\n const _key = getSubtle().importKey(\"raw\", key, algorithm, false, [\"verify\"]);\n return _key.then((cryptoKey) =>\n getSubtle().verify(algorithm, cryptoKey, sig, msg)\n );\n}\n\n/**\n * Derive shared secret for given private and public keys.\n *\n * @param privateKeyA Sender's private key (32 bytes)\n * @param publicKeyB Recipient's public key (65 bytes)\n * @returns A promise that resolves with the derived shared secret (Px, 32 bytes)\n * @throws Error If arguments are invalid\n */\nfunction derive(privateKeyA: Uint8Array, publicKeyB: Uint8Array): Uint8Array {\n if (privateKeyA.length !== 32) {\n throw new Error(\n `Bad private key, it should be 32 bytes but it's actually ${privateKeyA.length} bytes long`\n );\n } else if (publicKeyB.length !== 65) {\n throw new Error(\n `Bad public key, it should be 65 bytes but it's actually ${publicKeyB.length} bytes long`\n );\n } else if (publicKeyB[0] !== 4) {\n throw new Error(\"Bad public key, a valid public key would begin with 4\");\n } else {\n const px = secp.getSharedSecret(privateKeyA, publicKeyB, true);\n // Remove the compression prefix\n return new Uint8Array(hexToBytes(px).slice(1));\n }\n}\n\n/**\n * Encrypt message for given recipient's public key.\n *\n * @param publicKeyTo Recipient's public key (65 bytes)\n * @param msg The message being encrypted\n * @return A promise that resolves with the ECIES structure serialized\n */\nexport async function encrypt(\n publicKeyTo: Uint8Array,\n msg: Uint8Array\n): Promise {\n const ephemPrivateKey = randomBytes(32);\n\n const sharedPx = await derive(ephemPrivateKey, publicKeyTo);\n\n const hash = await kdf(sharedPx, 32);\n\n const iv = randomBytes(16);\n const encryptionKey = hash.slice(0, 16);\n const cipherText = await aesCtrEncrypt(iv, encryptionKey, msg);\n\n const ivCipherText = concat([iv, cipherText], iv.length + cipherText.length);\n\n const macKey = await sha256(hash.slice(16));\n const hmac = await hmacSha256Sign(macKey, ivCipherText);\n const ephemPublicKey = secp.getPublicKey(ephemPrivateKey, false);\n\n return concat(\n [ephemPublicKey, ivCipherText, hmac],\n ephemPublicKey.length + ivCipherText.length + hmac.length\n );\n}\n\nconst metaLength = 1 + 64 + 16 + 32;\n\n/**\n * Decrypt message using given private key.\n *\n * @param privateKey A 32-byte private key of recipient of the message\n * @param encrypted ECIES serialized structure (result of ECIES encryption)\n * @returns The clear text\n * @throws Error If decryption fails\n */\nexport async function decrypt(\n privateKey: Uint8Array,\n encrypted: Uint8Array\n): Promise {\n if (encrypted.length <= metaLength) {\n throw new Error(\n `Invalid Ciphertext. Data is too small. It should ba at least ${metaLength} bytes`\n );\n } else if (encrypted[0] !== 4) {\n throw new Error(\n `Not a valid ciphertext. It should begin with 4 but actually begin with ${encrypted[0]}`\n );\n } else {\n // deserialize\n const ephemPublicKey = encrypted.slice(0, 65);\n const cipherTextLength = encrypted.length - metaLength;\n const iv = encrypted.slice(65, 65 + 16);\n const cipherAndIv = encrypted.slice(65, 65 + 16 + cipherTextLength);\n const ciphertext = cipherAndIv.slice(16);\n const msgMac = encrypted.slice(65 + 16 + cipherTextLength);\n\n // check HMAC\n const px = derive(privateKey, ephemPublicKey);\n const hash = await kdf(px, 32);\n const [encryptionKey, macKey] = await sha256(hash.slice(16)).then(\n (macKey) => [hash.slice(0, 16), macKey]\n );\n\n if (!(await hmacSha256Verify(macKey, cipherAndIv, msgMac))) {\n throw new Error(\"Incorrect MAC\");\n }\n\n return aesCtrDecrypt(iv, encryptionKey, ciphertext);\n }\n}\n","import * as secp from \"@noble/secp256k1\";\nimport { concat } from \"uint8arrays/concat\";\n\nimport { keccak256, randomBytes, sign } from \"../crypto\";\nimport { hexToBytes } from \"../utils\";\n\nimport { Symmetric } from \"./constants\";\nimport * as ecies from \"./ecies\";\nimport * as symmetric from \"./symmetric\";\n\nconst FlagsLength = 1;\nconst FlagMask = 3; // 0011\nconst IsSignedMask = 4; // 0100\nconst PaddingTarget = 256;\nconst SignatureLength = 65;\n\nexport type Signature = {\n signature: Uint8Array;\n publicKey: Uint8Array | undefined;\n};\n\n/**\n * Encode the payload pre-encryption.\n *\n * @internal\n * @param messagePayload: The payload to include in the message\n * @param sigPrivKey: If set, a signature using this private key is added.\n * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}\n * or {@link encryptSymmetric}.\n */\nexport async function clearEncode(\n messagePayload: Uint8Array,\n sigPrivKey?: Uint8Array\n): Promise<{ payload: Uint8Array; sig?: Signature }> {\n let envelope = new Uint8Array([0]); // No flags\n envelope = addPayloadSizeField(envelope, messagePayload);\n envelope = concat([envelope, messagePayload]);\n\n // Calculate padding:\n let rawSize =\n FlagsLength +\n computeSizeOfPayloadSizeField(messagePayload) +\n messagePayload.length;\n\n if (sigPrivKey) {\n rawSize += SignatureLength;\n }\n\n const remainder = rawSize % PaddingTarget;\n const paddingSize = PaddingTarget - remainder;\n const pad = randomBytes(paddingSize);\n\n if (!validateDataIntegrity(pad, paddingSize)) {\n throw new Error(\"failed to generate random padding of size \" + paddingSize);\n }\n\n envelope = concat([envelope, pad]);\n\n let sig;\n if (sigPrivKey) {\n envelope[0] |= IsSignedMask;\n const hash = keccak256(envelope);\n const bytesSignature = await sign(hash, sigPrivKey);\n envelope = concat([envelope, bytesSignature]);\n sig = {\n signature: bytesSignature,\n publicKey: secp.getPublicKey(sigPrivKey, false),\n };\n }\n\n return { payload: envelope, sig };\n}\n\n/**\n * Decode a decrypted payload.\n *\n * @internal\n */\nexport function clearDecode(\n message: Uint8Array\n): { payload: Uint8Array; sig?: Signature } | undefined {\n const sizeOfPayloadSizeField = getSizeOfPayloadSizeField(message);\n if (sizeOfPayloadSizeField === 0) return;\n\n const payloadSize = getPayloadSize(message, sizeOfPayloadSizeField);\n const payloadStart = 1 + sizeOfPayloadSizeField;\n const payload = message.slice(payloadStart, payloadStart + payloadSize);\n\n const isSigned = isMessageSigned(message);\n\n let sig;\n if (isSigned) {\n const signature = getSignature(message);\n const hash = getHash(message, isSigned);\n const publicKey = ecRecoverPubKey(hash, signature);\n sig = { signature, publicKey };\n }\n\n return { payload, sig };\n}\n\nfunction getSizeOfPayloadSizeField(message: Uint8Array): number {\n const messageDataView = new DataView(message.buffer);\n return messageDataView.getUint8(0) & FlagMask;\n}\n\nfunction getPayloadSize(\n message: Uint8Array,\n sizeOfPayloadSizeField: number\n): number {\n let payloadSizeBytes = message.slice(1, 1 + sizeOfPayloadSizeField);\n // int 32 == 4 bytes\n if (sizeOfPayloadSizeField < 4) {\n // If less than 4 bytes pad right (Little Endian).\n payloadSizeBytes = concat(\n [payloadSizeBytes, new Uint8Array(4 - sizeOfPayloadSizeField)],\n 4\n );\n }\n const payloadSizeDataView = new DataView(payloadSizeBytes.buffer);\n return payloadSizeDataView.getInt32(0, true);\n}\n\nfunction isMessageSigned(message: Uint8Array): boolean {\n const messageDataView = new DataView(message.buffer);\n return (messageDataView.getUint8(0) & IsSignedMask) == IsSignedMask;\n}\n\n/**\n * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n * The data MUST be flags | payload-length | payload | [signature].\n * The returned result can be set to `WakuMessage.payload`.\n *\n * @internal\n */\nexport async function encryptAsymmetric(\n data: Uint8Array,\n publicKey: Uint8Array | string\n): Promise {\n return ecies.encrypt(hexToBytes(publicKey), data);\n}\n\n/**\n * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n * The returned data is expected to be `flags | payload-length | payload | [signature]`.\n *\n * @internal\n */\nexport async function decryptAsymmetric(\n payload: Uint8Array,\n privKey: Uint8Array\n): Promise {\n return ecies.decrypt(privKey, payload);\n}\n\n/**\n * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n *\n * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.\n * @param key The key to use for encryption.\n * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.\n *\n * @internal\n */\nexport async function encryptSymmetric(\n data: Uint8Array,\n key: Uint8Array | string\n): Promise {\n const iv = symmetric.generateIv();\n\n // Returns `cipher | tag`\n const cipher = await symmetric.encrypt(iv, hexToBytes(key), data);\n return concat([cipher, iv]);\n}\n\n/**\n * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n *\n * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.\n * @param key The key to use for decryption.\n * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.\n *\n * @internal\n */\nexport async function decryptSymmetric(\n payload: Uint8Array,\n key: Uint8Array | string\n): Promise {\n const ivStart = payload.length - Symmetric.ivSize;\n const cipher = payload.slice(0, ivStart);\n const iv = payload.slice(ivStart);\n\n return symmetric.decrypt(iv, hexToBytes(key), cipher);\n}\n\n/**\n * Computes the flags & auxiliary-field as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n */\nfunction addPayloadSizeField(msg: Uint8Array, payload: Uint8Array): Uint8Array {\n const fieldSize = computeSizeOfPayloadSizeField(payload);\n let field = new Uint8Array(4);\n const fieldDataView = new DataView(field.buffer);\n fieldDataView.setUint32(0, payload.length, true);\n field = field.slice(0, fieldSize);\n msg = concat([msg, field]);\n msg[0] |= fieldSize;\n return msg;\n}\n\n/**\n * Returns the size of the auxiliary-field which in turns contains the payload size\n */\nfunction computeSizeOfPayloadSizeField(payload: Uint8Array): number {\n let s = 1;\n for (let i = payload.length; i >= 256; i /= 256) {\n s++;\n }\n return s;\n}\n\nfunction validateDataIntegrity(\n value: Uint8Array,\n expectedSize: number\n): boolean {\n if (value.length !== expectedSize) {\n return false;\n }\n\n return expectedSize <= 3 || value.findIndex((i) => i !== 0) !== -1;\n}\n\nfunction getSignature(message: Uint8Array): Uint8Array {\n return message.slice(message.length - SignatureLength, message.length);\n}\n\nfunction getHash(message: Uint8Array, isSigned: boolean): Uint8Array {\n if (isSigned) {\n return keccak256(message.slice(0, message.length - SignatureLength));\n }\n return keccak256(message);\n}\n\nfunction ecRecoverPubKey(\n messageHash: Uint8Array,\n signature: Uint8Array\n): Uint8Array | undefined {\n const recoveryDataView = new DataView(signature.slice(64).buffer);\n const recovery = recoveryDataView.getUint8(0);\n const _signature = secp.Signature.fromCompact(signature.slice(0, 64));\n\n return secp.recoverPublicKey(\n messageHash,\n _signature,\n recovery,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: compressed: false\n false\n );\n}\n","import { getSubtle, randomBytes } from \"../crypto\";\n\nimport { Symmetric } from \"./constants\";\n\nexport async function encrypt(\n iv: Uint8Array,\n key: Uint8Array,\n clearText: Uint8Array\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, Symmetric.algorithm, false, [\"encrypt\"])\n .then((cryptoKey) =>\n getSubtle().encrypt({ iv, ...Symmetric.algorithm }, cryptoKey, clearText)\n )\n .then((cipher) => new Uint8Array(cipher));\n}\n\nexport async function decrypt(\n iv: Uint8Array,\n key: Uint8Array,\n cipherText: Uint8Array\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, Symmetric.algorithm, false, [\"decrypt\"])\n .then((cryptoKey) =>\n getSubtle().decrypt({ iv, ...Symmetric.algorithm }, cryptoKey, cipherText)\n )\n .then((clear) => new Uint8Array(clear));\n}\n\nexport function generateIv(): Uint8Array {\n return randomBytes(Symmetric.ivSize);\n}\n","import debug from \"debug\";\n\nimport * as proto from \"../../proto/message\";\nimport { bytesToUtf8, utf8ToBytes } from \"../utils\";\n\nimport * as version_1 from \"./version_1\";\n\nconst DefaultVersion = 0;\nconst dbg = debug(\"waku:message\");\nconst OneMillion = BigInt(1_000_000);\n\nexport enum DecryptionMethod {\n Asymmetric = \"asymmetric\",\n Symmetric = \"symmetric\",\n}\n\nexport interface Options {\n /**\n * Timestamp to set on the message, defaults to now if not passed.\n */\n timestamp?: Date;\n /**\n * Public Key to use to encrypt the messages using ECIES (Asymmetric Encryption).\n *\n * @throws if both `encPublicKey` and `symKey` are passed\n */\n encPublicKey?: Uint8Array | string;\n /**\n * Key to use to encrypt the messages using AES (Symmetric Encryption).\n *\n * @throws if both `encPublicKey` and `symKey` are passed\n */\n symKey?: Uint8Array | string;\n /**\n * Private key to use to sign the message, either `encPublicKey` or `symKey` must be provided as only\n * encrypted messages are signed.\n */\n sigPrivKey?: Uint8Array;\n}\n\nexport class WakuMessage {\n private constructor(\n public proto: proto.WakuMessage,\n private _signaturePublicKey?: Uint8Array,\n private _signature?: Uint8Array\n ) {}\n\n /**\n * Create Message with an utf-8 string as payload.\n */\n static async fromUtf8String(\n utf8: string,\n contentTopic: string,\n opts?: Options\n ): Promise {\n const payload = utf8ToBytes(utf8);\n return WakuMessage.fromBytes(payload, contentTopic, opts);\n }\n\n /**\n * Create a Waku Message with the given payload.\n *\n * By default, the payload is kept clear (version 0).\n * If `opts.encPublicKey` is passed, the payload is encrypted using\n * asymmetric encryption (version 1).\n *\n * If `opts.sigPrivKey` is passed and version 1 is used, the payload is signed\n * before encryption.\n *\n * @throws if both `opts.encPublicKey` and `opt.symKey` are passed\n */\n static async fromBytes(\n payload: Uint8Array,\n contentTopic: string,\n opts?: Options\n ): Promise {\n const { timestamp, encPublicKey, symKey, sigPrivKey } = Object.assign(\n { timestamp: new Date() },\n opts ? opts : {}\n );\n\n let _payload = payload;\n let version = DefaultVersion;\n let sig;\n\n if (encPublicKey && symKey) {\n throw \"Pass either `encPublicKey` or `symKey`, not both.\";\n }\n\n if (encPublicKey) {\n const enc = await version_1.clearEncode(_payload, sigPrivKey);\n _payload = await version_1.encryptAsymmetric(enc.payload, encPublicKey);\n sig = enc.sig;\n version = 1;\n } else if (symKey) {\n const enc = await version_1.clearEncode(_payload, sigPrivKey);\n _payload = await version_1.encryptSymmetric(enc.payload, symKey);\n sig = enc.sig;\n version = 1;\n }\n\n return new WakuMessage(\n {\n payload: _payload,\n timestampDeprecated: timestamp.valueOf() / 1000,\n // milliseconds 10^-3 to nanoseconds 10^-9\n timestamp: BigInt(timestamp.valueOf()) * OneMillion,\n version,\n contentTopic,\n },\n sig?.publicKey,\n sig?.signature\n );\n }\n\n /**\n * Decode a byte array into Waku Message.\n *\n * @params bytes The message encoded using protobuf as defined in [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/).\n * @params decryptionKeys If the payload is encrypted (version = 1), then the\n * keys are used to attempt decryption of the message. The passed key can either\n * be asymmetric private keys or symmetric keys, both method are tried for each\n * key until the message is decrypted or combinations are run out.\n */\n static async decode(\n bytes: Uint8Array,\n decryptionKeys?: Array<{\n key: Uint8Array;\n method?: DecryptionMethod;\n contentTopic?: string[];\n }>\n ): Promise {\n const protoBuf = proto.WakuMessage.decode(bytes);\n\n return WakuMessage.decodeProto(protoBuf, decryptionKeys);\n }\n\n /**\n * Decode and decrypt Waku Message Protobuf Object into Waku Message.\n *\n * @params protoBuf The message to decode and decrypt.\n * @params decryptionKeys If the payload is encrypted (version = 1), then the\n * keys are used to attempt decryption of the message. The passed key can either\n * be asymmetric private keys or symmetric keys, both method are tried for each\n * key until the message is decrypted or combinations are run out.\n */\n static async decodeProto(\n protoBuf: proto.WakuMessage,\n decryptionKeys?: Array<{\n key: Uint8Array;\n method?: DecryptionMethod;\n contentTopics?: string[];\n }>\n ): Promise {\n if (protoBuf.payload === undefined) {\n dbg(\"Payload is undefined\");\n return;\n }\n const payload = protoBuf.payload;\n\n let signaturePublicKey;\n let signature;\n if (protoBuf.version === 1 && protoBuf.payload) {\n if (decryptionKeys === undefined) {\n dbg(\"Payload is encrypted but no private keys have been provided.\");\n return;\n }\n\n // Returns a bunch of `undefined` and hopefully one decrypted result\n const allResults = await Promise.all(\n decryptionKeys.map(async ({ key, method, contentTopics }) => {\n if (\n !contentTopics ||\n (protoBuf.contentTopic &&\n contentTopics.includes(protoBuf.contentTopic))\n ) {\n switch (method) {\n case DecryptionMethod.Asymmetric:\n try {\n return await version_1.decryptAsymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption despite decryption method being specified\",\n e\n );\n return;\n }\n case DecryptionMethod.Symmetric:\n try {\n return await version_1.decryptSymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption despite decryption method being specified\",\n e\n );\n return;\n }\n default:\n try {\n return await version_1.decryptSymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using symmetric encryption\",\n e\n );\n try {\n return await version_1.decryptAsymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption\",\n e\n );\n return;\n }\n }\n }\n } else {\n // No key available for this content topic\n return;\n }\n })\n );\n\n const isDefined = (dec: Uint8Array | undefined): dec is Uint8Array => {\n return !!dec;\n };\n\n const decodedResults = allResults.filter(isDefined);\n\n if (decodedResults.length === 0) {\n dbg(\"Failed to decrypt payload.\");\n return;\n }\n const dec = decodedResults[0];\n\n const res = await version_1.clearDecode(dec);\n if (!res) {\n dbg(\"Failed to decode payload.\");\n return;\n }\n Object.assign(protoBuf, { payload: res.payload });\n signaturePublicKey = res.sig?.publicKey;\n signature = res.sig?.signature;\n }\n\n return new WakuMessage(protoBuf, signaturePublicKey, signature);\n }\n\n encode(): Uint8Array {\n return proto.WakuMessage.encode(this.proto);\n }\n\n get payloadAsUtf8(): string {\n if (!this.payload) {\n return \"\";\n }\n\n try {\n return bytesToUtf8(this.payload);\n } catch (e) {\n dbg(\"Could not decode byte as UTF-8\", e);\n return \"\";\n }\n }\n\n get payload(): Uint8Array | undefined {\n if (this.proto.payload) {\n return new Uint8Array(this.proto.payload);\n }\n return;\n }\n\n get contentTopic(): string | undefined {\n return this.proto.contentTopic;\n }\n\n get version(): number | undefined {\n return this.proto.version;\n }\n\n get timestamp(): Date | undefined {\n // In the case we receive a value that is bigger than JS's max number,\n // we catch the error and return undefined.\n try {\n if (this.proto.timestamp) {\n // nanoseconds 10^-9 to milliseconds 10^-3\n const timestamp = this.proto.timestamp / OneMillion;\n return new Date(Number(timestamp));\n }\n\n if (this.proto.timestampDeprecated) {\n return new Date(this.proto.timestampDeprecated * 1000);\n }\n } catch (e) {\n return;\n }\n return;\n }\n\n /**\n * The public key used to sign the message.\n *\n * MAY be present if the message is version 1.\n */\n get signaturePublicKey(): Uint8Array | undefined {\n return this._signaturePublicKey;\n }\n\n /**\n * The signature of the message.\n *\n * MAY be present if the message is version 1.\n */\n get signature(): Uint8Array | undefined {\n return this._signature;\n }\n}\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n string,\n bool,\n bytes,\n uint32,\n double,\n sint64,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface FilterRequest {\n subscribe?: boolean;\n topic?: string;\n contentFilters: FilterRequest.ContentFilter[];\n}\n\nexport namespace FilterRequest {\n export interface ContentFilter {\n contentTopic?: string;\n }\n\n export namespace ContentFilter {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"contentTopic\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 1: { name: \"subscribe\", codec: bool, optional: true },\n 2: { name: \"topic\", codec: string, optional: true },\n 3: {\n name: \"contentFilters\",\n codec: FilterRequest.ContentFilter.codec(),\n repeats: true,\n },\n });\n };\n\n export const encode = (obj: FilterRequest): Uint8Array => {\n return encodeMessage(obj, FilterRequest.codec());\n };\n\n export const decode = (buf: Uint8Array): FilterRequest => {\n return decodeMessage(buf, FilterRequest.codec());\n };\n}\n\nexport interface MessagePush {\n messages: WakuMessage[];\n}\n\nexport namespace MessagePush {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"messages\", codec: WakuMessage.codec(), repeats: true },\n });\n };\n\n export const encode = (obj: MessagePush): Uint8Array => {\n return encodeMessage(obj, MessagePush.codec());\n };\n\n export const decode = (buf: Uint8Array): MessagePush => {\n return decodeMessage(buf, MessagePush.codec());\n };\n}\n\nexport interface FilterRPC {\n requestId?: string;\n request?: FilterRequest;\n push?: MessagePush;\n}\n\nexport namespace FilterRPC {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"requestId\", codec: string, optional: true },\n 2: { name: \"request\", codec: FilterRequest.codec(), optional: true },\n 3: { name: \"push\", codec: MessagePush.codec(), optional: true },\n });\n };\n\n export const encode = (obj: FilterRPC): Uint8Array => {\n return encodeMessage(obj, FilterRPC.codec());\n };\n\n export const decode = (buf: Uint8Array): FilterRPC => {\n return decodeMessage(buf, FilterRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","import { v4 as uuid } from \"uuid\";\n\nimport * as proto from \"../../proto/filter\";\n\nexport type ContentFilter = {\n contentTopic: string;\n};\n\n/**\n * FilterRPC represents a message conforming to the Waku Filter protocol\n */\nexport class FilterRPC {\n public constructor(public proto: proto.FilterRPC) {}\n\n static createRequest(\n topic: string,\n contentFilters: ContentFilter[],\n requestId?: string,\n subscribe = true\n ): FilterRPC {\n return new FilterRPC({\n requestId: requestId || uuid(),\n request: {\n subscribe,\n topic,\n contentFilters,\n },\n push: undefined,\n });\n }\n\n /**\n *\n * @param bytes Uint8Array of bytes from a FilterRPC message\n * @returns FilterRPC\n */\n static decode(bytes: Uint8Array): FilterRPC {\n const res = proto.FilterRPC.decode(bytes);\n return new FilterRPC(res);\n }\n\n /**\n * Encode the current FilterRPC request to bytes\n * @returns Uint8Array\n */\n encode(): Uint8Array {\n return proto.FilterRPC.encode(this.proto);\n }\n\n get push(): proto.MessagePush | undefined {\n return this.proto.push;\n }\n\n get requestId(): string | undefined {\n return this.proto.requestId;\n }\n}\n","import type { Stream } from \"@libp2p/interface-connection\";\nimport type { PeerId } from \"@libp2p/interface-peer-id\";\nimport type { Peer } from \"@libp2p/interface-peer-store\";\nimport type { IncomingStreamData } from \"@libp2p/interface-registrar\";\nimport debug from \"debug\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { WakuMessage as WakuMessageProto } from \"../../proto/message\";\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport { ContentFilter, FilterRPC } from \"./filter_rpc\";\nexport { ContentFilter };\n\nexport const FilterCodec = \"/vac/waku/filter/2.0.0-beta1\";\n\nconst log = debug(\"waku:filter\");\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport type FilterSubscriptionOpts = {\n /**\n * The Pubsub topic for the subscription\n */\n pubsubTopic?: string;\n /**\n * Optionally specify a PeerId for the subscription. If not included, will use a random peer.\n */\n peerId?: PeerId;\n};\n\nexport type FilterCallback = (msg: WakuMessage) => void | Promise;\n\nexport type UnsubscribeFunction = () => Promise;\n\n/**\n * Implements client side of the [Waku v2 Filter protocol](https://rfc.vac.dev/spec/12/).\n *\n * Note this currently only works in NodeJS when the Waku node is listening on a port, see:\n * - https://github.com/status-im/go-waku/issues/245\n * - https://github.com/status-im/nwaku/issues/948\n */\nexport class WakuFilter {\n pubSubTopic: string;\n private subscriptions: Map;\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.subscriptions = new Map();\n this.decryptionKeys = new Map();\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n this.libp2p\n .handle(FilterCodec, this.onRequest.bind(this))\n .catch((e) => log(\"Failed to register filter protocol\", e));\n }\n\n /**\n * @param contentTopics Array of ContentTopics to subscribe to. If empty, no messages will be returned from the filter.\n * @param callback A function that will be called on each message returned by the filter.\n * @param opts The FilterSubscriptionOpts used to narrow which messages are returned, and which peer to connect to.\n * @returns Unsubscribe function that can be used to end the subscription.\n */\n async subscribe(\n callback: FilterCallback,\n contentTopics: string[],\n opts?: FilterSubscriptionOpts\n ): Promise {\n const topic = opts?.pubsubTopic ?? this.pubSubTopic;\n const contentFilters = contentTopics.map((contentTopic) => ({\n contentTopic,\n }));\n const request = FilterRPC.createRequest(\n topic,\n contentFilters,\n undefined,\n true\n );\n\n const requestId = request.requestId;\n if (!requestId)\n throw new Error(\n \"Internal error: createRequest expected to set `requestId`\"\n );\n\n const peer = await this.getPeer(opts?.peerId);\n const stream = await this.newStream(peer);\n\n try {\n const res = await pipe(\n [request.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n\n log(\"response\", res);\n } catch (e) {\n log(\n \"Error subscribing to peer \",\n peer.id.toString(),\n \"for content topics\",\n contentTopics,\n \": \",\n e\n );\n throw e;\n }\n\n this.addCallback(requestId, callback);\n\n return async () => {\n await this.unsubscribe(topic, contentFilters, requestId, peer);\n this.removeCallback(requestId);\n };\n }\n\n private onRequest(streamData: IncomingStreamData): void {\n log(\"Receiving message push\");\n try {\n pipe(streamData.stream, lp.decode(), async (source) => {\n for await (const bytes of source) {\n const res = FilterRPC.decode(bytes.slice());\n if (res.requestId && res.push?.messages?.length) {\n await this.pushMessages(res.requestId, res.push.messages);\n }\n }\n }).then(\n () => {\n log(\"Receiving pipe closed.\");\n },\n (e) => {\n log(\"Error with receiving pipe\", e);\n }\n );\n } catch (e) {\n log(\"Error decoding message\", e);\n }\n }\n\n private async pushMessages(\n requestId: string,\n messages: WakuMessageProto[]\n ): Promise {\n const callback = this.subscriptions.get(requestId);\n if (!callback) {\n log(`No callback registered for request ID ${requestId}`);\n return;\n }\n\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n for (const message of messages) {\n const decoded = await WakuMessage.decodeProto(message, decryptionKeys);\n if (!decoded) {\n log(\"Not able to decode message\");\n continue;\n }\n callback(decoded);\n }\n }\n\n private addCallback(requestId: string, callback: FilterCallback): void {\n this.subscriptions.set(requestId, callback);\n }\n\n private removeCallback(requestId: string): void {\n this.subscriptions.delete(requestId);\n }\n\n private async unsubscribe(\n topic: string,\n contentFilters: ContentFilter[],\n requestId: string,\n peer: Peer\n ): Promise {\n const unsubscribeRequest = FilterRPC.createRequest(\n topic,\n contentFilters,\n requestId,\n false\n );\n\n const stream = await this.newStream(peer);\n try {\n await pipe([unsubscribeRequest.encode()], lp.encode(), stream.sink);\n } catch (e) {\n log(\"Error unsubscribing\", e);\n throw e;\n }\n }\n\n // Should be able to remove any at next libp2p release >0.37.3\n private async newStream(peer: Peer): Promise {\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections) {\n throw new Error(\"Failed to get a connection to the peer\");\n }\n\n // TODO: Appropriate connection selection\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: tsc is confused by the @libp2p/interface-connection type to use\n return connections[0].newStream(FilterCodec);\n }\n\n private async getPeer(peerId?: PeerId): Promise {\n let peer;\n if (peerId) {\n peer = await this.libp2p.peerStore.get(peerId);\n if (!peer) {\n throw new Error(\n `Failed to retrieve connection details for provided peer in peer store: ${peerId.toString()}`\n );\n }\n } else {\n peer = await this.randomPeer();\n if (!peer) {\n throw new Error(\n \"Failed to find known peer that registers waku filter protocol\"\n );\n }\n }\n return peer;\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received in any\n * subsequent [[subscribe]] call. This can either be a private key for\n * asymmetric encryption or a symmetric key. [[WakuStore]] will attempt to\n * decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**\n * Delete a decryption key so that it cannot be used in future [[subscribe]] calls\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n async peers(): Promise {\n return getPeersForProtocol(this.libp2p, [FilterCodec]);\n }\n\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n string,\n bool,\n bytes,\n uint32,\n double,\n sint64,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface PushRequest {\n pubSubTopic?: string;\n message?: WakuMessage;\n}\n\nexport namespace PushRequest {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"pubSubTopic\", codec: string, optional: true },\n 2: { name: \"message\", codec: WakuMessage.codec(), optional: true },\n });\n };\n\n export const encode = (obj: PushRequest): Uint8Array => {\n return encodeMessage(obj, PushRequest.codec());\n };\n\n export const decode = (buf: Uint8Array): PushRequest => {\n return decodeMessage(buf, PushRequest.codec());\n };\n}\n\nexport interface PushResponse {\n isSuccess?: boolean;\n info?: string;\n}\n\nexport namespace PushResponse {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"isSuccess\", codec: bool, optional: true },\n 2: { name: \"info\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: PushResponse): Uint8Array => {\n return encodeMessage(obj, PushResponse.codec());\n };\n\n export const decode = (buf: Uint8Array): PushResponse => {\n return decodeMessage(buf, PushResponse.codec());\n };\n}\n\nexport interface PushRPC {\n requestId?: string;\n request?: PushRequest;\n response?: PushResponse;\n}\n\nexport namespace PushRPC {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"requestId\", codec: string, optional: true },\n 2: { name: \"request\", codec: PushRequest.codec(), optional: true },\n 3: { name: \"response\", codec: PushResponse.codec(), optional: true },\n });\n };\n\n export const encode = (obj: PushRPC): Uint8Array => {\n return encodeMessage(obj, PushRPC.codec());\n };\n\n export const decode = (buf: Uint8Array): PushRPC => {\n return decodeMessage(buf, PushRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","import { v4 as uuid } from \"uuid\";\n\nimport * as proto from \"../../proto/light_push\";\nimport { WakuMessage } from \"../waku_message\";\n\nexport class PushRPC {\n public constructor(public proto: proto.PushRPC) {}\n\n static createRequest(message: WakuMessage, pubSubTopic: string): PushRPC {\n return new PushRPC({\n requestId: uuid(),\n request: {\n message: message.proto,\n pubSubTopic: pubSubTopic,\n },\n response: undefined,\n });\n }\n\n static decode(bytes: Uint8Array): PushRPC {\n const res = proto.PushRPC.decode(bytes);\n return new PushRPC(res);\n }\n\n encode(): Uint8Array {\n return proto.PushRPC.encode(this.proto);\n }\n\n get query(): proto.PushRequest | undefined {\n return this.proto.request;\n }\n\n get response(): proto.PushResponse | undefined {\n return this.proto.response;\n }\n}\n","import type { PeerId } from \"@libp2p/interface-peer-id\";\nimport type { Peer } from \"@libp2p/interface-peer-store\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Libp2p } from \"libp2p\";\nimport { concat } from \"uint8arrays/concat\";\n\nimport { PushResponse } from \"../../proto/light_push\";\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { WakuMessage } from \"../waku_message\";\n\nimport { PushRPC } from \"./push_rpc\";\n\nexport const LightPushCodec = \"/vac/waku/lightpush/2.0.0-beta1\";\nexport { PushResponse };\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport interface PushOptions {\n peerId?: PeerId;\n pubSubTopic?: string;\n}\n\n/**\n * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).\n */\nexport class WakuLightPush {\n pubSubTopic: string;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n }\n\n async push(\n message: WakuMessage,\n opts?: PushOptions\n ): Promise {\n let peer;\n if (opts?.peerId) {\n peer = await this.libp2p.peerStore.get(opts.peerId);\n if (!peer) throw \"Peer is unknown\";\n } else {\n peer = await this.randomPeer();\n }\n if (!peer) throw \"No peer available\";\n if (!peer.protocols.includes(LightPushCodec))\n throw \"Peer does not register waku light push protocol\";\n\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections) throw \"Failed to get a connection to the peer\";\n\n // TODO: Appropriate connection management\n const stream = await connections[0].newStream(LightPushCodec);\n try {\n const pubSubTopic = opts?.pubSubTopic\n ? opts.pubSubTopic\n : this.pubSubTopic;\n const query = PushRPC.createRequest(message, pubSubTopic);\n const res = await pipe(\n [query.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n try {\n const bytes = concat(res);\n const response = PushRPC.decode(bytes).response;\n\n if (!response) {\n console.log(\"No response in PushRPC\");\n return null;\n }\n\n return response;\n } catch (err) {\n console.log(\"Failed to decode push reply\", err);\n }\n } catch (err) {\n console.log(\"Failed to send waku light push request\", err);\n }\n return null;\n }\n\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * light push protocol. Waku may or may not be currently connected to these\n * peers.\n */\n async peers(): Promise {\n return getPeersForProtocol(this.libp2p, [LightPushCodec]);\n }\n\n /**\n * Returns a random peer that supports light push protocol from the address\n * book (`libp2p.peerStore`). Waku may or may not be currently connected to\n * this peer.\n */\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","export const second = 1000;\nexport const minute = 60 * second;\n\n/**\n * RelayCodec is the libp2p identifier for the waku relay protocol\n */\nexport const RelayCodecs = [\n \"/vac/waku/relay/2.0.0-beta2\",\n \"/vac/waku/relay/2.0.0\",\n];\n\nexport const RelayPingContentTopic = \"/relay-ping/1/ping/null\";\n\n/**\n * RelayGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to RelayGossipFactor * (total number of non-mesh peers), or\n * RelayDlazy, whichever is greater.\n */\nexport const RelayGossipFactor = 0.25;\n\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const RelayHeartbeatInitialDelay = 100;\n\n/**\n * RelayHeartbeatInterval controls the time between heartbeats.\n */\nexport const RelayHeartbeatInterval = second;\n\n/**\n * RelayPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to RelayPrunePeers other peers that we\n * know of.\n */\nexport const RelayPrunePeers = 16;\n\n/**\n * RelayPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of RelayPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least RelayPruneBackoff\n * before attempting to re-graft.\n */\nexport const RelayPruneBackoff = minute;\n\n/**\n * RelayFanoutTTL controls how long we keep track of the fanout state. If it's been\n * RelayFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const RelayFanoutTTL = minute;\n\n/**\n * RelayOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every RelayOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const RelayOpportunisticGraftTicks = 60;\n\n/**\n * RelayOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const RelayOpportunisticGraftPeers = 2;\n\n/**\n * RelayMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const RelayMaxIHaveLength = 5000;\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n bytes,\n sint64,\n string,\n enumeration,\n uint64,\n uint32,\n double,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface Index {\n digest?: Uint8Array;\n receivedTime?: bigint;\n senderTime?: bigint;\n pubsubTopic?: string;\n}\n\nexport namespace Index {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"digest\", codec: bytes, optional: true },\n 2: { name: \"receivedTime\", codec: sint64, optional: true },\n 3: { name: \"senderTime\", codec: sint64, optional: true },\n 4: { name: \"pubsubTopic\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: Index): Uint8Array => {\n return encodeMessage(obj, Index.codec());\n };\n\n export const decode = (buf: Uint8Array): Index => {\n return decodeMessage(buf, Index.codec());\n };\n}\n\nexport interface PagingInfo {\n pageSize?: bigint;\n cursor?: Index;\n direction?: PagingInfo.Direction;\n}\n\nexport namespace PagingInfo {\n export enum Direction {\n DIRECTION_BACKWARD_UNSPECIFIED = \"DIRECTION_BACKWARD_UNSPECIFIED\",\n DIRECTION_FORWARD = \"DIRECTION_FORWARD\",\n }\n\n enum __DirectionValues {\n DIRECTION_BACKWARD_UNSPECIFIED = 0,\n DIRECTION_FORWARD = 1,\n }\n\n export namespace Direction {\n export const codec = () => {\n return enumeration(__DirectionValues);\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 1: { name: \"pageSize\", codec: uint64, optional: true },\n 2: { name: \"cursor\", codec: Index.codec(), optional: true },\n 3: {\n name: \"direction\",\n codec: PagingInfo.Direction.codec(),\n optional: true,\n },\n });\n };\n\n export const encode = (obj: PagingInfo): Uint8Array => {\n return encodeMessage(obj, PagingInfo.codec());\n };\n\n export const decode = (buf: Uint8Array): PagingInfo => {\n return decodeMessage(buf, PagingInfo.codec());\n };\n}\n\nexport interface ContentFilter {\n contentTopic?: string;\n}\n\nexport namespace ContentFilter {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"contentTopic\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n}\n\nexport interface HistoryQuery {\n pubSubTopic?: string;\n contentFilters: ContentFilter[];\n pagingInfo?: PagingInfo;\n startTime?: bigint;\n endTime?: bigint;\n}\n\nexport namespace HistoryQuery {\n export const codec = (): Codec => {\n return message({\n 2: { name: \"pubSubTopic\", codec: string, optional: true },\n 3: {\n name: \"contentFilters\",\n codec: ContentFilter.codec(),\n repeats: true,\n },\n 4: { name: \"pagingInfo\", codec: PagingInfo.codec(), optional: true },\n 5: { name: \"startTime\", codec: sint64, optional: true },\n 6: { name: \"endTime\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: HistoryQuery): Uint8Array => {\n return encodeMessage(obj, HistoryQuery.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryQuery => {\n return decodeMessage(buf, HistoryQuery.codec());\n };\n}\n\nexport interface HistoryResponse {\n messages: WakuMessage[];\n pagingInfo?: PagingInfo;\n error?: HistoryResponse.Error;\n}\n\nexport namespace HistoryResponse {\n export enum Error {\n ERROR_NONE_UNSPECIFIED = \"ERROR_NONE_UNSPECIFIED\",\n ERROR_INVALID_CURSOR = \"ERROR_INVALID_CURSOR\",\n }\n\n enum __ErrorValues {\n ERROR_NONE_UNSPECIFIED = 0,\n ERROR_INVALID_CURSOR = 1,\n }\n\n export namespace Error {\n export const codec = () => {\n return enumeration(__ErrorValues);\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 2: { name: \"messages\", codec: WakuMessage.codec(), repeats: true },\n 3: { name: \"pagingInfo\", codec: PagingInfo.codec(), optional: true },\n 4: {\n name: \"error\",\n codec: HistoryResponse.Error.codec(),\n optional: true,\n },\n });\n };\n\n export const encode = (obj: HistoryResponse): Uint8Array => {\n return encodeMessage(obj, HistoryResponse.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryResponse => {\n return decodeMessage(buf, HistoryResponse.codec());\n };\n}\n\nexport interface HistoryRPC {\n requestId?: string;\n query?: HistoryQuery;\n response?: HistoryResponse;\n}\n\nexport namespace HistoryRPC {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"requestId\", codec: string, optional: true },\n 2: { name: \"query\", codec: HistoryQuery.codec(), optional: true },\n 3: { name: \"response\", codec: HistoryResponse.codec(), optional: true },\n });\n };\n\n export const encode = (obj: HistoryRPC): Uint8Array => {\n return encodeMessage(obj, HistoryRPC.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryRPC => {\n return decodeMessage(buf, HistoryRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n bytes,\n double,\n enumeration,\n uint64,\n string,\n uint32,\n sint64,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface Index {\n digest?: Uint8Array;\n receivedTime?: number;\n senderTime?: number;\n}\n\nexport namespace Index {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"digest\", codec: bytes, optional: true },\n 2: { name: \"receivedTime\", codec: double, optional: true },\n 3: { name: \"senderTime\", codec: double, optional: true },\n });\n };\n\n export const encode = (obj: Index): Uint8Array => {\n return encodeMessage(obj, Index.codec());\n };\n\n export const decode = (buf: Uint8Array): Index => {\n return decodeMessage(buf, Index.codec());\n };\n}\n\nexport interface PagingInfo {\n pageSize?: bigint;\n cursor?: Index;\n direction?: PagingInfo.Direction;\n}\n\nexport namespace PagingInfo {\n export enum Direction {\n DIRECTION_BACKWARD_UNSPECIFIED = \"DIRECTION_BACKWARD_UNSPECIFIED\",\n DIRECTION_FORWARD = \"DIRECTION_FORWARD\",\n }\n\n enum __DirectionValues {\n DIRECTION_BACKWARD_UNSPECIFIED = 0,\n DIRECTION_FORWARD = 1,\n }\n\n export namespace Direction {\n export const codec = () => {\n return enumeration(__DirectionValues);\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 1: { name: \"pageSize\", codec: uint64, optional: true },\n 2: { name: \"cursor\", codec: Index.codec(), optional: true },\n 3: {\n name: \"direction\",\n codec: PagingInfo.Direction.codec(),\n optional: true,\n },\n });\n };\n\n export const encode = (obj: PagingInfo): Uint8Array => {\n return encodeMessage(obj, PagingInfo.codec());\n };\n\n export const decode = (buf: Uint8Array): PagingInfo => {\n return decodeMessage(buf, PagingInfo.codec());\n };\n}\n\nexport interface ContentFilter {\n contentTopic?: string;\n}\n\nexport namespace ContentFilter {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"contentTopic\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n}\n\nexport interface HistoryQuery {\n pubSubTopic?: string;\n contentFilters: ContentFilter[];\n pagingInfo?: PagingInfo;\n startTime?: number;\n endTime?: number;\n}\n\nexport namespace HistoryQuery {\n export const codec = (): Codec => {\n return message({\n 2: { name: \"pubSubTopic\", codec: string, optional: true },\n 3: {\n name: \"contentFilters\",\n codec: ContentFilter.codec(),\n repeats: true,\n },\n 4: { name: \"pagingInfo\", codec: PagingInfo.codec(), optional: true },\n 5: { name: \"startTime\", codec: double, optional: true },\n 6: { name: \"endTime\", codec: double, optional: true },\n });\n };\n\n export const encode = (obj: HistoryQuery): Uint8Array => {\n return encodeMessage(obj, HistoryQuery.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryQuery => {\n return decodeMessage(buf, HistoryQuery.codec());\n };\n}\n\nexport interface HistoryResponse {\n messages: WakuMessage[];\n pagingInfo?: PagingInfo;\n error?: HistoryResponse.Error;\n}\n\nexport namespace HistoryResponse {\n export enum Error {\n ERROR_NONE_UNSPECIFIED = \"ERROR_NONE_UNSPECIFIED\",\n ERROR_INVALID_CURSOR = \"ERROR_INVALID_CURSOR\",\n }\n\n enum __ErrorValues {\n ERROR_NONE_UNSPECIFIED = 0,\n ERROR_INVALID_CURSOR = 1,\n }\n\n export namespace Error {\n export const codec = () => {\n return enumeration(__ErrorValues);\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 2: { name: \"messages\", codec: WakuMessage.codec(), repeats: true },\n 3: { name: \"pagingInfo\", codec: PagingInfo.codec(), optional: true },\n 4: {\n name: \"error\",\n codec: HistoryResponse.Error.codec(),\n optional: true,\n },\n });\n };\n\n export const encode = (obj: HistoryResponse): Uint8Array => {\n return encodeMessage(obj, HistoryResponse.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryResponse => {\n return decodeMessage(buf, HistoryResponse.codec());\n };\n}\n\nexport interface HistoryRPC {\n requestId?: string;\n query?: HistoryQuery;\n response?: HistoryResponse;\n}\n\nexport namespace HistoryRPC {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"requestId\", codec: string, optional: true },\n 2: { name: \"query\", codec: HistoryQuery.codec(), optional: true },\n 3: { name: \"response\", codec: HistoryResponse.codec(), optional: true },\n });\n };\n\n export const encode = (obj: HistoryRPC): Uint8Array => {\n return encodeMessage(obj, HistoryRPC.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryRPC => {\n return decodeMessage(buf, HistoryRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","export enum StoreCodecs {\n V2Beta3 = \"/vac/waku/store/2.0.0-beta3\",\n V2Beta4 = \"/vac/waku/store/2.0.0-beta4\",\n}\n","import { v4 as uuid } from \"uuid\";\n\nimport * as protoV2Beta3 from \"../../proto/store_v2beta3\";\nimport * as protoV2Beta4 from \"../../proto/store_v2beta4\";\n\nimport { StoreCodecs } from \"./constants\";\n\nconst OneMillion = BigInt(1_000_000);\n\nexport enum PageDirection {\n BACKWARD = \"backward\",\n FORWARD = \"forward\",\n}\n\nexport interface Params {\n contentTopics: string[];\n pubSubTopic: string;\n pageDirection: PageDirection;\n pageSize: number;\n startTime?: Date;\n endTime?: Date;\n cursor?: protoV2Beta3.Index | protoV2Beta4.Index;\n storeCodec?: StoreCodecs;\n}\n\nexport class HistoryRPC {\n private readonly historyRpc:\n | typeof protoV2Beta3.HistoryRPC\n | typeof protoV2Beta4.HistoryRPC;\n\n private constructor(\n public readonly proto: protoV2Beta3.HistoryRPC | protoV2Beta4.HistoryRPC,\n public readonly storeCodec: StoreCodecs\n ) {\n switch (storeCodec) {\n case StoreCodecs.V2Beta3:\n this.historyRpc = protoV2Beta3.HistoryRPC;\n break;\n case StoreCodecs.V2Beta4:\n this.historyRpc = protoV2Beta4.HistoryRPC;\n break;\n default:\n throw `Internal Error: Unexpected store codec value received in constructor: ${storeCodec}`;\n }\n }\n\n get query():\n | protoV2Beta3.HistoryQuery\n | protoV2Beta4.HistoryQuery\n | undefined {\n return this.proto.query;\n }\n\n get response():\n | protoV2Beta3.HistoryResponse\n | protoV2Beta4.HistoryResponse\n | undefined {\n return this.proto.response;\n }\n\n /**\n * Create History Query.\n */\n static createQuery(params: Params): HistoryRPC {\n const storeCodec = params.storeCodec ?? StoreCodecs.V2Beta4;\n\n const contentFilters = params.contentTopics.map((contentTopic) => {\n return { contentTopic };\n });\n\n const direction = directionToProto(params.pageDirection);\n\n switch (storeCodec) {\n case StoreCodecs.V2Beta3:\n // Using function to scope variables\n return ((): HistoryRPC => {\n const pagingInfo = {\n pageSize: BigInt(params.pageSize),\n cursor: params.cursor,\n direction,\n } as protoV2Beta3.PagingInfo;\n\n let startTime, endTime;\n if (params.startTime) startTime = params.startTime.valueOf() / 1000;\n\n if (params.endTime) endTime = params.endTime.valueOf() / 1000;\n\n return new HistoryRPC(\n {\n requestId: uuid(),\n query: {\n pubSubTopic: params.pubSubTopic,\n contentFilters,\n pagingInfo,\n startTime,\n endTime,\n },\n response: undefined,\n },\n storeCodec\n );\n })();\n case StoreCodecs.V2Beta4:\n return ((): HistoryRPC => {\n const pagingInfo = {\n pageSize: BigInt(params.pageSize),\n cursor: params.cursor,\n direction,\n } as protoV2Beta4.PagingInfo;\n\n let startTime, endTime;\n if (params.startTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n startTime = BigInt(params.startTime.valueOf()) * OneMillion;\n }\n\n if (params.endTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n endTime = BigInt(params.endTime.valueOf()) * OneMillion;\n }\n return new HistoryRPC(\n {\n requestId: uuid(),\n query: {\n pubSubTopic: params.pubSubTopic,\n contentFilters,\n pagingInfo,\n startTime,\n endTime,\n },\n response: undefined,\n },\n storeCodec\n );\n })();\n\n default:\n throw `Internal Error: Unexpected store codec value received in createQuery: ${storeCodec}`;\n }\n }\n\n decode(bytes: Uint8Array): HistoryRPC {\n const res = this.historyRpc.decode(bytes);\n return new HistoryRPC(res, this.storeCodec);\n }\n\n encode(): Uint8Array {\n return this.historyRpc.encode(this.proto as any);\n }\n}\n\nfunction directionToProto(\n pageDirection: PageDirection\n): protoV2Beta4.PagingInfo.Direction {\n switch (pageDirection) {\n case PageDirection.BACKWARD:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_BACKWARD_UNSPECIFIED;\n case PageDirection.FORWARD:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_FORWARD;\n default:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_BACKWARD_UNSPECIFIED;\n }\n}\n","import type { PeerId } from \"@libp2p/interface-peer-id\";\nimport { Peer } from \"@libp2p/interface-peer-store\";\nimport debug from \"debug\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Libp2p } from \"libp2p\";\nimport { concat } from \"uint8arrays/concat\";\n\nimport * as protoV2Beta4 from \"../../proto/store_v2beta4\";\nimport { HistoryResponse } from \"../../proto/store_v2beta4\";\nimport { DefaultPubSubTopic, StoreCodecs } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport { HistoryRPC, PageDirection } from \"./history_rpc\";\n\nimport Error = HistoryResponse.Error;\n\nconst dbg = debug(\"waku:store\");\n\nexport const DefaultPageSize = 10;\n\nexport { PageDirection, StoreCodecs };\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport interface TimeFilter {\n startTime: Date;\n endTime: Date;\n}\n\nexport interface QueryOptions {\n /**\n * The peer to query. If undefined, a pseudo-random peer is selected from the connected Waku Store peers.\n */\n peerId?: PeerId;\n /**\n * The pubsub topic to pass to the query.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/).\n */\n pubSubTopic?: string;\n /**\n * The direction in which pages are retrieved:\n * - [[PageDirection.BACKWARD]]: Most recent page first.\n * - [[PageDirection.FORWARD]]: Oldest page first.\n *\n * Note: This does not affect the ordering of messages with the page\n * (oldest message is always first).\n *\n * @default [[PageDirection.BACKWARD]]\n */\n pageDirection?: PageDirection;\n /**\n * The number of message per page.\n *\n * @default [[DefaultPageSize]]\n */\n pageSize?: number;\n /**\n * Retrieve messages with a timestamp within the provided values.\n */\n timeFilter?: TimeFilter;\n /**\n * Callback called on pages of stored messages as they are retrieved.\n *\n * Allows for a faster access to the results as it is called as soon as a page\n * is received. Traversal of the pages is done automatically so this function\n * will invoked for each retrieved page.\n *\n * If the call on a page returns `true`, then traversal of the pages is aborted.\n * For example, this can be used for the caller to stop the query after a\n * specific message is found.\n */\n callback?: (messages: WakuMessage[]) => void | boolean;\n /**\n * Keys that will be used to decrypt messages.\n *\n * It can be Asymmetric Private Keys and Symmetric Keys in the same array,\n * all keys will be tried with both methods.\n */\n decryptionKeys?: Array;\n}\n\n/**\n * Implements the [Waku v2 Store protocol](https://rfc.vac.dev/spec/13/).\n *\n * The Waku Store protocol can be used to retrieved historical messages.\n */\nexport class WakuStore {\n pubSubTopic: string;\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n\n this.decryptionKeys = new Map();\n }\n\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n *\n * @param contentTopics The content topics to pass to the query, leave empty to\n * retrieve all messages.\n * @param options Optional parameters.\n *\n * @throws If not able to reach a Waku Store peer to query\n * or if an error is encountered when processing the reply.\n */\n async queryHistory(\n contentTopics: string[],\n options?: QueryOptions\n ): Promise {\n let startTime, endTime;\n\n if (options?.timeFilter) {\n startTime = options.timeFilter.startTime;\n endTime = options.timeFilter.endTime;\n }\n\n const opts = Object.assign(\n {\n pubSubTopic: this.pubSubTopic,\n pageDirection: PageDirection.BACKWARD,\n pageSize: DefaultPageSize,\n },\n options,\n { contentTopics, startTime, endTime }\n );\n\n dbg(\"Querying history with the following options\", {\n peerId: options?.peerId?.toString(),\n ...options,\n });\n\n let peer;\n if (opts.peerId) {\n peer = await this.libp2p.peerStore.get(opts.peerId);\n if (!peer)\n throw `Failed to retrieve connection details for provided peer in peer store: ${opts.peerId.toString()}`;\n } else {\n peer = await this.randomPeer();\n if (!peer)\n throw \"Failed to find known peer that registers waku store protocol\";\n }\n\n let storeCodec = \"\";\n for (const codec of Object.values(StoreCodecs)) {\n if (peer.protocols.includes(codec)) {\n storeCodec = codec;\n // Do not break as we want to keep the last value\n }\n }\n dbg(`Use store codec ${storeCodec}`);\n if (!storeCodec)\n throw `Peer does not register waku store protocol: ${peer.id.toString()}`;\n\n Object.assign(opts, { storeCodec });\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections || !connections.length)\n throw \"Failed to get a connection to the peer\";\n\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n // Add the decryption keys passed to this function against the\n // content topics also passed to this function.\n if (opts.decryptionKeys) {\n opts.decryptionKeys.forEach((key) => {\n decryptionKeys.push({\n key: hexToBytes(key),\n contentTopics: contentTopics.length ? contentTopics : undefined,\n method: undefined,\n });\n });\n }\n\n const messages: WakuMessage[] = [];\n let cursor = undefined;\n while (true) {\n // TODO: Some connection selection logic?\n const stream = await connections[0].newStream(storeCodec);\n const queryOpts = Object.assign(opts, { cursor });\n const historyRpcQuery = HistoryRPC.createQuery(queryOpts);\n dbg(\"Querying store peer\", connections[0].remoteAddr.toString());\n\n const res = await pipe(\n [historyRpcQuery.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n const bytes = concat(res);\n const reply = historyRpcQuery.decode(bytes);\n\n if (!reply.response) {\n dbg(\"No message returned from store: `response` field missing\");\n }\n\n const response = reply.response as protoV2Beta4.HistoryResponse;\n\n if (response.error && response.error !== Error.ERROR_NONE_UNSPECIFIED) {\n throw \"History response contains an Error: \" + response.error;\n }\n\n if (!response.messages || !response.messages.length) {\n // No messages left (or stored)\n dbg(\"No message returned from store: `messages` array empty\");\n return messages;\n }\n\n dbg(\n `${response.messages.length} messages retrieved for pubsub topic ${opts.pubSubTopic}`\n );\n\n const pageMessages: WakuMessage[] = [];\n await Promise.all(\n response.messages.map(async (protoMsg) => {\n const msg = await WakuMessage.decodeProto(protoMsg, decryptionKeys);\n\n if (msg) {\n messages.push(msg);\n pageMessages.push(msg);\n }\n })\n );\n\n let abort = false;\n if (opts.callback) {\n abort = Boolean(opts.callback(pageMessages));\n }\n\n const responsePageSize = response.pagingInfo?.pageSize;\n const queryPageSize = historyRpcQuery.query?.pagingInfo?.pageSize;\n if (\n abort ||\n // Response page size smaller than query, meaning this is the last page\n (responsePageSize && queryPageSize && responsePageSize < queryPageSize)\n ) {\n return messages;\n }\n\n cursor = response.pagingInfo?.cursor;\n if (cursor === undefined) {\n // If the server does not return cursor then there is an issue,\n // Need to abort, or we end up in an infinite loop\n dbg(\"Store response does not contain a cursor, stopping pagination\");\n return messages;\n }\n }\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received in any\n * subsequent [[queryHistory]] call. This can either be a private key for\n * asymmetric encryption or a symmetric key. [[WakuStore]] will attempt to\n * decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**cursorV2Beta4\n * Delete a decryption key that was used to attempt decryption of messages\n * received in subsequent [[queryHistory]] calls.\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * store protocol. Waku may or may not be currently connected to these peers.\n */\n async peers(): Promise {\n const codecs = [];\n for (const codec of Object.values(StoreCodecs)) {\n codecs.push(codec);\n }\n\n return getPeersForProtocol(this.libp2p, codecs);\n }\n\n /**\n * Returns a random peer that supports store protocol from the address\n * book (`libp2p.peerStore`). Waku may or may not be currently connected to\n * this peer.\n */\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","import type { Stream } from \"@libp2p/interface-connection\";\nimport type { PeerId } from \"@libp2p/interface-peer-id\";\nimport { peerIdFromString } from \"@libp2p/peer-id\";\nimport type { Multiaddr } from \"@multiformats/multiaddr\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport debug from \"debug\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { FilterCodec, WakuFilter } from \"./waku_filter\";\nimport { LightPushCodec, WakuLightPush } from \"./waku_light_push\";\nimport { DecryptionMethod, WakuMessage } from \"./waku_message\";\nimport { WakuRelay } from \"./waku_relay\";\nimport { RelayCodecs, RelayPingContentTopic } from \"./waku_relay/constants\";\nimport { StoreCodecs, WakuStore } from \"./waku_store\";\n\nexport const DefaultPingKeepAliveValueSecs = 0;\nexport const DefaultRelayKeepAliveValueSecs = 5 * 60;\n\nconst log = debug(\"waku:waku\");\n\nexport enum Protocols {\n Relay = \"relay\",\n Store = \"store\",\n LightPush = \"lightpush\",\n Filter = \"filter\",\n}\n\nexport interface WakuOptions {\n /**\n * Set keep alive frequency in seconds: Waku will send a `/ipfs/ping/1.0.0`\n * request to each peer after the set number of seconds. Set to 0 to disable.\n *\n * @default {@link DefaultPingKeepAliveValueSecs}\n */\n pingKeepAlive?: number;\n /**\n * Set keep alive frequency in seconds: Waku will send a ping message over\n * relay to each peer after the set number of seconds. Set to 0 to disable.\n *\n * @default {@link DefaultRelayKeepAliveValueSecs}\n */\n relayKeepAlive?: number;\n decryptionKeys?: Array;\n}\n\nexport class Waku {\n public libp2p: Libp2p;\n public relay: WakuRelay;\n public store: WakuStore;\n public filter: WakuFilter;\n public lightPush: WakuLightPush;\n\n private pingKeepAliveTimers: {\n [peer: string]: ReturnType;\n };\n private relayKeepAliveTimers: {\n [peer: string]: ReturnType;\n };\n\n constructor(\n options: WakuOptions,\n libp2p: Libp2p,\n store: WakuStore,\n lightPush: WakuLightPush,\n filter: WakuFilter\n ) {\n this.libp2p = libp2p;\n this.relay = libp2p.pubsub as unknown as WakuRelay;\n this.store = store;\n this.filter = filter;\n this.lightPush = lightPush;\n this.pingKeepAliveTimers = {};\n this.relayKeepAliveTimers = {};\n\n const pingKeepAlive =\n options.pingKeepAlive || DefaultPingKeepAliveValueSecs;\n const relayKeepAlive =\n options.relayKeepAlive || DefaultRelayKeepAliveValueSecs;\n\n libp2p.connectionManager.addEventListener(\"peer:connect\", (evt) => {\n this.startKeepAlive(evt.detail.remotePeer, pingKeepAlive, relayKeepAlive);\n });\n\n /**\n * NOTE: Event is not being emitted on closing nor losing a connection.\n * @see https://github.com/libp2p/js-libp2p/issues/939\n * @see https://github.com/status-im/js-waku/issues/252\n *\n * >This event will be triggered anytime we are disconnected from another peer,\n * >regardless of the circumstances of that disconnection.\n * >If we happen to have multiple connections to a peer,\n * >this event will **only** be triggered when the last connection is closed.\n * @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100\n */\n libp2p.connectionManager.addEventListener(\"peer:disconnect\", (evt) => {\n this.stopKeepAlive(evt.detail.remotePeer);\n });\n\n options?.decryptionKeys?.forEach((key) => {\n this.addDecryptionKey(key);\n });\n }\n\n /**\n * Dials to the provided peer.\n *\n * @param peer The peer to dial\n * @param protocols Waku protocols we expect from the peer; Default to Relay\n */\n async dial(\n peer: PeerId | Multiaddr,\n protocols?: Protocols[]\n ): Promise {\n const _protocols = protocols ?? [Protocols.Relay];\n\n const codecs: string[] = [];\n if (_protocols.includes(Protocols.Relay)) {\n RelayCodecs.forEach((codec) => codecs.push(codec));\n }\n if (_protocols.includes(Protocols.Store)) {\n for (const codec of Object.values(StoreCodecs)) {\n codecs.push(codec);\n }\n }\n if (_protocols.includes(Protocols.LightPush)) {\n codecs.push(LightPushCodec);\n }\n if (_protocols.includes(Protocols.Filter)) {\n codecs.push(FilterCodec);\n }\n\n return this.libp2p.dialProtocol(peer, codecs);\n }\n\n /**\n * Add peer to address book, it will be auto-dialed in the background.\n */\n addPeerToAddressBook(\n peerId: PeerId | string,\n multiaddrs: Multiaddr[] | string[]\n ): void {\n let peer;\n if (typeof peerId === \"string\") {\n peer = peerIdFromString(peerId);\n } else {\n peer = peerId;\n }\n const addresses = multiaddrs.map((addr: Multiaddr | string) => {\n if (typeof addr === \"string\") {\n return multiaddr(addr);\n } else {\n return addr;\n }\n });\n this.libp2p.peerStore.addressBook.set(peer, addresses);\n }\n\n async start(): Promise {\n await this.libp2p.start();\n }\n\n async stop(): Promise {\n this.stopAllKeepAlives();\n await this.libp2p.stop();\n }\n\n isStarted(): boolean {\n return this.libp2p.isStarted();\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received via\n * [[WakuRelay]] and [[WakuStore]]. This can either be a private key for\n * asymmetric encryption or a symmetric key.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.relay.addDecryptionKey(key, options);\n this.store.addDecryptionKey(key, options);\n this.filter.addDecryptionKey(key, options);\n }\n\n /**\n * Delete a decryption key that was used to attempt decryption of messages\n * received via [[WakuRelay]] or [[WakuStore]].\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.relay.deleteDecryptionKey(key);\n this.store.deleteDecryptionKey(key);\n this.filter.deleteDecryptionKey(key);\n }\n\n /**\n * Return the local multiaddr with peer id on which libp2p is listening.\n *\n * @throws if libp2p is not listening on localhost.\n */\n getLocalMultiaddrWithID(): string {\n const localMultiaddr = this.libp2p\n .getMultiaddrs()\n .find((addr) => addr.toString().match(/127\\.0\\.0\\.1/));\n if (!localMultiaddr || localMultiaddr.toString() === \"\") {\n throw \"Not listening on localhost\";\n }\n return localMultiaddr + \"/p2p/\" + this.libp2p.peerId.toString();\n }\n\n private startKeepAlive(\n peerId: PeerId,\n pingPeriodSecs: number,\n relayPeriodSecs: number\n ): void {\n // Just in case a timer already exist for this peer\n this.stopKeepAlive(peerId);\n\n const peerIdStr = peerId.toString();\n\n if (pingPeriodSecs !== 0) {\n this.pingKeepAliveTimers[peerIdStr] = setInterval(() => {\n this.libp2p.ping(peerId).catch((e) => {\n log(`Ping failed (${peerIdStr})`, e);\n });\n }, pingPeriodSecs * 1000);\n }\n\n if (relayPeriodSecs !== 0) {\n this.relayKeepAliveTimers[peerIdStr] = setInterval(() => {\n WakuMessage.fromBytes(new Uint8Array(), RelayPingContentTopic).then(\n (wakuMsg) => this.relay.send(wakuMsg)\n );\n }, relayPeriodSecs * 1000);\n }\n }\n\n private stopKeepAlive(peerId: PeerId): void {\n const peerIdStr = peerId.toString();\n\n if (this.pingKeepAliveTimers[peerIdStr]) {\n clearInterval(this.pingKeepAliveTimers[peerIdStr]);\n delete this.pingKeepAliveTimers[peerIdStr];\n }\n\n if (this.relayKeepAliveTimers[peerIdStr]) {\n clearInterval(this.relayKeepAliveTimers[peerIdStr]);\n delete this.relayKeepAliveTimers[peerIdStr];\n }\n }\n\n private stopAllKeepAlives(): void {\n for (const timer of [\n ...Object.values(this.pingKeepAliveTimers),\n ...Object.values(this.relayKeepAliveTimers),\n ]) {\n clearInterval(timer);\n }\n\n this.pingKeepAliveTimers = {};\n this.relayKeepAliveTimers = {};\n }\n}\n","import type { GossipSub } from \"@chainsafe/libp2p-gossipsub\";\nimport { Peer, PeerProtocolsChangeData } from \"@libp2p/interface-peer-store\";\nimport debug from \"debug\";\nimport type { Libp2p } from \"libp2p\";\nimport { pEvent } from \"p-event\";\n\nimport { StoreCodecs } from \"./constants\";\nimport { Protocols, Waku } from \"./waku\";\nimport { FilterCodec } from \"./waku_filter\";\nimport { LightPushCodec } from \"./waku_light_push\";\n\nconst log = debug(\"waku:wait-for-remote-peer\");\n\ninterface WakuProtocol {\n libp2p: Libp2p;\n peers: () => Promise;\n}\n\ninterface WakuGossipSubProtocol extends GossipSub {\n getMeshPeers: () => string[];\n}\n\n/**\n * Wait for a remote peer to be ready given the passed protocols.\n * Must be used after attempting to connect to nodes, using {@link Waku.dial} or\n * a bootstrap method with {@link Waku.constructor}.\n *\n * If the passed protocols is a GossipSub protocol, then it resolves only once\n * a peer is in a mesh, to help ensure that other peers will send and receive\n * message to us.\n *\n * @param waku The Waku Node\n * @param protocols The protocols that need to be enabled by remote peers.\n * @param timeoutMs A timeout value in milliseconds..\n *\n * @returns A promise that **resolves** if all desired protocols are fulfilled by\n * remote nodes, **rejects** if the timeoutMs is reached.\n *\n * @default Remote peer must have Waku Relay enabled and no time out is applied.\n */\nexport async function waitForRemotePeer(\n waku: Waku,\n protocols?: Protocols[],\n timeoutMs?: number\n): Promise {\n protocols = protocols ?? [Protocols.Relay];\n\n if (!waku.isStarted()) return Promise.reject(\"Waku node is not started\");\n\n const promises = [];\n\n if (protocols.includes(Protocols.Relay)) {\n promises.push(waitForGossipSubPeerInMesh(waku.relay));\n }\n\n if (protocols.includes(Protocols.Store)) {\n promises.push(waitForConnectedPeer(waku.store, Object.values(StoreCodecs)));\n }\n\n if (protocols.includes(Protocols.LightPush)) {\n promises.push(waitForConnectedPeer(waku.lightPush, [LightPushCodec]));\n }\n\n if (protocols.includes(Protocols.Filter)) {\n promises.push(waitForConnectedPeer(waku.filter, [FilterCodec]));\n }\n\n if (timeoutMs) {\n await rejectOnTimeout(\n Promise.all(promises),\n timeoutMs,\n \"Timed out waiting for a remote peer.\"\n );\n } else {\n await Promise.all(promises);\n }\n}\n\n/**\n * Wait for a peer with the given protocol to be connected.\n */\nasync function waitForConnectedPeer(\n waku: WakuProtocol,\n codecs: string[]\n): Promise {\n const peers = await waku.peers();\n\n if (peers.length) {\n log(`${codecs} peer found: `, peers[0].id.toString());\n return;\n }\n\n await new Promise((resolve) => {\n const cb = (evt: CustomEvent): void => {\n for (const codec of codecs) {\n if (evt.detail.protocols.includes(codec)) {\n log(\"Resolving for\", codec, evt.detail.protocols);\n waku.libp2p.peerStore.removeEventListener(\"change:protocols\", cb);\n resolve();\n break;\n }\n }\n };\n waku.libp2p.peerStore.addEventListener(\"change:protocols\", cb);\n });\n}\n\n/**\n * Wait for a peer with the given protocol to be connected and in the gossipsub\n * mesh.\n */\nasync function waitForGossipSubPeerInMesh(\n waku: WakuGossipSubProtocol\n): Promise {\n let peers = waku.getMeshPeers();\n\n while (peers.length == 0) {\n await pEvent(waku, \"gossipsub:heartbeat\");\n peers = waku.getMeshPeers();\n }\n}\n\nconst awaitTimeout = (ms: number, rejectReason: string): Promise =>\n new Promise((_resolve, reject) => setTimeout(() => reject(rejectReason), ms));\n\nasync function rejectOnTimeout(\n promise: Promise,\n timeoutMs: number,\n rejectReason: string\n): Promise {\n await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);\n}\n","\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\n","import { concat } from 'uint8arrays'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\ntype Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number, totalLength: number) {\n if (index == null || index < 0 || index >= totalLength) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable {\n private bufs: Uint8Array[]\n public length: number\n\n constructor (...data: Appendable[]) {\n // Define symbol\n Object.defineProperty(this, symbol, { value: true })\n\n this.bufs = []\n this.length = 0\n\n this.appendAll(data)\n }\n\n * [Symbol.iterator] () {\n yield * this.bufs\n }\n\n get byteLength () {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to this Uint8ArrayList\n */\n append (...bufs: Appendable[]) {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.length\n this.bufs = this.bufs.concat(buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number) {\n const res = findBufAndOffset(this.bufs, index, this.length)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number) {\n const res = findBufAndOffset(this.bufs, index, this.length)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n slice (beginInclusive?: number, endExclusive?: number) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n subarray (beginInclusive?: number, endExclusive?: number) {\n const { bufs } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.appendAll(bufs)\n\n return list\n }\n\n _subList (beginInclusive?: number, endExclusive?: number) {\n if (beginInclusive == null && endExclusive == null) {\n return { bufs: this.bufs, length: this.length }\n }\n\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? (this.length > 0 ? this.length : 0)\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (const buf of this.bufs) {\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n const bufInSlice = beginInclusive < bufStart && endExclusive >= bufEnd\n offset = bufEnd\n\n let startIndex: number | undefined\n let endIndex: number | undefined\n\n if (sliceStartInBuf) {\n startIndex = beginInclusive - bufStart\n endIndex = buf.byteLength\n }\n\n if (sliceEndsInBuf) {\n endIndex = endExclusive - bufStart\n\n if (startIndex == null) {\n startIndex = 0\n }\n }\n\n if (bufInSlice) {\n startIndex = 0\n endIndex = buf.byteLength\n }\n\n if (startIndex != null && endIndex != null) {\n bufs.push(buf.subarray(startIndex, endIndex))\n }\n\n if (sliceEndsInBuf) {\n break\n }\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.slice(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = new Uint8Array(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.slice(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = new Uint8Array(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.slice(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = new Uint8Array(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.slice(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = new Uint8Array(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport default function accessor (buf: Uint8Array | Uint8ArrayList) {\n if (buf instanceof Uint8Array) {\n return {\n get (index: number) {\n return buf[index]\n },\n\n set (index: number, value: number) {\n buf[index] = value\n }\n }\n }\n\n return {\n get (index: number) {\n return buf.get(index)\n },\n\n set (index: number, value: number) {\n buf.set(index, value)\n }\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\n\nconst TWO_32 = 4294967296\n\nexport class LongBits {\n public hi: number\n public lo: number\n\n constructor (hi: number = 0, lo: number = 0) {\n this.hi = hi\n this.lo = lo\n }\n\n toBigInt (unsigned: boolean): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n zzDecode () {\n const mask = -(this.lo & 1)\n const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n const hi = (this.hi >>> 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n zzEncode () {\n const mask = this.hi >> 31\n const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n const lo = (this.lo << 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n toBytes (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n const access = accessor(buf)\n\n while (this.hi > 0) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0\n this.hi >>>= 7\n }\n\n while (this.lo > 127) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = this.lo >>> 7\n }\n\n access.set(offset++, this.lo)\n }\n\n static fromBigInt (value: bigint) {\n if (value === 0n) {\n return new LongBits()\n }\n\n const negative = value < 0\n\n if (negative) {\n value = -value\n }\n\n let hi = Number(value >> 32n) | 0\n let lo = Number(value - (BigInt(hi) << 32n)) | 0\n\n if (negative) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > TWO_32) {\n lo = 0\n\n if (++hi > TWO_32) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n static fromNumber (value: number) {\n if (value === 0) {\n return new LongBits()\n }\n\n const sign = value < 0\n\n if (sign) {\n value = -value\n }\n\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > 4294967295) {\n lo = 0\n\n if (++hi > 4294967295) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n static fromBytes (buf: Uint8ArrayList | Uint8Array, offset: number) {\n const access = accessor(buf)\n\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits()\n let i = 0\n\n if (buf.length - offset > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0\n bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0\n if (access.get(offset++) < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 1st..3th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (access.get(offset++) & 127) << i * 7) >>> 0\n return bits\n }\n if (buf.length - offset > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n /* istanbul ignore next */\n throw Error('invalid varint encoding')\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\nimport { LongBits } from './long-bits.js'\n\nconst MSB = 0x80\nconst REST = 0x7F\nconst MSBALL = ~REST\nconst INT = Math.pow(2, 31)\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\nexport const unsigned = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array) {\n let offset = 0\n const access = accessor(buf)\n\n while (value >= INT) {\n access.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n\n while ((value & MSBALL) > 0) {\n access.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n\n access.set(offset, value | 0)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0) {\n const access = accessor(buf)\n let value = 4294967295 // optimizer type-hint, tends to deopt otherwise (?!)\n\n value = (access.get(offset) & 127) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 14) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 21) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 15) << 28) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n if ((offset += 5) > buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n return value\n }\n}\n\nexport const signed = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array) {\n if (value < 0) {\n let offset = 0\n const access = accessor(buf)\n const bits = LongBits.fromNumber(value)\n\n while (bits.hi > 0) {\n access.set(offset++, bits.lo & 127 | 128)\n bits.lo = (bits.lo >>> 7 | bits.hi << 25) >>> 0\n bits.hi >>>= 7\n }\n\n while (bits.lo > 127) {\n access.set(offset++, bits.lo & 127 | 128)\n bits.lo = bits.lo >>> 7\n }\n\n access.set(offset++, bits.lo)\n\n return\n }\n\n unsigned.encode(value, buf)\n },\n\n decode (data: Uint8ArrayList | Uint8Array, offset = 0) {\n return unsigned.decode(data, offset) | 0\n }\n}\n\nexport const zigzag = {\n encodingLength (value: number): number {\n value = (value << 1 ^ value >> 31) >>> 0\n return unsigned.encodingLength(value)\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n value = (value << 1 ^ value >> 31) >>> 0\n return unsigned.encode(value, buf)\n },\n\n decode (data: Uint8ArrayList | Uint8Array, offset = 0) {\n const value = unsigned.decode(data, offset)\n return value >>> 1 ^ -(value & 1) | 0\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from './utils/varint.js'\nimport type { Codec } from './codec.js'\n\nexport function decodeMessage (buf: Uint8Array, codec: Codec) {\n // wrap root message\n const prefix = new Uint8Array(unsigned.encodingLength(buf.length))\n unsigned.encode(buf.length, prefix)\n\n return codec.decode(new Uint8ArrayList(prefix, buf), 0)\n}\n","import type { Codec } from './codec.js'\nimport { unsigned } from './utils/varint.js'\n\nexport function encodeMessage (message: T, codec: Codec) {\n // unwrap root message\n const encoded = codec.encode(message)\n const skip = unsigned.encodingLength(unsigned.decode(encoded))\n\n return encoded.slice(skip)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeFunction {\n (value: T): Uint8Array | Uint8ArrayList\n}\n\nexport interface DecodeFunction {\n (buf: Uint8ArrayList, offset: number): T\n}\n\nexport interface EncodingLengthFunction {\n (value: T): number\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n encodingLength: EncodingLengthFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction, encodingLength: EncodingLengthFunction): Codec {\n return {\n name,\n type,\n encode,\n decode,\n encodingLength\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function boolEncodingLength () {\n return 1\n}\n\nconst encode: EncodeFunction = function boolEncode (value) {\n return Uint8Array.from([value ? 1 : 0])\n}\n\nconst decode: DecodeFunction = function boolDecode (buffer, offset) {\n return buffer.get(offset) > 0\n}\n\nexport const bool = createCodec('bool', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function bytesEncodingLength (val) {\n const len = val.byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function bytesEncode (val) {\n const prefix = new Uint8Array(unsigned.encodingLength(val.byteLength))\n\n unsigned.encode(val.byteLength, prefix)\n\n return new Uint8ArrayList(prefix, val)\n}\n\nconst decode: DecodeFunction = function bytesDecode (buf, offset) {\n const byteLength = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(byteLength)\n\n return buf.slice(offset, offset + byteLength)\n}\n\nexport const bytes = createCodec('bytes', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function doubleEncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function doubleEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setFloat64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function doubleDecode (buf, offset) {\n return buf.getFloat64(offset, true)\n}\n\nexport const double = createCodec('double', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function fixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function fixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function fixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const fixed32 = createCodec('fixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return 8\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const fixed64 = createCodec('fixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function floatEncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function floatEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(1)))\n buf.setFloat32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function floatDecode (buf, offset) {\n return buf.getFloat32(offset, true)\n}\n\nexport const float = createCodec('float', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { signed } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int32EncodingLength (val) {\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int32Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n signed.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int32Decode (buf, offset) {\n return signed.decode(buf, offset)\n}\n\nexport const int32 = createCodec('int32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\nimport { LongBits } from './long-bits.js'\n\nconst LIMIT = 0x7fn\n\n// https://github.com/joeltg/big-varint/blob/main/src/unsigned.ts\nexport const unsigned = {\n encodingLength (value: bigint): number {\n let i = 0\n for (; value >= 0x80n; i++) {\n value >>= 7n\n }\n return i + 1\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array) {\n const access = accessor(buf)\n\n let offset = 0\n while (LIMIT < value) {\n access.set(offset++, Number(value & LIMIT) | 0x80)\n value >>= 7n\n }\n\n access.set(offset, Number(value))\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(true)\n }\n}\n\nexport const signed = {\n encodingLength (value: bigint): number {\n if (value < 0n) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n if (value < 0n) {\n LongBits.fromBigInt(value).toBytes(buf, offset)\n\n return\n }\n\n return unsigned.encode(value, buf)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(false)\n }\n}\n\nexport const zigzag = {\n encodingLength (value: bigint): number {\n return unsigned.encodingLength(value >= 0 ? value * 2n : value * -2n - 1n)\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n LongBits.fromBigInt(value).zzEncode().toBytes(buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).zzDecode().toBigInt(false)\n }\n}\n","import { signed } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n signed.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return signed.decode(buf, offset) | 0n\n}\n\nexport const int64 = createCodec('int64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction, Codec } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { FieldDefs, FieldDef } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (fieldDefs: FieldDefs): Codec {\n const encodingLength: EncodingLengthFunction = function messageEncodingLength (val: Record) {\n let length = 0\n\n for (const fieldDef of Object.values(fieldDefs)) {\n length += fieldDef.codec.encodingLength(val[fieldDef.name])\n }\n\n return unsigned.encodingLength(length) + length\n }\n\n const encode: EncodeFunction> = function messageEncode (val) {\n const bytes = new Uint8ArrayList()\n\n function encodeValue (value: any, fieldNumber: number, fieldDef: FieldDef) {\n if (value == null) {\n if (fieldDef.optional === true) {\n return\n }\n\n throw new Error(`Non optional field \"${fieldDef.name}\" was ${value === null ? 'null' : 'undefined'}`)\n }\n\n const key = (fieldNumber << 3) | fieldDef.codec.type\n const prefix = new Uint8Array(unsigned.encodingLength(key))\n unsigned.encode(key, prefix)\n const encoded = fieldDef.codec.encode(value)\n\n bytes.append(prefix)\n bytes.append(encoded)\n }\n\n for (const [fieldNumberStr, fieldDef] of Object.entries(fieldDefs)) {\n const fieldNumber = parseInt(fieldNumberStr)\n\n if (fieldDef.repeats === true) {\n if (!Array.isArray(val[fieldDef.name])) {\n throw new Error(`Repeating field \"${fieldDef.name}\" was not an array`)\n }\n\n for (const value of val[fieldDef.name]) {\n encodeValue(value, fieldNumber, fieldDef)\n }\n } else {\n encodeValue(val[fieldDef.name], fieldNumber, fieldDef)\n }\n }\n\n const prefix = new Uint8Array(unsigned.encodingLength(bytes.length))\n unsigned.encode(bytes.length, prefix)\n\n return new Uint8ArrayList(prefix, bytes)\n }\n\n const decode: DecodeFunction = function messageDecode (buffer, offset) {\n const length = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(length)\n const end = offset + length\n const fields: any = {}\n\n while (offset < end) {\n const key = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(key)\n\n const wireType = key & 0x7\n const fieldNumber = key >> 3\n const fieldDef = fieldDefs[fieldNumber]\n let fieldLength = 0\n\n if (wireType === CODEC_TYPES.VARINT) {\n if (fieldDef != null) {\n // use the codec if it is available as this could be a bigint\n const value = fieldDef.codec.decode(buffer, offset)\n fieldLength = fieldDef.codec.encodingLength(value)\n } else {\n const value = unsigned.decode(buffer, offset)\n fieldLength = unsigned.encodingLength(value)\n }\n } else if (wireType === CODEC_TYPES.BIT64) {\n fieldLength = 8\n } else if (wireType === CODEC_TYPES.LENGTH_DELIMITED) {\n const valueLength = unsigned.decode(buffer, offset)\n fieldLength = valueLength + unsigned.encodingLength(valueLength)\n } else if (wireType === CODEC_TYPES.BIT32) {\n fieldLength = 4\n } else if (wireType === CODEC_TYPES.START_GROUP) {\n throw new Error('Unsupported wire type START_GROUP')\n } else if (wireType === CODEC_TYPES.END_GROUP) {\n throw new Error('Unsupported wire type END_GROUP')\n }\n\n if (fieldDef != null) {\n const value = fieldDef.codec.decode(buffer, offset)\n\n if (fieldDef.repeats === true) {\n if (fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n\n fields[fieldDef.name].push(value)\n } else {\n fields[fieldDef.name] = value\n }\n }\n\n offset += fieldLength\n }\n\n // make sure repeated fields have an array if not set\n for (const fieldDef of Object.values(fieldDefs)) {\n if (fieldDef.repeats === true && fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n }\n\n return fields\n }\n\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function sfixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const sfixed32 = createCodec('sfixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed64EncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function sfixed64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const sfixed64 = createCodec('sfixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { zigzag } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sint32EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function svarintEncode (val) {\n const buf = new Uint8Array(encodingLength(val))\n\n zigzag.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function svarintDecode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint32 = createCodec('sint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { zigzag } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n zigzag.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint64 = createCodec('sint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint32EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint32Encode (val) {\n // val = val < 0 ? val + 4294967296 : val\n\n const buf = new Uint8Array(encodingLength(val))\n\n unsigned.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function uint32Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n\n // return value > 2147483647 ? value - 4294967296 : value\n}\n\nexport const uint32 = createCodec('uint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\n\nconst encodingLength: EncodingLengthFunction = function stringEncodingLength (val) {\n const len = uint8ArrayFromString(val).byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function stringEncode (val) {\n const asBuf = uint8ArrayFromString(val)\n const prefix = new Uint8Array(unsigned.encodingLength(asBuf.byteLength))\n\n unsigned.encode(asBuf.length, prefix)\n\n return new Uint8ArrayList(prefix, asBuf)\n}\n\nconst decode: DecodeFunction = function stringDecode (buf, offset) {\n const strLen = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(strLen)\n\n return uint8ArrayToString(buf.slice(offset, offset + strLen))\n}\n\nexport const string = createCodec('string', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { unsigned } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint64EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint64Encode (val) {\n const buf = new Uint8Array(unsigned.encodingLength(val))\n\n unsigned.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function uint64Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n}\n\nexport const uint64 = createCodec('uint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, bytes } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n export const codec = (): Codec => {\n return message({\n 1: { name: 'publicKey', codec: bytes },\n 2: { name: 'payloadType', codec: bytes },\n 3: { name: 'payload', codec: bytes },\n 5: { name: 'signature', codec: bytes }\n })\n }\n\n export const encode = (obj: Envelope): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\n","import errCode from 'err-code'\nimport { concat as uint8arraysConcat } from 'uint8arrays/concat'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport varint from 'varint'\nimport { equals as uint8arraysEquals } from 'uint8arrays/equals'\nimport { codes } from '../errors.js'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\n\nexport interface EnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array) => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\n }\n\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record: Record, peerId: PeerId) => {\n const domain = record.domain\n const payloadType = record.codec\n const payload = record.marshal()\n\n const signData = formatSignaturePayload(domain, payloadType, payload)\n\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\n\n const key = await unmarshalPrivateKey(peerId.privateKey)\n const signature = await key.sign(signData)\n\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\n }\n\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data: Uint8Array, domain: string) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw errCode(new Error('envelope signature is not valid for the given domain'), codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: EnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal () {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload,\n signature: this.signature\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope) {\n return uint8arraysEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return await key.verify(signData, this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array) => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = varint.encode(domainUint8Array.byteLength)\n const payloadTypeLength = varint.encode(payloadType.length)\n const payloadLength = varint.encode(payload.length)\n\n return uint8arraysConcat([\n new Uint8Array(domainLength),\n domainUint8Array,\n new Uint8Array(payloadTypeLength),\n payloadType,\n new Uint8Array(payloadLength),\n payload\n ])\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, bytes, uint64 } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n export const codec = (): Codec => {\n return message({\n 1: { name: 'multiaddr', codec: bytes }\n })\n }\n\n export const encode = (obj: AddressInfo): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n export const codec = (): Codec => {\n return message({\n 1: { name: 'peerId', codec: bytes },\n 2: { name: 'seq', codec: uint64 },\n 3: { name: 'addresses', codec: PeerRecord.AddressInfo.codec(), repeats: true }\n })\n }\n\n export const encode = (obj: PeerRecord): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n","\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1])\n","import { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\n}\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array): PeerRecord => {\n const peerRecord = Protobuf.decode(buf)\n const peerId = peerIdFromBytes(peerRecord.peerId)\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => new Multiaddr(a.multiaddr))\n const seqNumber = peerRecord.seq\n\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\n\n /**\n * Marshal a record to be used in an envelope\n */\n marshal () {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown) {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n","/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals (a: any[], b: any[]) {\n const sort = (a: any, b: any) => a.toString().localeCompare(b.toString())\n return a.length === b.length && b.sort(sort) && a.sort(sort).every((item, index) => b[index].equals(item))\n}\n","import debug from 'debug'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { Key } from 'interface-datastore'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key) => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error: (formatter: any, ...args: any[]) => void\n trace: (formatter: any, ...args: any[]) => void\n enabled: boolean\n}\n\nexport function logger (name: string): Logger {\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace: debug(`${name}:trace`)\n })\n}\n\nexport function disable () {\n debug.disable()\n}\n\nexport function enable (namespaces: string) {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string) {\n return debug.enabled(namespaces)\n}\n","import type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nexport interface IncomingStreamData {\n stream: Stream\n connection: Connection\n}\n\nexport interface StreamHandler {\n (data: IncomingStreamData): void\n}\n\nexport interface StreamHandlerOptions {\n /**\n * How many incoming streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxInboundStreams?: number\n\n /**\n * How many outgoing streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxOutboundStreams?: number\n}\n\nexport interface StreamHandlerRecord {\n handler: StreamHandler\n options: StreamHandlerOptions\n}\n\nexport interface Registrar {\n getProtocols: () => string[]\n handle: (protocol: string, handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n unhandle: (protocol: string) => Promise\n getHandler: (protocol: string) => StreamHandlerRecord\n\n register: (protocol: string, topology: Topology) => Promise\n unregister: (id: string) => void\n getTopologies: (protocol: string) => Topology[]\n}\n\nexport interface onConnectHandler {\n (peerId: PeerId, conn: Connection): void\n}\n\nexport interface onDisconnectHandler {\n (peerId: PeerId, conn?: Connection): void\n}\n\nexport interface TopologyInit {\n /**\n * minimum needed connections\n */\n min?: number\n\n /**\n * maximum needed connections\n */\n max?: number\n onConnect?: onConnectHandler\n onDisconnect?: onDisconnectHandler\n}\n\nexport interface Topology {\n min: number\n max: number\n peers: Set\n\n onConnect: (peerId: PeerId, conn: Connection) => void\n onDisconnect: (peerId: PeerId) => void\n setRegistrar: (registrar: Registrar) => Promise\n}\n\nexport const topologySymbol = Symbol.for('@libp2p/topology')\n\nexport function isTopology (other: any): other is Topology {\n return other != null && Boolean(other[topologySymbol])\n}\n","import { topologySymbol as symbol } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Topology, TopologyInit, onConnectHandler, onDisconnectHandler, Registrar } from '@libp2p/interface-registrar'\n\nconst noop = () => {}\n\nclass TopologyImpl implements Topology {\n public min: number\n public max: number\n\n /**\n * Set of peers that support the protocol\n */\n public peers: Set\n public onConnect: onConnectHandler\n public onDisconnect: onDisconnectHandler\n\n protected registrar: Registrar | undefined\n\n constructor (init: TopologyInit) {\n this.min = init.min ?? 0\n this.max = init.max ?? Infinity\n this.peers = new Set()\n\n this.onConnect = init.onConnect ?? noop\n this.onDisconnect = init.onDisconnect ?? noop\n }\n\n get [Symbol.toStringTag] () {\n return symbol.toString()\n }\n\n get [symbol] () {\n return true\n }\n\n async setRegistrar (registrar: Registrar) {\n this.registrar = registrar\n }\n\n /**\n * Notify about peer disconnected event\n */\n disconnect (peerId: PeerId) {\n this.onDisconnect(peerId)\n }\n}\n\nexport function createTopology (init: TopologyInit): Topology {\n return new TopologyImpl(init)\n}\n","\nexport interface EventCallback { (evt: EventType): void }\nexport interface EventObject { handleEvent: EventCallback }\nexport type EventHandler = EventCallback | EventObject\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n * Adds types to the EventTarget class. Hopefully this won't be necessary forever.\n *\n * https://github.com/microsoft/TypeScript/issues/28357\n * https://github.com/microsoft/TypeScript/issues/43477\n * https://github.com/microsoft/TypeScript/issues/299\n * etc\n */\nexport class EventEmitter extends EventTarget {\n #listeners: Map = new Map()\n\n listenerCount (type: string) {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n}\n\n/**\n * CustomEvent is a standard event but it's not supported by node.\n *\n * Remove this when https://github.com/nodejs/node/issues/40678 is closed.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n */\nclass CustomEventPolyfill extends Event {\n /** Returns any custom data event was created with. Typically used for synthetic events. */\n public detail: T\n\n constructor (message: string, data?: EventInit & { detail: T }) {\n super(message, data)\n // @ts-expect-error could be undefined\n this.detail = data?.detail\n }\n}\n\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill\n",null,null,null,null,null,null,"import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Pushable } from 'it-pushable'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Stream } from '@libp2p/interface-connection'\n\n/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nexport const StrictSign = 'StrictSign'\n\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nexport const StrictNoSign = 'StrictNoSign'\n\nexport type SignaturePolicy = typeof StrictSign | typeof StrictNoSign\n\nexport interface Message {\n from: PeerId\n topic: string\n data: Uint8Array\n sequenceNumber?: bigint\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCMessage {\n from?: Uint8Array\n topic?: string\n data?: Uint8Array\n sequenceNumber?: Uint8Array\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCSubscription {\n subscribe?: boolean\n topic?: string\n}\n\nexport interface PubSubRPC {\n subscriptions: PubSubRPCSubscription[]\n messages: PubSubRPCMessage[]\n}\n\nexport interface PeerStreams extends EventEmitter {\n id: PeerId\n protocol: string\n outboundStream?: Pushable\n inboundStream?: AsyncIterable\n isWritable: boolean\n\n close: () => void\n write: (buf: Uint8Array) => void\n attachInboundStream: (stream: Stream) => AsyncIterable\n attachOutboundStream: (stream: Stream) => Promise>\n}\n\nexport interface PubSubInit {\n enabled?: boolean\n\n multicodecs?: string[]\n\n /**\n * defines how signatures should be handled\n */\n globalSignaturePolicy?: SignaturePolicy\n\n /**\n * if can relay messages not subscribed\n */\n canRelayMessage?: boolean\n\n /**\n * if publish should emit to self, if subscribed\n */\n emitSelf?: boolean\n\n /**\n * handle this many incoming pubsub messages concurrently\n */\n messageProcessingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the pubsub protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the pubsub protocol per-connection\n */\n maxOutboundStreams?: number\n}\n\ninterface Subscription {\n topic: string\n subscribe: boolean\n}\n\nexport interface SubscriptionChangeData {\n peerId: PeerId\n subscriptions: Subscription[]\n}\n\nexport interface PubSubEvents {\n 'subscription-change': CustomEvent\n 'message': CustomEvent\n}\n\nexport interface PublishResult {\n recipients: PeerId[]\n}\n\nexport interface PubSub extends EventEmitter {\n globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n multicodecs: string[]\n\n getPeers: () => PeerId[]\n getTopics: () => string[]\n subscribe: (topic: string) => void\n unsubscribe: (topic: string) => void\n getSubscribers: (topic: string) => PeerId[]\n publish: (topic: string, data: Uint8Array) => Promise\n}\n\nexport interface PeerStreamEvents {\n 'stream:inbound': CustomEvent\n 'stream:outbound': CustomEvent\n 'close': CustomEvent\n}\n",null,null,null,null,null,null,"\n/**\n * Implemented by components that have a lifecycle\n */\nexport interface Startable {\n isStarted: () => boolean\n\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?: () => void | Promise\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?: () => void | Promise\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?: () => void | Promise\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?: () => void | Promise\n}\n\nexport function isStartable (obj: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\nexport async function start (...objs: any[]) {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\nexport async function stop (...objs: any[]) {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n","import errCode from 'err-code'\nimport type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport { isStartable, Startable } from '@libp2p/interfaces/startable'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport type { TransportManager, Upgrader } from '@libp2p/interface-transport'\nimport type { Datastore } from 'interface-datastore'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nexport interface Initializable {\n init: (components: Components) => void\n}\n\nexport function isInitializable (obj: any): obj is Initializable {\n return obj != null && typeof obj.init === 'function'\n}\n\nexport interface ComponentsInit {\n peerId?: PeerId\n addressManager?: AddressManager\n peerStore?: PeerStore\n upgrader?: Upgrader\n metrics?: Metrics\n registrar?: Registrar\n connectionManager?: ConnectionManager\n transportManager?: TransportManager\n connectionGater?: ConnectionGater\n contentRouting?: ContentRouting\n peerRouting?: PeerRouting\n datastore?: Datastore\n connectionProtector?: ConnectionProtector\n dht?: DualDHT\n pubsub?: PubSub\n}\n\nexport class Components implements Startable {\n private peerId?: PeerId\n private addressManager?: AddressManager\n private peerStore?: PeerStore\n private upgrader?: Upgrader\n private metrics?: Metrics\n private registrar?: Registrar\n private connectionManager?: ConnectionManager\n private transportManager?: TransportManager\n private connectionGater?: ConnectionGater\n private contentRouting?: ContentRouting\n private peerRouting?: PeerRouting\n private datastore?: Datastore\n private connectionProtector?: ConnectionProtector\n private dht?: DualDHT\n private pubsub?: PubSub\n private started = false\n\n constructor (init: ComponentsInit = {}) {\n if (init.peerId != null) {\n this.setPeerId(init.peerId)\n }\n\n if (init.addressManager != null) {\n this.setAddressManager(init.addressManager)\n }\n\n if (init.peerStore != null) {\n this.setPeerStore(init.peerStore)\n }\n\n if (init.upgrader != null) {\n this.setUpgrader(init.upgrader)\n }\n\n if (init.metrics != null) {\n this.setMetrics(init.metrics)\n }\n\n if (init.registrar != null) {\n this.setRegistrar(init.registrar)\n }\n\n if (init.connectionManager != null) {\n this.setConnectionManager(init.connectionManager)\n }\n\n if (init.transportManager != null) {\n this.setTransportManager(init.transportManager)\n }\n\n if (init.connectionGater != null) {\n this.setConnectionGater(init.connectionGater)\n }\n\n if (init.contentRouting != null) {\n this.setContentRouting(init.contentRouting)\n }\n\n if (init.peerRouting != null) {\n this.setPeerRouting(init.peerRouting)\n }\n\n if (init.datastore != null) {\n this.setDatastore(init.datastore)\n }\n\n if (init.connectionProtector != null) {\n this.setConnectionProtector(init.connectionProtector)\n }\n\n if (init.dht != null) {\n this.setDHT(init.dht)\n }\n\n if (init.pubsub != null) {\n this.setPubSub(init.pubsub)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async beforeStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStart != null) {\n await startable.beforeStart()\n }\n })\n )\n }\n\n async start () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.start()\n })\n )\n\n this.started = true\n }\n\n async afterStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStart != null) {\n await startable.afterStart()\n }\n })\n )\n }\n\n async beforeStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStop != null) {\n await startable.beforeStop()\n }\n })\n )\n }\n\n async stop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.stop()\n })\n )\n\n this.started = false\n }\n\n async afterStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStop != null) {\n await startable.afterStop()\n }\n })\n )\n }\n\n setPeerId (peerId: PeerId) {\n this.peerId = peerId\n\n return peerId\n }\n\n getPeerId (): PeerId {\n if (this.peerId == null) {\n throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerId\n }\n\n setMetrics (metrics: Metrics) {\n this.metrics = metrics\n\n if (isInitializable(metrics)) {\n metrics.init(this)\n }\n\n return metrics\n }\n\n getMetrics (): Metrics | undefined {\n return this.metrics\n }\n\n setAddressManager (addressManager: AddressManager) {\n this.addressManager = addressManager\n\n if (isInitializable(addressManager)) {\n addressManager.init(this)\n }\n\n return addressManager\n }\n\n getAddressManager (): AddressManager {\n if (this.addressManager == null) {\n throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.addressManager\n }\n\n setPeerStore (peerStore: PeerStore) {\n this.peerStore = peerStore\n\n if (isInitializable(peerStore)) {\n peerStore.init(this)\n }\n\n return peerStore\n }\n\n getPeerStore (): PeerStore {\n if (this.peerStore == null) {\n throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerStore\n }\n\n setUpgrader (upgrader: Upgrader) {\n this.upgrader = upgrader\n\n if (isInitializable(upgrader)) {\n upgrader.init(this)\n }\n\n return upgrader\n }\n\n getUpgrader (): Upgrader {\n if (this.upgrader == null) {\n throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.upgrader\n }\n\n setRegistrar (registrar: Registrar) {\n this.registrar = registrar\n\n if (isInitializable(registrar)) {\n registrar.init(this)\n }\n\n return registrar\n }\n\n getRegistrar (): Registrar {\n if (this.registrar == null) {\n throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.registrar\n }\n\n setConnectionManager (connectionManager: ConnectionManager) {\n this.connectionManager = connectionManager\n\n if (isInitializable(connectionManager)) {\n connectionManager.init(this)\n }\n\n return connectionManager\n }\n\n getConnectionManager (): ConnectionManager {\n if (this.connectionManager == null) {\n throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.connectionManager\n }\n\n setTransportManager (transportManager: TransportManager) {\n this.transportManager = transportManager\n\n if (isInitializable(transportManager)) {\n transportManager.init(this)\n }\n\n return transportManager\n }\n\n getTransportManager (): TransportManager {\n if (this.transportManager == null) {\n throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.transportManager\n }\n\n setConnectionGater (connectionGater: ConnectionGater) {\n this.connectionGater = connectionGater\n\n if (isInitializable(connectionGater)) {\n connectionGater.init(this)\n }\n\n return connectionGater\n }\n\n getConnectionGater (): ConnectionGater {\n if (this.connectionGater == null) {\n throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.connectionGater\n }\n\n setContentRouting (contentRouting: ContentRouting) {\n this.contentRouting = contentRouting\n\n if (isInitializable(contentRouting)) {\n contentRouting.init(this)\n }\n\n return contentRouting\n }\n\n getContentRouting (): ContentRouting {\n if (this.contentRouting == null) {\n throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.contentRouting\n }\n\n setPeerRouting (peerRouting: PeerRouting) {\n this.peerRouting = peerRouting\n\n if (isInitializable(peerRouting)) {\n peerRouting.init(this)\n }\n\n return peerRouting\n }\n\n getPeerRouting (): PeerRouting {\n if (this.peerRouting == null) {\n throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerRouting\n }\n\n setDatastore (datastore: Datastore) {\n this.datastore = datastore\n\n if (isInitializable(datastore)) {\n datastore.init(this)\n }\n\n return datastore\n }\n\n getDatastore (): Datastore {\n if (this.datastore == null) {\n throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.datastore\n }\n\n setConnectionProtector (connectionProtector: ConnectionProtector) {\n this.connectionProtector = connectionProtector\n\n if (isInitializable(connectionProtector)) {\n connectionProtector.init(this)\n }\n\n return connectionProtector\n }\n\n getConnectionProtector (): ConnectionProtector | undefined {\n return this.connectionProtector\n }\n\n setDHT (dht: DualDHT) {\n this.dht = dht\n\n if (isInitializable(dht)) {\n dht.init(this)\n }\n\n return dht\n }\n\n getDHT (): DualDHT {\n if (this.dht == null) {\n throw errCode(new Error('dht not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.dht\n }\n\n setPubSub (pubsub: PubSub) {\n this.pubsub = pubsub\n\n if (isInitializable(pubsub)) {\n pubsub.init(this)\n }\n\n return pubsub\n }\n\n getPubSub (): PubSub {\n if (this.pubsub == null) {\n throw errCode(new Error('pubsub not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.pubsub\n }\n}\n",null,null,null,null,"// @ts-expect-error types are missing\nimport forgePbkdf2 from 'node-forge/lib/pbkdf2.js'\n// @ts-expect-error types are missing\nimport forgeUtil from 'node-forge/lib/util.js'\nimport errcode from 'err-code'\n\n/**\n * Maps an IPFS hash name to its node-forge equivalent.\n *\n * See https://github.com/multiformats/multihash/blob/master/hashtable.csv\n *\n * @private\n */\nconst hashName = {\n sha1: 'sha1',\n 'sha2-256': 'sha256',\n 'sha2-512': 'sha512'\n}\n\n/**\n * Computes the Password-Based Key Derivation Function 2.\n */\nexport default function pbkdf2 (password: string, salt: string, iterations: number, keySize: number, hash: string): string {\n if (hash !== 'sha1' && hash !== 'sha2-256' && hash !== 'sha2-512') {\n const types = Object.keys(hashName).join(' / ')\n throw errcode(new Error(`Hash '${hash}' is unknown or not supported. Must be ${types}`), 'ERR_UNSUPPORTED_HASH_TYPE')\n }\n\n const hasher = hashName[hash]\n const dek = forgePbkdf2(\n password,\n salt,\n iterations,\n keySize,\n hasher\n )\n\n return forgeUtil.encode64(dek, null)\n}\n",null,null,"import { randomBytes } from '@libp2p/crypto'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport type { Message, PubSubRPCMessage } from '@libp2p/interface-pubsub'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { codes } from './errors.js'\nimport errcode from 'err-code'\n\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno (): bigint {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`)\n}\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key: Uint8Array, seqno: bigint) => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16')\n\n const msgId = new Uint8Array(key.length + seqnoBytes.length)\n msgId.set(key, 0)\n msgId.set(seqnoBytes, key.length)\n\n return msgId\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data: Uint8Array) => {\n return sha256.encode(data)\n}\n\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a: Set | number[], b: Set | number[]) => {\n let bHas\n if (Array.isArray(b)) {\n bHas = (val: number) => b.includes(val)\n } else {\n bHas = (val: number) => b.has(val)\n }\n\n for (const val of a) {\n if (bHas(val)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Make everything an array\n */\nexport const ensureArray = function (maybeArray: T | T[]) {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray]\n }\n\n return maybeArray\n}\n\nexport const toMessage = (message: PubSubRPCMessage): Message => {\n if (message.from == null) {\n throw errcode(new Error('RPC message was missing from'), codes.ERR_MISSING_FROM)\n }\n\n if (message.sequenceNumber == null || message.from == null || message.signature == null || message.key == null) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n }\n }\n\n return {\n type: 'signed',\n from: peerIdFromBytes(message.from),\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature,\n key: message.key\n }\n}\n\nexport const toRpcMessage = (message: Message): PubSubRPCMessage => {\n if (message.type === 'signed') {\n return {\n from: message.from.multihash.bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n key: message.key\n }\n }\n\n return {\n data: message.data,\n topic: message.topic\n }\n}\n\nexport const bigIntToBytes = (num: bigint): Uint8Array => {\n let str = num.toString(16)\n\n if (str.length % 2 !== 0) {\n str = `0${str}`\n }\n\n return uint8ArrayFromString(str, 'base16')\n}\n\nexport const bigIntFromBytes = (num: Uint8Array): bigint => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`)\n}\n",null,null,"\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n","import { AbortError } from './abort-error.js'\nimport { getIterator } from 'get-iterator'\nimport type { Duplex, Source, Sink } from 'it-stream-types'\n\nexport interface Options {\n onReturnError?: (err: Error) => void\n onAbort?: (source: Source) => void\n abortMessage?: string\n abortCode?: string\n returnOnAbort?: boolean\n}\n\n// Wrap an iterator to make it abortable, allow cleanup when aborted via onAbort\nexport function abortableSource (source: Source, signal: AbortSignal, options?: Options) {\n const opts: Options = options ?? {}\n const iterator = getIterator(source)\n\n async function * abortable () {\n let nextAbortHandler: (() => void) | null\n const abortHandler = () => {\n if (nextAbortHandler != null) nextAbortHandler()\n }\n\n signal.addEventListener('abort', abortHandler)\n\n while (true) {\n let result: IteratorResult\n try {\n if (signal.aborted) {\n const { abortMessage, abortCode } = opts\n throw new AbortError(abortMessage, abortCode)\n }\n\n const abort = new Promise((resolve, reject) => { // eslint-disable-line no-loop-func\n nextAbortHandler = () => {\n const { abortMessage, abortCode } = opts\n reject(new AbortError(abortMessage, abortCode))\n }\n })\n\n // Race the iterator and the abort signals\n result = await Promise.race([abort, iterator.next()])\n nextAbortHandler = null\n } catch (err: any) {\n signal.removeEventListener('abort', abortHandler)\n\n // Might not have been aborted by a known signal\n const isKnownAborter = err.type === 'aborted' && signal.aborted\n\n if (isKnownAborter && (opts.onAbort != null)) {\n // Do any custom abort handling for the iterator\n await opts.onAbort(source)\n }\n\n // End the iterator if it is a generator\n if (typeof iterator.return === 'function') {\n try {\n const p = iterator.return()\n\n if (p instanceof Promise) { // eslint-disable-line max-depth\n p.catch(err => {\n if (opts.onReturnError != null) {\n opts.onReturnError(err)\n }\n })\n }\n } catch (err: any) {\n if (opts.onReturnError != null) { // eslint-disable-line max-depth\n opts.onReturnError(err)\n }\n }\n }\n\n if (isKnownAborter && opts.returnOnAbort === true) {\n return\n }\n\n throw err\n }\n\n if (result.done === true) {\n break\n }\n\n yield result.value\n }\n\n signal.removeEventListener('abort', abortHandler)\n }\n\n return abortable()\n}\n\nexport function abortableSink (sink: Sink, signal: AbortSignal, options?: Options): Sink {\n return (source: Source) => sink(abortableSource(source, signal, options))\n}\n\nexport function abortableDuplex > (duplex: Duplex, signal: AbortSignal, options?: Options) {\n return {\n sink: abortableSink(duplex.sink, signal, {\n ...options,\n onAbort: undefined\n }),\n source: abortableSource(duplex.source, signal, options)\n }\n}\n\nexport { AbortError }\nexport { abortableSink as abortableTransform }\n","\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator (obj: AsyncIterable): AsyncIterator\nexport function getIterator (obj: AsyncIterator): AsyncIterator\nexport function getIterator (obj: Iterable): Iterator\nexport function getIterator (obj: Iterator): Iterator\nexport function getIterator (obj: any): AsyncIterator | Iterator \nexport function getIterator (obj: any): AsyncIterator | Iterator {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]()\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]()\n }\n if (typeof obj.next === 'function') {\n return obj // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable')\n}\n","import { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\ntype Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number) {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable {\n private bufs: Uint8Array[]\n public length: number\n\n constructor (...data: Appendable[]) {\n // Define symbol\n Object.defineProperty(this, symbol, { value: true })\n\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] () {\n yield * this.bufs\n }\n\n get byteLength () {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]) {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]) {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number) {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number) {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = bufs\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number) {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: [...this.bufs], length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport default function accessor (buf: Uint8Array | Uint8ArrayList) {\n if (buf instanceof Uint8Array) {\n return {\n get (index: number) {\n return buf[index]\n },\n\n set (index: number, value: number) {\n buf[index] = value\n }\n }\n }\n\n return {\n get (index: number) {\n return buf.get(index)\n },\n\n set (index: number, value: number) {\n buf.set(index, value)\n }\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from 'byte-access'\n\nconst TWO_32 = 4294967296\n\nexport class LongBits {\n public hi: number\n public lo: number\n\n constructor (hi: number = 0, lo: number = 0) {\n this.hi = hi\n this.lo = lo\n }\n\n /**\n * Returns these hi/lo bits as a BigInt\n */\n toBigInt (unsigned?: boolean): bigint {\n if (unsigned === true) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Returns these hi/lo bits as a Number - this may overflow, toBigInt\n * should be preferred\n */\n toNumber (unsigned?: boolean): number {\n return Number(this.toBigInt(unsigned))\n }\n\n /**\n * ZigZag decode a LongBits object\n */\n zzDecode () {\n const mask = -(this.lo & 1)\n const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n const hi = (this.hi >>> 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n /**\n * ZigZag encode a LongBits object\n */\n zzEncode () {\n const mask = this.hi >> 31\n const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n const lo = (this.lo << 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Encode a LongBits object as a varint byte array\n */\n toBytes (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n const access = accessor(buf)\n\n while (this.hi > 0) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0\n this.hi >>>= 7\n }\n\n while (this.lo > 127) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = this.lo >>> 7\n }\n\n access.set(offset++, this.lo)\n }\n\n /**\n * Parse a LongBits object from a BigInt\n */\n static fromBigInt (value: bigint) {\n if (value === 0n) {\n return new LongBits()\n }\n\n const negative = value < 0\n\n if (negative) {\n value = -value\n }\n\n let hi = Number(value >> 32n) | 0\n let lo = Number(value - (BigInt(hi) << 32n)) | 0\n\n if (negative) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > TWO_32) {\n lo = 0\n\n if (++hi > TWO_32) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Parse a LongBits object from a Number\n */\n static fromNumber (value: number) {\n if (value === 0) {\n return new LongBits()\n }\n\n const sign = value < 0\n\n if (sign) {\n value = -value\n }\n\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > 4294967295) {\n lo = 0\n\n if (++hi > 4294967295) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Parse a LongBits object from a varint byte array\n */\n static fromBytes (buf: Uint8ArrayList | Uint8Array, offset: number = 0) {\n const access = accessor(buf)\n\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits()\n let i = 0\n\n if (buf.length - offset > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n\n // 5th\n bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0\n bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n\n i = 0\n } else {\n for (; i < 4; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n if (buf.length - offset > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n } else if (offset < buf.byteLength) {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n /* istanbul ignore next */\n throw RangeError('invalid varint encoding')\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport { LongBits } from 'longbits'\nimport { allocUnsafe } from 'uint8arrays/alloc'\n\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\ninterface VarintCodec {\n encodingLength: (value: number) => number\n encode: ((value: number) => Uint8Array) & ((value: number, buf: Uint8Array, offset?: number) => Uint8Array) & ((value: number, buf: Uint8ArrayList, offset?: number) => Uint8ArrayList)\n decode: (buf: Uint8ArrayList | Uint8Array, offset?: number) => number\n}\n\nexport const unsigned: VarintCodec = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf?: any, offset: number = 0) {\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n if (buf == null) {\n buf = allocUnsafe(unsigned.encodingLength(value))\n }\n\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(true)\n }\n}\n\nexport const signed: VarintCodec = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(signed.encodingLength(value))\n }\n\n if (value < 0) {\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n }\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(false)\n }\n}\n\nexport const zigzag: VarintCodec = {\n encodingLength (value: number): number {\n return unsigned.encodingLength(value >= 0 ? value * 2 : value * -2 - 1)\n },\n\n // @ts-expect-error\n encode (value: any, buf?: any, offset?: any) {\n value = value >= 0 ? value * 2 : (value * -2) - 1\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n const value = unsigned.decode(buf, offset)\n\n return (value & 1) !== 0 ? (value + 1) / -2 : value / 2\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport type { LengthEncoderFunction } from './index.js'\nimport type { Source, Transform } from 'it-stream-types'\nimport { allocUnsafe } from './alloc.js'\n\ninterface EncoderOptions {\n lengthEncoder?: LengthEncoderFunction\n}\n\nconst defaultEncoder: LengthEncoderFunction = (length) => {\n const lengthLength = unsigned.encodingLength(length)\n const lengthBuf = allocUnsafe(lengthLength)\n\n unsigned.encode(length, lengthBuf)\n\n defaultEncoder.bytes = lengthLength\n\n return lengthBuf\n}\ndefaultEncoder.bytes = 0\n\nexport function encode (options?: EncoderOptions): Transform {\n options = options ?? {}\n\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n const encoder = async function * (source: Source): Source {\n for await (const chunk of source) {\n // length + data\n const length = encodeLength(chunk.byteLength)\n\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length\n } else {\n yield * length\n }\n\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk\n } else {\n yield * chunk\n }\n }\n }\n\n return encoder\n}\n\nencode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {\n options = options ?? {}\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n return new Uint8ArrayList(\n encodeLength(chunk.byteLength),\n chunk\n )\n}\n","\nexport function alloc (len: number) {\n return new Uint8Array(len)\n}\n\nexport function allocUnsafe (len: number) {\n if (globalThis?.Buffer?.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n","/* eslint max-depth: [\"error\", 6] */\n\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport errCode from 'err-code'\nimport type { LengthDecoderFunction } from './index.js'\nimport type { Reader } from 'it-reader'\nimport type { Source, Transform } from 'it-stream-types'\n\nexport interface ReadState {\n dataLength: number\n}\n\nexport interface DecoderOptions {\n lengthDecoder?: LengthDecoderFunction\n onData?: (data: Uint8ArrayList) => void\n onLength?: (length: number) => void\n maxLengthLength?: number\n maxDataLength?: number\n}\n\nexport interface ReadResult {\n mode: string\n chunk?: Uint8ArrayList\n buffer: Uint8ArrayList\n state?: ReadState\n data?: Uint8ArrayList\n}\n\n// Maximum length of the length section of the message\nexport const MAX_LENGTH_LENGTH = 8 // Varint.encode(Number.MAX_SAFE_INTEGER).length\n// Maximum length of the data section of the message\nexport const MAX_DATA_LENGTH = 1024 * 1024 * 4\n\nenum ReadMode {\n LENGTH,\n DATA\n}\n\nconst defaultDecoder: LengthDecoderFunction = (buf) => {\n const length = unsigned.decode(buf)\n defaultDecoder.bytes = unsigned.encodingLength(length)\n\n return length\n}\ndefaultDecoder.bytes = 0\n\nexport function decode (options?: DecoderOptions): Transform {\n const decoder = async function * (source: Source): Source {\n const buffer = new Uint8ArrayList()\n let mode = ReadMode.LENGTH\n let dataLength = -1\n\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n for await (const buf of source) {\n buffer.append(buf)\n\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer)\n\n if (dataLength < 0) {\n throw errCode(new Error('invalid message length'), 'ERR_INVALID_MSG_LENGTH')\n }\n\n if (dataLength > maxDataLength) {\n throw errCode(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG')\n }\n\n const dataLengthLength = lengthDecoder.bytes\n buffer.consume(dataLengthLength)\n\n if (options?.onLength != null) {\n options.onLength(dataLength)\n }\n\n mode = ReadMode.DATA\n } catch (err: any) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw errCode(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG')\n }\n\n break\n }\n\n throw err\n }\n }\n\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break\n }\n\n const data = buffer.sublist(0, dataLength)\n buffer.consume(dataLength)\n\n if (options?.onData != null) {\n options.onData(data)\n }\n\n yield data\n\n mode = ReadMode.LENGTH\n }\n }\n }\n\n if (buffer.byteLength > 0) {\n throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF')\n }\n }\n\n return decoder\n}\n\n/**\n * @param {*} reader\n * @param {import('./types').DecoderOptions} [options]\n * @returns\n */\ndecode.fromReader = (reader: Reader, options?: DecoderOptions) => {\n let byteLength = 1 // Read single byte chunks until the length is known\n\n const varByteSource = (async function * () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength)\n\n if (done === true) {\n return\n }\n\n if (value != null) {\n yield value\n }\n } catch (err: any) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null }\n }\n throw err\n } finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1\n }\n }\n }())\n\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l: number) => { byteLength = l }\n return decode({\n ...(options ?? {}),\n onLength\n })(varByteSource)\n}\n",null,null,null,"import {\n GossipSub,\n GossipsubMessage,\n GossipsubOpts,\n} from \"@chainsafe/libp2p-gossipsub\";\nimport {\n PeerIdStr,\n TopicStr,\n} from \"@chainsafe/libp2p-gossipsub/dist/src/types\";\nimport { SignaturePolicy } from \"@chainsafe/libp2p-gossipsub/types\";\nimport debug from \"debug\";\n\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport * as constants from \"./constants\";\n\nconst dbg = debug(\"waku:relay\");\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * One and only one pubsub topic is used by Waku. This is used by:\n * - WakuRelay to receive, route and send messages,\n * - WakuLightPush to send messages,\n * - WakuStore to retrieve messages.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n decryptionKeys?: Array;\n}\n\n/**\n * Implements the [Waku v2 Relay protocol]{@link https://rfc.vac.dev/spec/11/}.\n * Must be passed as a `pubsub` module to a {Libp2p} instance.\n *\n * @implements {require('libp2p-interfaces/src/pubsub')}\n * @noInheritDoc\n */\nexport class WakuRelay extends GossipSub {\n pubSubTopic: string;\n public static multicodec: string = constants.RelayCodecs[0];\n\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n /**\n * observers called when receiving new message.\n * Observers under key `\"\"` are always called.\n */\n public observers: {\n [contentTopic: string]: Set<(message: WakuMessage) => void>;\n };\n\n constructor(options?: Partial) {\n options = Object.assign(options ?? {}, {\n // Ensure that no signature is included nor expected in the messages.\n globalSignaturePolicy: SignaturePolicy.StrictNoSign,\n fallbackToFloodsub: false,\n });\n super(options);\n this.multicodecs = constants.RelayCodecs;\n\n this.observers = {};\n this.decryptionKeys = new Map();\n\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n\n options?.decryptionKeys?.forEach((key) => {\n this.addDecryptionKey(key);\n });\n }\n\n /**\n * Mounts the gossipsub protocol onto the libp2p node\n * and subscribes to the default topic.\n *\n * @override\n * @returns {void}\n */\n public async start(): Promise {\n await super.start();\n this.subscribe(this.pubSubTopic);\n }\n\n /**\n * Send Waku message.\n *\n * @param {WakuMessage} message\n * @returns {Promise}\n */\n public async send(message: WakuMessage): Promise {\n const msg = message.encode();\n await this.publish(this.pubSubTopic, msg);\n }\n\n /**\n * Register a decryption key to attempt decryption of received messages.\n * This can either be a private key for asymmetric encryption or a symmetric\n * key. `WakuRelay` will attempt to decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**\n * Delete a decryption key that was used to attempt decryption of received\n * messages.\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n /**\n * Register an observer of new messages received via waku relay\n *\n * @param callback called when a new message is received via waku relay\n * @param contentTopics Content Topics for which the callback with be called,\n * all of them if undefined, [] or [\"\",..] is passed.\n * @returns {void}\n */\n addObserver(\n callback: (message: WakuMessage) => void,\n contentTopics: string[] = []\n ): void {\n if (contentTopics.length === 0) {\n if (!this.observers[\"\"]) {\n this.observers[\"\"] = new Set();\n }\n this.observers[\"\"].add(callback);\n } else {\n contentTopics.forEach((contentTopic) => {\n if (!this.observers[contentTopic]) {\n this.observers[contentTopic] = new Set();\n }\n this.observers[contentTopic].add(callback);\n });\n }\n }\n\n /**\n * Remove an observer of new messages received via waku relay.\n * Useful to ensure the same observer is not registered several time\n * (e.g when loading React components)\n */\n deleteObserver(\n callback: (message: WakuMessage) => void,\n contentTopics: string[] = []\n ): void {\n if (contentTopics.length === 0) {\n if (this.observers[\"\"]) {\n this.observers[\"\"].delete(callback);\n }\n } else {\n contentTopics.forEach((contentTopic) => {\n if (this.observers[contentTopic]) {\n this.observers[contentTopic].delete(callback);\n }\n });\n }\n }\n\n /**\n * Subscribe to a pubsub topic and start emitting Waku messages to observers.\n *\n * @override\n */\n subscribe(pubSubTopic: string): void {\n this.addEventListener(\n \"gossipsub:message\",\n (event: CustomEvent) => {\n if (event.detail.msg.topic === pubSubTopic) {\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n dbg(`Message received on ${pubSubTopic}`);\n WakuMessage.decode(event.detail.msg.data, decryptionKeys)\n .then((wakuMsg) => {\n if (!wakuMsg) {\n dbg(\"Failed to decode Waku Message\");\n return;\n }\n\n if (this.observers[\"\"]) {\n this.observers[\"\"].forEach((callbackFn) => {\n callbackFn(wakuMsg);\n });\n }\n if (wakuMsg.contentTopic) {\n if (this.observers[wakuMsg.contentTopic]) {\n this.observers[wakuMsg.contentTopic].forEach((callbackFn) => {\n callbackFn(wakuMsg);\n });\n }\n }\n })\n .catch((e) => {\n dbg(\"Failed to decode Waku Message\", e);\n });\n }\n }\n );\n\n super.subscribe(pubSubTopic);\n }\n\n getMeshPeers(topic?: TopicStr): PeerIdStr[] {\n return super.getMeshPeers(topic ?? this.pubSubTopic);\n }\n}\n","export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n","import { Reader, reader } from 'it-reader'\nimport { pushable } from 'it-pushable'\nimport defer from 'p-defer'\nimport type { Duplex, Source } from 'it-stream-types'\nimport type { Pushable } from 'it-pushable'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Handshake {\n reader: Reader\n writer: Pushable\n stream: Duplex\n rest: () => Source\n write: (data: TSink) => void\n read: () => Promise\n}\n\n// Convert a duplex stream into a reader and writer and rest stream\nexport function handshake (stream: Duplex): Handshake {\n const writer = pushable() // Write bytes on demand to the sink\n const source = reader(stream.source) // Read bytes on demand from the source\n\n // Waits for a source to be passed to the rest stream's sink\n const sourcePromise = defer>()\n let sinkErr: Error\n\n const sinkPromise = stream.sink((async function * () {\n yield * writer\n const source = await sourcePromise.promise\n yield * source\n })())\n\n sinkPromise.catch(err => {\n sinkErr = err\n })\n\n const rest: Duplex = {\n sink: async source => {\n if (sinkErr != null) {\n return await Promise.reject(sinkErr)\n }\n\n sourcePromise.resolve(source)\n return await sinkPromise\n },\n source\n }\n\n return {\n reader: source,\n writer,\n stream: rest,\n rest: () => writer.end(),\n write: writer.push,\n read: async () => {\n const res = await source.next()\n\n if (res.value != null) {\n return res.value\n }\n }\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport type { Source } from 'it-stream-types'\n\nexport interface Reader extends AsyncGenerator {\n next: (...args: [] | [number | undefined]) => Promise>\n}\n\nexport function reader (source: Source) {\n const reader: Reader = (async function * (): AsyncGenerator {\n // @ts-expect-error first yield in stream is ignored\n let bytes: number | undefined = yield // Allows us to receive 8 when reader.next(8) is called\n let bl = new Uint8ArrayList()\n\n for await (const chunk of source) {\n if (bytes == null) {\n bl.append(chunk)\n bytes = yield bl\n bl = new Uint8ArrayList()\n continue\n }\n\n bl.append(chunk)\n\n while (bl.length >= bytes) {\n const data = bl.sublist(0, bytes)\n bl.consume(bytes)\n bytes = yield data\n\n // If we no longer want a specific byte length, we yield the rest now\n if (bytes == null) {\n if (bl.length > 0) {\n bytes = yield bl\n bl = new Uint8ArrayList()\n }\n break // bytes is null and/or no more buffer to yield\n }\n }\n }\n\n // Consumer wants more bytes but the source has ended and our buffer\n // is not big enough to satisfy.\n if (bytes != null) {\n throw Object.assign(\n new Error(`stream ended before ${bytes} bytes became available`),\n { code: 'ERR_UNDER_READ', buffer: bl }\n )\n }\n })()\n\n void reader.next()\n return reader\n}\n","import { handshake } from 'it-handshake'\nimport * as lp from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\ninterface Decoder {\n (data: Uint8Array | Uint8ArrayList): T\n}\n\ninterface Encoder {\n (data: T): Uint8Array\n}\n\nexport interface ProtobufStream {\n read: (bytes?: number) => Promise\n readLP: () => Promise\n readPB: (proto: { decode: Decoder }) => Promise\n write: (input: Uint8Array | Uint8ArrayList) => void\n writeLP: (input: Uint8Array | Uint8ArrayList) => void\n writePB: (data: Uint8Array | Uint8ArrayList, proto: {encode: Encoder}) => void\n pb: (proto: {encode: Encoder, decode: Decoder }) => {read: () => Promise, write: (d: Uint8Array | Uint8ArrayList) => void}\n\n // return vanilla duplex\n unwrap: () => Duplex\n}\n\nexport interface Opts {\n // encoding opts\n poolSize: number\n minPoolSize: number\n lengthEncoder: lp.LengthEncoderFunction\n\n // decoding opts\n lengthDecoder: lp.LengthDecoderFunction\n maxLengthLength: number\n maxDataLength: number\n}\n\nexport function pbStream (duplex: Duplex, opts = {}): ProtobufStream {\n const shake = handshake(duplex)\n const lpReader = lp.decode.fromReader(\n shake.reader,\n opts\n )\n\n const W: ProtobufStream = {\n read: async (bytes) => {\n // just read\n const { value } = await shake.reader.next(bytes)\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n return value\n },\n readLP: async () => {\n // read, decode\n // @ts-expect-error .next is part of the generator interface\n const { value } = await lpReader.next()\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n return value\n },\n readPB: async (proto) => {\n // readLP, decode\n const value = await W.readLP()\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n // Is this a buffer?\n const buf = value instanceof Uint8Array ? value : value.slice()\n\n return proto.decode(buf)\n },\n write: (data) => {\n // just write\n if (data instanceof Uint8Array) {\n shake.writer.push(data)\n } else {\n shake.writer.push(data.slice())\n }\n },\n writeLP: (data) => {\n // encode, write\n W.write(lp.encode.single(data, opts))\n },\n writePB: (data, proto) => {\n // encode, writeLP\n W.writeLP(proto.encode(data))\n },\n pb: (proto) => {\n return {\n read: async () => await W.readPB(proto),\n write: (d) => W.writePB(d, proto)\n }\n },\n unwrap: () => {\n // returns vanilla duplex again, terminates all reads/writes from this object\n shake.rest()\n return shake.stream\n }\n }\n\n return W\n}\n","import defer from 'p-defer'\nimport type { Source, Duplex } from 'it-stream-types'\n\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair (): Duplex {\n const deferred = defer>()\n let piped = false\n\n return {\n sink: async source => {\n if (piped) {\n throw new Error('already piped')\n }\n\n piped = true\n deferred.resolve(source)\n },\n source: (async function * () {\n const source = await deferred.promise\n\n yield * source\n }())\n }\n}\n","export const NOISE_MSG_MAX_LENGTH_BYTES = 65535\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16\n\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS)\n","import { HKDF } from '@stablelib/hkdf'\nimport * as x25519 from '@stablelib/x25519'\nimport { SHA256, hash } from '@stablelib/sha256'\nimport { ChaCha20Poly1305 } from '@stablelib/chacha20poly1305'\nimport type { bytes32, bytes } from '../@types/basic.js'\nimport type { Hkdf } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport type { ICryptoInterface } from '../crypto.js'\n\nexport const stablelib: ICryptoInterface = {\n hashSHA256 (data: Uint8Array): Uint8Array {\n return hash(data)\n },\n\n getHKDF (ck: bytes32, ikm: Uint8Array): Hkdf {\n const hkdf = new HKDF(SHA256, ikm, ck)\n const okmU8Array = hkdf.expand(96)\n const okm = okmU8Array\n\n const k1 = okm.subarray(0, 32)\n const k2 = okm.subarray(32, 64)\n const k3 = okm.subarray(64, 96)\n\n return [k1, k2, k3]\n },\n\n generateX25519KeyPair (): KeyPair {\n const keypair = x25519.generateKeyPair()\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair {\n const keypair = x25519.generateKeyPairFromSeed(seed)\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519SharedKey (privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array {\n return x25519.sharedKey(privateKey, publicKey)\n },\n\n chaCha20Poly1305Encrypt (plaintext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.seal(nonce, plaintext, ad)\n },\n\n chaCha20Poly1305Decrypt (ciphertext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes | null {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.open(nonce, ciphertext, ad)\n }\n}\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { bytes } from './@types/basic.js'\nimport type { MessageBuffer } from './@types/handshake.js'\nimport type { LengthDecoderFunction, LengthEncoderFunction } from 'it-length-prefixed'\n\nconst allocUnsafe = (len: number): Uint8Array => {\n if (globalThis.Buffer) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n\nexport const uint16BEEncode: LengthEncoderFunction = (value: number) => {\n const target = allocUnsafe(2)\n new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)\n return target\n}\nuint16BEEncode.bytes = 2\n\nexport const uint16BEDecode: LengthDecoderFunction = (data: Uint8Array | Uint8ArrayList): number => {\n if (data.length < 2) throw RangeError('Could not decode int16BE')\n\n if (data instanceof Uint8Array) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false)\n }\n\n return data.getUint16(0)\n}\nuint16BEDecode.bytes = 2\n\n// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)\n\nexport function encode0 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ciphertext], message.ne.length + message.ciphertext.length)\n}\n\nexport function encode1 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ns, message.ciphertext], message.ne.length + message.ns.length + message.ciphertext.length)\n}\n\nexport function encode2 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ns, message.ciphertext], message.ns.length + message.ciphertext.length)\n}\n\nexport function decode0 (input: bytes): MessageBuffer {\n if (input.length < 32) {\n throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ciphertext: input.subarray(32, input.length),\n ns: new Uint8Array(0)\n }\n}\n\nexport function decode1 (input: bytes): MessageBuffer {\n if (input.length < 80) {\n throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ns: input.subarray(32, 80),\n ciphertext: input.subarray(80, input.length)\n }\n}\n\nexport function decode2 (input: bytes): MessageBuffer {\n if (input.length < 48) {\n throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')\n }\n\n return {\n ne: new Uint8Array(0),\n ns: input.subarray(0, 48),\n ciphertext: input.subarray(48, input.length)\n }\n}\n","\nexport function alloc (len: number) {\n return new Uint8Array(len)\n}\n\nexport function allocUnsafe (len: number) {\n if (globalThis?.Buffer?.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeFunction {\n (value: T): Uint8Array | Uint8ArrayList\n}\n\nexport interface DecodeFunction {\n (buf: Uint8ArrayList, offset: number): T\n}\n\nexport interface EncodingLengthFunction {\n (value: T): number\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n encodingLength: EncodingLengthFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction, encodingLength: EncodingLengthFunction): Codec {\n return {\n name,\n type,\n encode,\n decode,\n encodingLength\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function boolEncodingLength () {\n return 1\n}\n\nconst encode: EncodeFunction = function boolEncode (value) {\n return Uint8Array.from([value ? 1 : 0])\n}\n\nconst decode: DecodeFunction = function boolDecode (buffer, offset) {\n return buffer.get(offset) > 0\n}\n\nexport const bool = createCodec('bool', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function bytesEncodingLength (val) {\n const len = val.byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function bytesEncode (val) {\n return new Uint8ArrayList(\n unsigned.encode(val.byteLength),\n val\n )\n}\n\nconst decode: DecodeFunction = function bytesDecode (buf, offset) {\n const byteLength = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(byteLength)\n\n return buf.subarray(offset, offset + byteLength)\n}\n\nexport const bytes = createCodec('bytes', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function doubleEncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function doubleEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setFloat64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function doubleDecode (buf, offset) {\n return buf.getFloat64(offset, true)\n}\n\nexport const double = createCodec('double', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function fixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function fixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function fixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const fixed32 = createCodec('fixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return 8\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const fixed64 = createCodec('fixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function floatEncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function floatEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(1)))\n buf.setFloat32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function floatDecode (buf, offset) {\n return buf.getFloat32(offset, true)\n}\n\nexport const float = createCodec('float', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { signed } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int32EncodingLength (val) {\n if (val < 0) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int32Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n\n return signed.encode(val, buf)\n}\n\nconst decode: DecodeFunction = function int32Decode (buf, offset) {\n return signed.decode(buf, offset) | 0\n}\n\nexport const int32 = createCodec('int32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from 'byte-access'\nimport { LongBits } from 'longbits'\nimport { allocUnsafe } from 'uint8arrays/alloc'\n\nconst LIMIT = 0x7fn\n\ninterface BigVarintCodec {\n encodingLength: (value: bigint) => number\n encode: ((value: bigint) => Uint8Array) & ((value: bigint, buf: Uint8Array, offset?: number) => Uint8Array) & ((value: bigint, buf: Uint8ArrayList, offset?: number) => Uint8ArrayList)\n decode: (buf: Uint8ArrayList | Uint8Array, offset?: number) => bigint\n}\n\n// https://github.com/joeltg/big-varint/blob/main/src/unsigned.ts\nexport const unsigned: BigVarintCodec = {\n encodingLength (value: bigint): number {\n let i = 0\n for (; value >= 0x80n; i++) {\n value >>= 7n\n }\n return i + 1\n },\n\n encode (value: any, buf?: any, offset: any = 0) {\n if (buf == null) {\n buf = allocUnsafe(unsigned.encodingLength(value))\n }\n\n const access = accessor(buf)\n\n while (LIMIT < value) {\n access.set(offset++, Number(value & LIMIT) | 0x80)\n value >>= 7n\n }\n\n access.set(offset, Number(value))\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(true)\n }\n}\n\nexport const signed: BigVarintCodec = {\n encodingLength (value: bigint): number {\n if (value < 0n) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(signed.encodingLength(value))\n }\n\n if (value < 0n) {\n LongBits.fromBigInt(value).toBytes(buf, offset)\n\n return buf\n }\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(false)\n }\n}\n\nexport const zigzag: BigVarintCodec = {\n encodingLength (value: bigint): number {\n return unsigned.encodingLength(value >= 0 ? value * 2n : value * -2n - 1n)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(zigzag.encodingLength(value))\n }\n\n LongBits.fromBigInt(value).zzEncode().toBytes(buf, offset)\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).zzDecode().toBigInt(false)\n }\n}\n","import { signed } from 'uint8-varint/big'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n if (val < 0n) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n\n return signed.encode(val, buf)\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return signed.decode(buf, offset) | 0n\n}\n\nexport const int64 = createCodec('int64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function sfixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const sfixed32 = createCodec('sfixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed64EncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function sfixed64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const sfixed64 = createCodec('sfixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { zigzag } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sint32EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function svarintEncode (val) {\n return zigzag.encode(val)\n}\n\nconst decode: DecodeFunction = function svarintDecode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint32 = createCodec('sint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { zigzag } from 'uint8-varint/big'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n return zigzag.encode(val)\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint64 = createCodec('sint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from 'uint8-varint'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\n\nconst encodingLength: EncodingLengthFunction = function stringEncodingLength (val) {\n const len = uint8ArrayFromString(val).byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function stringEncode (val) {\n const asBuf = uint8ArrayFromString(val)\n\n return new Uint8ArrayList(\n unsigned.encode(asBuf.byteLength),\n asBuf\n )\n}\n\nconst decode: DecodeFunction = function stringDecode (buf, offset) {\n const strLen = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(strLen)\n\n return uint8ArrayToString(buf.subarray(offset, offset + strLen))\n}\n\nexport const string = createCodec('string', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { unsigned } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint32EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint32Encode (val) {\n // val = val < 0 ? val + 4294967296 : val\n\n return unsigned.encode(val)\n}\n\nconst decode: DecodeFunction = function uint32Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n\n // return value > 2147483647 ? value - 4294967296 : value\n}\n\nexport const uint32 = createCodec('uint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from 'uint8-varint/big'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint64EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint64Encode (val) {\n return unsigned.encode(val)\n}\n\nconst decode: DecodeFunction = function uint64Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n}\n\nexport const uint64 = createCodec('uint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, bytes } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport namespace pb {\n export interface NoiseHandshakePayload {\n identityKey: Uint8Array\n identitySig: Uint8Array\n data: Uint8Array\n }\n\n export namespace NoiseHandshakePayload {\n export const codec = (): Codec => {\n return message({\n 1: { name: 'identityKey', codec: bytes },\n 2: { name: 'identitySig', codec: bytes },\n 3: { name: 'data', codec: bytes }\n })\n }\n\n export const encode = (obj: NoiseHandshakePayload): Uint8ArrayList => {\n return encodeMessage(obj, NoiseHandshakePayload.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseHandshakePayload => {\n return decodeMessage(buf, NoiseHandshakePayload.codec())\n }\n }\n}\n","import { unsigned } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction, Codec } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { FieldDefs, FieldDef } from '../index.js'\nimport { allocUnsafe } from '../utils/alloc.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (fieldDefs: FieldDefs): Codec {\n const encodingLength: EncodingLengthFunction = function messageEncodingLength (val: Record) {\n let length = 0\n\n for (const fieldDef of Object.values(fieldDefs)) {\n length += fieldDef.codec.encodingLength(val[fieldDef.name])\n }\n\n return unsigned.encodingLength(length) + length\n }\n\n const encode: EncodeFunction> = function messageEncode (val) {\n const bytes = new Uint8ArrayList()\n\n function encodeValue (value: any, fieldNumber: number, fieldDef: FieldDef) {\n if (value == null) {\n if (fieldDef.optional === true) {\n return\n }\n\n throw new Error(`Non optional field \"${fieldDef.name}\" was ${value === null ? 'null' : 'undefined'}`)\n }\n\n const key = (fieldNumber << 3) | fieldDef.codec.type\n const prefix = allocUnsafe(unsigned.encodingLength(key))\n unsigned.encode(key, prefix)\n const encoded = fieldDef.codec.encode(value)\n\n bytes.append(prefix)\n bytes.append(encoded)\n }\n\n for (const [fieldNumberStr, fieldDef] of Object.entries(fieldDefs)) {\n const fieldNumber = parseInt(fieldNumberStr)\n\n if (fieldDef.repeats === true) {\n if (!Array.isArray(val[fieldDef.name])) {\n throw new Error(`Repeating field \"${fieldDef.name}\" was not an array`)\n }\n\n for (const value of val[fieldDef.name]) {\n encodeValue(value, fieldNumber, fieldDef)\n }\n } else {\n encodeValue(val[fieldDef.name], fieldNumber, fieldDef)\n }\n }\n\n const prefix = unsigned.encode(bytes.length)\n\n return new Uint8ArrayList(prefix, bytes)\n }\n\n const decode: DecodeFunction = function messageDecode (buffer, offset) {\n const length = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(length)\n const end = offset + length\n const fields: any = {}\n\n while (offset < end) {\n const key = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(key)\n\n const wireType = key & 0x7\n const fieldNumber = key >> 3\n const fieldDef = fieldDefs[fieldNumber]\n let fieldLength = 0\n\n if (wireType === CODEC_TYPES.VARINT) {\n if (fieldDef != null) {\n // use the codec if it is available as this could be a bigint\n const value = fieldDef.codec.decode(buffer, offset)\n fieldLength = fieldDef.codec.encodingLength(value)\n } else {\n const value = unsigned.decode(buffer, offset)\n fieldLength = unsigned.encodingLength(value)\n }\n } else if (wireType === CODEC_TYPES.BIT64) {\n fieldLength = 8\n } else if (wireType === CODEC_TYPES.LENGTH_DELIMITED) {\n const valueLength = unsigned.decode(buffer, offset)\n fieldLength = valueLength + unsigned.encodingLength(valueLength)\n } else if (wireType === CODEC_TYPES.BIT32) {\n fieldLength = 4\n } else if (wireType === CODEC_TYPES.START_GROUP) {\n throw new Error('Unsupported wire type START_GROUP')\n } else if (wireType === CODEC_TYPES.END_GROUP) {\n throw new Error('Unsupported wire type END_GROUP')\n }\n\n if (fieldDef != null) {\n const value = fieldDef.codec.decode(buffer, offset)\n\n if (fieldDef.repeats === true) {\n if (fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n\n fields[fieldDef.name].push(value)\n } else {\n fields[fieldDef.name] = value\n }\n }\n\n offset += fieldLength\n }\n\n // make sure repeated fields have an array if not set\n for (const fieldDef of Object.values(fieldDefs)) {\n if (fieldDef.repeats === true && fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n }\n\n return fields\n }\n\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from './codec.js'\nimport { unsigned } from 'uint8-varint'\n\nexport function encodeMessage (message: T, codec: Codec): Uint8ArrayList {\n // unwrap root message\n const encoded = codec.encode(message)\n const skip = unsigned.encodingLength(unsigned.decode(encoded))\n\n if (encoded instanceof Uint8Array) {\n return new Uint8ArrayList(encoded.subarray(skip))\n }\n\n return encoded.sublist(skip)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport type { Codec } from './codec.js'\nimport { allocUnsafe } from './utils/alloc.js'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Codec): T {\n // wrap root message\n const prefix = allocUnsafe(unsigned.encodingLength(buf.byteLength))\n unsigned.encode(buf.byteLength, prefix)\n\n return codec.decode(new Uint8ArrayList(prefix, buf), 0)\n}\n","import { unmarshalPublicKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { bytes } from './@types/basic.js'\nimport { pb } from './proto/payload.js'\n\nconst NoiseHandshakePayloadProto = pb.NoiseHandshakePayload\n\nexport async function getPayload (\n localPeer: PeerId,\n staticPublicKey: bytes,\n earlyData?: bytes\n): Promise {\n const signedPayload = await signPayload(localPeer, getHandshakePayload(staticPublicKey))\n const earlyDataPayload = earlyData ?? new Uint8Array(0)\n\n if (localPeer.publicKey == null) {\n throw new Error('PublicKey was missing from local PeerId')\n }\n\n return createHandshakePayload(\n localPeer.publicKey,\n signedPayload,\n earlyDataPayload\n )\n}\n\nexport function createHandshakePayload (\n libp2pPublicKey: Uint8Array,\n signedPayload: Uint8Array,\n earlyData?: Uint8Array\n): bytes {\n return NoiseHandshakePayloadProto.encode({\n identityKey: libp2pPublicKey,\n identitySig: signedPayload,\n data: earlyData ?? new Uint8Array(0)\n }).subarray()\n}\n\nexport async function signPayload (peerId: PeerId, payload: bytes): Promise {\n if (peerId.privateKey == null) {\n throw new Error('PrivateKey was missing from PeerId')\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return await privateKey.sign(payload)\n}\n\nexport async function getPeerIdFromPayload (payload: pb.NoiseHandshakePayload): Promise {\n return await peerIdFromKeys(payload.identityKey)\n}\n\nexport function decodePayload (payload: bytes|Uint8Array): pb.NoiseHandshakePayload {\n return NoiseHandshakePayloadProto.decode(payload)\n}\n\nexport function getHandshakePayload (publicKey: bytes): bytes {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:')\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length)\n}\n\n/**\n * Verifies signed payload, throws on any irregularities.\n *\n * @param {bytes} noiseStaticKey - owner's noise static key\n * @param {bytes} payload - decoded payload\n * @param {PeerId} remotePeer - owner's libp2p peer ID\n * @returns {Promise} - peer ID of payload owner\n */\nexport async function verifySignedPayload (\n noiseStaticKey: bytes,\n payload: pb.NoiseHandshakePayload,\n remotePeer: PeerId\n): Promise {\n // Unmarshaling from PublicKey protobuf\n const payloadPeerId = await peerIdFromKeys(payload.identityKey)\n if (!payloadPeerId.equals(remotePeer)) {\n throw new Error(\"Peer ID doesn't match libp2p public key.\")\n }\n const generatedPayload = getHandshakePayload(noiseStaticKey)\n\n if (payloadPeerId.publicKey == null) {\n throw new Error('PublicKey was missing from PeerId')\n }\n\n if (payload.identitySig == null) {\n throw new Error('Signature was missing from message')\n }\n\n const publicKey = unmarshalPublicKey(payloadPeerId.publicKey)\n\n const valid = await publicKey.verify(generatedPayload, payload.identitySig)\n\n if (!valid) {\n throw new Error(\"Static key doesn't match to peer that signed payload!\")\n }\n\n return payloadPeerId\n}\n\nexport function isValidPublicKey (pk: bytes): boolean {\n if (!(pk instanceof Uint8Array)) {\n return false\n }\n\n if (pk.length !== 32) {\n return false\n }\n\n return true\n}\n","import { Logger, logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport { DUMP_SESSION_KEYS } from './constants.js'\n\nconst log = logger('libp2p:noise')\n\nexport { log as logger }\n\nlet keyLogger: Logger\nif (DUMP_SESSION_KEYS) {\n keyLogger = log\n} else {\n keyLogger = Object.assign(() => { /* do nothing */ }, {\n enabled: false,\n trace: () => {},\n error: () => {}\n })\n}\n\nexport function logLocalStaticKeys (s: KeyPair): void {\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`)\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`)\n}\n\nexport function logLocalEphemeralKeys (e: KeyPair|undefined): void {\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`)\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`)\n } else {\n keyLogger('Missing local ephemeral keys.')\n }\n}\n\nexport function logRemoteStaticKey (rs: Uint8Array): void {\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs, 'hex')}`)\n}\n\nexport function logRemoteEphemeralKey (re: Uint8Array): void {\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re, 'hex')}`)\n}\n\nexport function logCipherState (session: NoiseSession): void {\n if (session.cs1 && session.cs2) {\n keyLogger(`CIPHER_STATE_1 ${session.cs1.n.getUint64()} ${uint8ArrayToString(session.cs1.k, 'hex')}`)\n keyLogger(`CIPHER_STATE_2 ${session.cs2.n.getUint64()} ${uint8ArrayToString(session.cs2.k, 'hex')}`)\n } else {\n keyLogger('Missing cipher state.')\n }\n}\n","import type { bytes, uint64 } from './@types/basic'\n\nexport const MIN_NONCE = 0\n// For performance reasons, the nonce is represented as a JS `number`\n// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use\n// 4 bytes to store the data for performance reason.\n// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2\n// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.\n// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.\nexport const MAX_NONCE = 0xffffffff\n\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed'\n\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n private n: uint64\n private readonly bytes: bytes\n private readonly view: DataView\n\n constructor (n = MIN_NONCE) {\n this.n = n\n this.bytes = new Uint8Array(12)\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength)\n this.view.setUint32(4, n, true)\n }\n\n increment (): void {\n this.n++\n // Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.\n this.view.setUint32(4, this.n, true)\n }\n\n getBytes (): bytes {\n return this.bytes\n }\n\n getUint64 (): uint64 {\n return this.n\n }\n\n assertValue (): void {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE)\n }\n }\n}\n","import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays'\nimport type { bytes, bytes32 } from '../@types/basic.js'\nimport type { CipherState, MessageBuffer, SymmetricState } from '../@types/handshake.js'\nimport type { ICryptoInterface } from '../crypto.js'\nimport { logger } from '../logger.js'\nimport { Nonce } from '../nonce.js'\n\nexport abstract class AbstractHandshake {\n public crypto: ICryptoInterface\n\n constructor (crypto: ICryptoInterface) {\n this.crypto = crypto\n }\n\n public encryptWithAd (cs: CipherState, ad: Uint8Array, plaintext: Uint8Array): bytes {\n const e = this.encrypt(cs.k, cs.n, ad, plaintext)\n cs.n.increment()\n\n return e\n }\n\n public decryptWithAd (cs: CipherState, ad: Uint8Array, ciphertext: Uint8Array): {plaintext: bytes, valid: boolean} {\n const { plaintext, valid } = this.decrypt(cs.k, cs.n, ad, ciphertext)\n cs.n.increment()\n\n return { plaintext, valid }\n }\n\n // Cipher state related\n protected hasKey (cs: CipherState): boolean {\n return !this.isEmptyKey(cs.k)\n }\n\n protected createEmptyKey (): bytes32 {\n return new Uint8Array(32)\n }\n\n protected isEmptyKey (k: bytes32): boolean {\n const emptyKey = this.createEmptyKey()\n return uint8ArrayEquals(emptyKey, k)\n }\n\n protected encrypt (k: bytes32, n: Nonce, ad: Uint8Array, plaintext: Uint8Array): bytes {\n n.assertValue()\n\n return this.crypto.chaCha20Poly1305Encrypt(plaintext, n.getBytes(), ad, k)\n }\n\n protected encryptAndHash (ss: SymmetricState, plaintext: bytes): bytes {\n let ciphertext\n if (this.hasKey(ss.cs)) {\n ciphertext = this.encryptWithAd(ss.cs, ss.h, plaintext)\n } else {\n ciphertext = plaintext\n }\n\n this.mixHash(ss, ciphertext)\n return ciphertext\n }\n\n protected decrypt (k: bytes32, n: Nonce, ad: bytes, ciphertext: bytes): {plaintext: bytes, valid: boolean} {\n n.assertValue()\n\n const encryptedMessage = this.crypto.chaCha20Poly1305Decrypt(ciphertext, n.getBytes(), ad, k)\n\n if (encryptedMessage) {\n return {\n plaintext: encryptedMessage,\n valid: true\n }\n } else {\n return {\n plaintext: new Uint8Array(0),\n valid: false\n }\n }\n }\n\n protected decryptAndHash (ss: SymmetricState, ciphertext: bytes): {plaintext: bytes, valid: boolean} {\n let plaintext: bytes; let valid = true\n if (this.hasKey(ss.cs)) {\n ({ plaintext, valid } = this.decryptWithAd(ss.cs, ss.h, ciphertext))\n } else {\n plaintext = ciphertext\n }\n\n this.mixHash(ss, ciphertext)\n return { plaintext, valid }\n }\n\n protected dh (privateKey: bytes32, publicKey: bytes32): bytes32 {\n try {\n const derivedU8 = this.crypto.generateX25519SharedKey(privateKey, publicKey)\n\n if (derivedU8.length === 32) {\n return derivedU8\n }\n\n return derivedU8.subarray(0, 32)\n } catch (e) {\n const err = e as Error\n logger(err.message)\n return new Uint8Array(32)\n }\n }\n\n protected mixHash (ss: SymmetricState, data: bytes): void {\n ss.h = this.getHash(ss.h, data)\n }\n\n protected getHash (a: Uint8Array, b: Uint8Array): bytes32 {\n const u = this.crypto.hashSHA256(uint8ArrayConcat([a, b], a.length + b.length))\n return u\n }\n\n protected mixKey (ss: SymmetricState, ikm: bytes32): void {\n const [ck, tempK] = this.crypto.getHKDF(ss.ck, ikm)\n ss.cs = this.initializeKey(tempK)\n ss.ck = ck\n }\n\n protected initializeKey (k: bytes32): CipherState {\n return { k, n: new Nonce() }\n }\n\n // Symmetric state related\n\n protected initializeSymmetric (protocolName: string): SymmetricState {\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8')\n const h = this.hashProtocolName(protocolNameBytes)\n\n const ck = h\n const key = this.createEmptyKey()\n const cs: CipherState = this.initializeKey(key)\n\n return { cs, ck, h }\n }\n\n protected hashProtocolName (protocolName: Uint8Array): bytes32 {\n if (protocolName.length <= 32) {\n const h = new Uint8Array(32)\n h.set(protocolName)\n return h\n } else {\n return this.getHash(protocolName, new Uint8Array(0))\n }\n }\n\n protected split (ss: SymmetricState): {cs1: CipherState, cs2: CipherState} {\n const [tempk1, tempk2] = this.crypto.getHKDF(ss.ck, new Uint8Array(0))\n const cs1 = this.initializeKey(tempk1)\n const cs2 = this.initializeKey(tempk2)\n\n return { cs1, cs2 }\n }\n\n protected writeMessageRegular (cs: CipherState, payload: bytes): MessageBuffer {\n const ciphertext = this.encryptWithAd(cs, new Uint8Array(0), payload)\n const ne = this.createEmptyKey()\n const ns = new Uint8Array(0)\n\n return { ne, ns, ciphertext }\n }\n\n protected readMessageRegular (cs: CipherState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n return this.decryptWithAd(cs, new Uint8Array(0), message.ciphertext)\n }\n}\n","import type { bytes, bytes32 } from '../@types/basic.js'\nimport type { CipherState, HandshakeState, MessageBuffer, NoiseSession } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport { isValidPublicKey } from '../utils.js'\nimport { AbstractHandshake } from './abstract-handshake.js'\n\nexport class IK extends AbstractHandshake {\n public initSession (initiator: boolean, prologue: bytes32, s: KeyPair, rs: bytes32): NoiseSession {\n const psk = this.createEmptyKey()\n\n let hs\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk)\n } else {\n hs = this.initializeResponder(prologue, s, rs, psk)\n }\n\n return {\n hs,\n i: initiator,\n mc: 0\n }\n }\n\n public sendMessage (session: NoiseSession, message: bytes): MessageBuffer {\n let messageBuffer: MessageBuffer\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message)\n } else if (session.mc === 1) {\n const { messageBuffer: mb, h, cs1, cs2 } = this.writeMessageB(session.hs, message)\n messageBuffer = mb\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n } else if (session.mc > 1) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs1, message)\n } else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs2, message)\n }\n } else {\n throw new Error('Session invalid.')\n }\n\n session.mc++\n return messageBuffer\n }\n\n public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n let plaintext = new Uint8Array(0); let valid = false\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message))\n }\n if (session.mc === 1) {\n const { plaintext: pt, valid: v, h, cs1, cs2 } = this.readMessageB(session.hs, message)\n plaintext = pt\n valid = v\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n }\n session.mc++\n return { plaintext, valid }\n }\n\n private writeMessageA (hs: HandshakeState, payload: bytes): MessageBuffer {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.rs))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageB (hs: HandshakeState, payload: bytes): { messageBuffer: MessageBuffer, cs1: CipherState, cs2: CipherState, h: bytes} {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n const ns = this.createEmptyKey()\n const messageBuffer: MessageBuffer = { ne, ns, ciphertext }\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { messageBuffer, cs1, cs2, h: hs.ss.h }\n }\n\n private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.rs))\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n return { plaintext, valid: (valid1 && valid2) }\n }\n\n private readMessageB (hs: HandshakeState, message: MessageBuffer): {h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n if (!hs.e) {\n throw new Error('Handshake state should contain ephemeral key by now.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const { plaintext, valid } = this.decryptAndHash(hs.ss, message.ciphertext)\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, valid, plaintext, cs1, cs2 }\n }\n\n private initializeInitiator (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_IK_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n this.mixHash(ss, rs)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, re, psk }\n }\n\n private initializeResponder (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_IK_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n this.mixHash(ss, s.publicKey)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, re, psk }\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class FailedIKError extends Error {\n public initialMsg: string|Uint8ArrayList|Uint8Array\n\n constructor (initialMsg: string|Uint8ArrayList|Uint8Array, message?: string) {\n super(message)\n\n this.initialMsg = initialMsg\n this.name = 'FailedIKhandshake'\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { CipherState, NoiseSession } from './@types/handshake.js'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { IK } from './handshakes/ik.js'\nimport { decode0, decode1, encode0, encode1 } from './encoder.js'\nimport { FailedIKError } from './errors.js'\nimport {\n logger,\n logLocalStaticKeys,\n logRemoteStaticKey,\n logLocalEphemeralKeys,\n logRemoteEphemeralKey,\n logCipherState\n} from './logger.js'\nimport { decodePayload, getPeerIdFromPayload, verifySignedPayload } from './utils.js'\n\nexport class IKHandshake implements IHandshake {\n public isInitiator: boolean\n public session: NoiseSession\n public remotePeer!: PeerId\n public remoteEarlyData: Uint8Array\n\n private readonly payload: bytes\n private readonly prologue: bytes32\n private readonly staticKeypair: KeyPair\n private readonly connection: ProtobufStream\n private readonly ik: IK\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n remoteStaticKey: bytes,\n remotePeer?: PeerId,\n handshake?: IK\n ) {\n this.isInitiator = isInitiator\n this.payload = payload\n this.prologue = prologue\n this.staticKeypair = staticKeypair\n this.connection = connection\n if (remotePeer) {\n this.remotePeer = remotePeer\n }\n this.ik = handshake ?? new IK(crypto)\n this.session = this.ik.initSession(this.isInitiator, this.prologue, this.staticKeypair, remoteStaticKey)\n this.remoteEarlyData = new Uint8Array()\n }\n\n public async stage0 (): Promise {\n logLocalStaticKeys(this.session.hs.s)\n logRemoteStaticKey(this.session.hs.rs)\n if (this.isInitiator) {\n logger('IK Stage 0 - Initiator sending message...')\n const messageBuffer = this.ik.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode1(messageBuffer))\n logger('IK Stage 0 - Initiator sent message.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger('IK Stage 0 - Responder receiving message...')\n const receivedMsg = await this.connection.readLP()\n try {\n const receivedMessageBuffer = decode1(receivedMsg.slice())\n const { plaintext, valid } = this.ik.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new Error('ik handshake stage 0 decryption validation fail')\n }\n logger('IK Stage 0 - Responder got message, going to verify payload.')\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n logger('IK Stage 0 - Responder successfully verified payload!')\n logRemoteEphemeralKey(this.session.hs.re)\n } catch (e) {\n const err = e as Error\n logger('Responder breaking up with IK handshake in stage 0.')\n\n throw new FailedIKError(receivedMsg.slice(), `Error occurred while verifying initiator's signed payload: ${err.message}`)\n }\n }\n }\n\n public async stage1 (): Promise {\n if (this.isInitiator) {\n logger('IK Stage 1 - Initiator receiving message...')\n const receivedMsg = (await this.connection.readLP()).slice()\n const receivedMessageBuffer = decode0(receivedMsg)\n const { plaintext, valid } = this.ik.recvMessage(this.session, receivedMessageBuffer)\n logger('IK Stage 1 - Initiator got message, going to verify payload.')\n try {\n if (!valid) {\n throw new Error('ik stage 1 decryption validation fail')\n }\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(receivedMessageBuffer.ns.slice(0, 32), decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n logger('IK Stage 1 - Initiator successfully verified payload!')\n logRemoteEphemeralKey(this.session.hs.re)\n } catch (e) {\n const err = e as Error\n logger('Initiator breaking up with IK handshake in stage 1.')\n throw new FailedIKError(receivedMsg, `Error occurred while verifying responder's signed payload: ${err.message}`)\n }\n } else {\n logger('IK Stage 1 - Responder sending message...')\n const messageBuffer = this.ik.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode0(messageBuffer))\n logger('IK Stage 1 - Responder sent message...')\n logLocalEphemeralKeys(this.session.hs.e)\n }\n logCipherState(this.session)\n }\n\n public decrypt (ciphertext: Uint8Array, session: NoiseSession): {plaintext: bytes, valid: boolean} {\n const cs = this.getCS(session, false)\n return this.ik.decryptWithAd(cs, new Uint8Array(0), ciphertext)\n }\n\n public encrypt (plaintext: Uint8Array, session: NoiseSession): bytes {\n const cs = this.getCS(session)\n return this.ik.encryptWithAd(cs, new Uint8Array(0), plaintext)\n }\n\n public getLocalEphemeralKeys (): KeyPair {\n if (!this.session.hs.e) {\n throw new Error('Ephemeral keys do not exist.')\n }\n\n return this.session.hs.e\n }\n\n private getCS (session: NoiseSession, encryption = true): CipherState {\n if (!session.cs1 || !session.cs2) {\n throw new Error('Handshake not completed properly, cipher state does not exist.')\n }\n\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2\n } else {\n return encryption ? session.cs2 : session.cs1\n }\n }\n\n private setRemoteEarlyData (data: Uint8Array|null|undefined): void {\n if (data) {\n this.remoteEarlyData = data\n }\n }\n}\n","\nexport class UnexpectedPeerError extends Error {\n public code: string\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.code = UnexpectedPeerError.code\n }\n\n static get code () {\n return 'ERR_UNEXPECTED_PEER'\n }\n}\n\nexport class InvalidCryptoExchangeError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.code = InvalidCryptoExchangeError.code\n }\n\n static get code () {\n return 'ERR_INVALID_CRYPTO_EXCHANGE'\n }\n}\n\nexport class InvalidCryptoTransmissionError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto transmission') {\n super(message)\n this.code = InvalidCryptoTransmissionError.code\n }\n\n static get code () {\n return 'ERR_INVALID_CRYPTO_TRANSMISSION'\n }\n}\n","import type { bytes32, bytes } from '../@types/basic.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport { isValidPublicKey } from '../utils.js'\nimport type { CipherState, HandshakeState, MessageBuffer, NoiseSession } from '../@types/handshake.js'\nimport { AbstractHandshake } from './abstract-handshake.js'\n\nexport class XX extends AbstractHandshake {\n private initializeInitiator (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private initializeResponder (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private writeMessageA (hs: HandshakeState, payload: bytes, e?: KeyPair): MessageBuffer {\n const ns = new Uint8Array(0)\n\n if (e !== undefined) {\n hs.e = e\n } else {\n hs.e = this.crypto.generateX25519KeyPair()\n }\n\n const ne = hs.e.publicKey\n\n this.mixHash(hs.ss, ne)\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageB (hs: HandshakeState, payload: bytes): MessageBuffer {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageC (hs: HandshakeState, payload: bytes): { messageBuffer: MessageBuffer, cs1: CipherState, cs2: CipherState, h: bytes } {\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n const ne = this.createEmptyKey()\n const messageBuffer: MessageBuffer = { ne, ns, ciphertext }\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, messageBuffer, cs1, cs2 }\n }\n\n private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n return this.decryptAndHash(hs.ss, message.ciphertext)\n }\n\n private readMessageB (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n return { plaintext, valid: (valid1 && valid2) }\n }\n\n private readMessageC (hs: HandshakeState, message: MessageBuffer): {h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState} {\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, plaintext, valid: (valid1 && valid2), cs1, cs2 }\n }\n\n public initSession (initiator: boolean, prologue: bytes32, s: KeyPair): NoiseSession {\n const psk = this.createEmptyKey()\n const rs = new Uint8Array(32) // no static key yet\n let hs\n\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk)\n } else {\n hs = this.initializeResponder(prologue, s, rs, psk)\n }\n\n return {\n hs,\n i: initiator,\n mc: 0\n }\n }\n\n public sendMessage (session: NoiseSession, message: bytes, ephemeral?: KeyPair): MessageBuffer {\n let messageBuffer: MessageBuffer\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message, ephemeral)\n } else if (session.mc === 1) {\n messageBuffer = this.writeMessageB(session.hs, message)\n } else if (session.mc === 2) {\n const { h, messageBuffer: resultingBuffer, cs1, cs2 } = this.writeMessageC(session.hs, message)\n messageBuffer = resultingBuffer\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n } else if (session.mc > 2) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs1, message)\n } else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs2, message)\n }\n } else {\n throw new Error('Session invalid.')\n }\n\n session.mc++\n return messageBuffer\n }\n\n public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n let plaintext: bytes = new Uint8Array(0)\n let valid = false\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message))\n } else if (session.mc === 1) {\n ({ plaintext, valid } = this.readMessageB(session.hs, message))\n } else if (session.mc === 2) {\n const { h, plaintext: resultingPlaintext, valid: resultingValid, cs1, cs2 } = this.readMessageC(session.hs, message)\n plaintext = resultingPlaintext\n valid = resultingValid\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n }\n session.mc++\n return { plaintext, valid }\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { InvalidCryptoExchangeError, UnexpectedPeerError } from '@libp2p/interface-connection-encrypter/errors'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { CipherState, NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { decode0, decode1, decode2, encode0, encode1, encode2 } from './encoder.js'\nimport { XX } from './handshakes/xx.js'\nimport {\n logger,\n logLocalStaticKeys,\n logLocalEphemeralKeys,\n logRemoteEphemeralKey,\n logRemoteStaticKey,\n logCipherState\n} from './logger.js'\nimport {\n decodePayload,\n getPeerIdFromPayload,\n verifySignedPayload\n} from './utils.js'\n\nexport class XXHandshake implements IHandshake {\n public isInitiator: boolean\n public session: NoiseSession\n public remotePeer!: PeerId\n public remoteEarlyData: bytes\n\n protected payload: bytes\n protected connection: ProtobufStream\n protected xx: XX\n protected staticKeypair: KeyPair\n\n private readonly prologue: bytes32\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n remotePeer?: PeerId,\n handshake?: XX\n ) {\n this.isInitiator = isInitiator\n this.payload = payload\n this.prologue = prologue\n this.staticKeypair = staticKeypair\n this.connection = connection\n if (remotePeer) {\n this.remotePeer = remotePeer\n }\n this.xx = handshake ?? new XX(crypto)\n this.session = this.xx.initSession(this.isInitiator, this.prologue, this.staticKeypair)\n this.remoteEarlyData = new Uint8Array(0)\n }\n\n // stage 0\n public async propose (): Promise {\n logLocalStaticKeys(this.session.hs.s)\n if (this.isInitiator) {\n logger('Stage 0 - Initiator starting to send first message.')\n const messageBuffer = this.xx.sendMessage(this.session, new Uint8Array(0))\n this.connection.writeLP(encode0(messageBuffer))\n logger('Stage 0 - Initiator finished sending first message.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger('Stage 0 - Responder waiting to receive first message...')\n const receivedMessageBuffer = decode0((await this.connection.readLP()).subarray())\n const { valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 0 validation fail')\n }\n logger('Stage 0 - Responder received first message.')\n logRemoteEphemeralKey(this.session.hs.re)\n }\n }\n\n // stage 1\n public async exchange (): Promise {\n if (this.isInitiator) {\n logger('Stage 1 - Initiator waiting to receive first message from responder...')\n const receivedMessageBuffer = decode1((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 1 validation fail')\n }\n logger('Stage 1 - Initiator received the message.')\n logRemoteEphemeralKey(this.session.hs.re)\n logRemoteStaticKey(this.session.hs.rs)\n\n logger(\"Initiator going to check remote's signature...\")\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n logger('All good with the signature!')\n } else {\n logger('Stage 1 - Responder sending out first message with signed payload and static key.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode1(messageBuffer))\n logger('Stage 1 - Responder sent the second handshake message with signed payload.')\n logLocalEphemeralKeys(this.session.hs.e)\n }\n }\n\n // stage 2\n public async finish (): Promise {\n if (this.isInitiator) {\n logger('Stage 2 - Initiator sending third handshake message.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode2(messageBuffer))\n logger('Stage 2 - Initiator sent message with signed payload.')\n } else {\n logger('Stage 2 - Responder waiting for third handshake message...')\n const receivedMessageBuffer = decode2((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 2 validation fail')\n }\n logger('Stage 2 - Responder received the message, finished handshake.')\n\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n }\n logCipherState(this.session)\n }\n\n public encrypt (plaintext: Uint8Array, session: NoiseSession): bytes {\n const cs = this.getCS(session)\n\n return this.xx.encryptWithAd(cs, new Uint8Array(0), plaintext)\n }\n\n public decrypt (ciphertext: Uint8Array, session: NoiseSession): {plaintext: bytes, valid: boolean} {\n const cs = this.getCS(session, false)\n\n return this.xx.decryptWithAd(cs, new Uint8Array(0), ciphertext)\n }\n\n public getRemoteStaticKey (): bytes {\n return this.session.hs.rs\n }\n\n private getCS (session: NoiseSession, encryption = true): CipherState {\n if (!session.cs1 || !session.cs2) {\n throw new InvalidCryptoExchangeError('Handshake not completed properly, cipher state does not exist.')\n }\n\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2\n } else {\n return encryption ? session.cs2 : session.cs1\n }\n }\n\n protected setRemoteEarlyData (data: Uint8Array|null|undefined): void {\n if (data) {\n this.remoteEarlyData = data\n }\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport { XXHandshake } from './handshake-xx.js'\nimport type { XX } from './handshakes/xx.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { decode0, decode1 } from './encoder.js'\nimport { logger, logLocalEphemeralKeys, logRemoteEphemeralKey, logRemoteStaticKey } from './logger.js'\nimport { decodePayload, getPeerIdFromPayload, verifySignedPayload } from './utils.js'\n\nexport class XXFallbackHandshake extends XXHandshake {\n private readonly ephemeralKeys?: KeyPair\n private readonly initialMsg: bytes\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n initialMsg: bytes,\n remotePeer?: PeerId,\n ephemeralKeys?: KeyPair,\n handshake?: XX\n ) {\n super(isInitiator, payload, prologue, crypto, staticKeypair, connection, remotePeer, handshake)\n if (ephemeralKeys) {\n this.ephemeralKeys = ephemeralKeys\n }\n this.initialMsg = initialMsg\n }\n\n // stage 0\n // eslint-disable-next-line require-await\n public async propose (): Promise {\n if (this.isInitiator) {\n this.xx.sendMessage(this.session, new Uint8Array(0), this.ephemeralKeys)\n logger('XX Fallback Stage 0 - Initialized state as the first message was sent by initiator.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger('XX Fallback Stage 0 - Responder decoding initial msg from IK.')\n const receivedMessageBuffer = decode0(this.initialMsg)\n const { valid } = this.xx.recvMessage(this.session, {\n ne: receivedMessageBuffer.ne,\n ns: new Uint8Array(0),\n ciphertext: new Uint8Array(0)\n })\n if (!valid) {\n throw new Error('xx fallback stage 0 decryption validation fail')\n }\n logger('XX Fallback Stage 0 - Responder used received message from IK.')\n logRemoteEphemeralKey(this.session.hs.re)\n }\n }\n\n // stage 1\n public async exchange (): Promise {\n if (this.isInitiator) {\n const receivedMessageBuffer = decode1(this.initialMsg)\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new Error('xx fallback stage 1 decryption validation fail')\n }\n logger('XX Fallback Stage 1 - Initiator used received message from IK.')\n logRemoteEphemeralKey(this.session.hs.re)\n logRemoteStaticKey(this.session.hs.rs)\n\n logger(\"Initiator going to check remote's signature...\")\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n } catch (e) {\n const err = e as Error\n throw new Error(`Error occurred while verifying signed payload from responder: ${err.message}`)\n }\n logger('All good with the signature!')\n } else {\n logger('XX Fallback Stage 1 - Responder start')\n await super.exchange()\n logger('XX Fallback Stage 1 - Responder end')\n }\n }\n}\n","\nexport function mapIterable (iter: IterableIterator, map: (val: T) => R): IterableIterator {\n const iterator: IterableIterator = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerMap {\n private readonly map: Map\n\n constructor (map?: PeerMap) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value)\n }\n }\n }\n\n [Symbol.iterator] () {\n return this.entries()\n }\n\n clear () {\n this.map.clear()\n }\n\n delete (peer: PeerId) {\n this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, T], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [peerIdFromString(val[0]), val[1]]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap) => void): void {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T) {\n this.map.set(peer.toString(), value)\n }\n\n keys (): IterableIterator {\n return mapIterable(\n this.map.keys(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n values () {\n return this.map.values()\n }\n\n get size () {\n return this.map.size\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerSet {\n private readonly set: Set\n\n constructor (set?: PeerSet | Iterable) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size () {\n return this.set.size\n }\n\n [Symbol.iterator] () {\n return this.values()\n }\n\n add (peer: PeerId) {\n this.set.add(peer.toString())\n }\n\n clear () {\n this.set.clear()\n }\n\n delete (peer: PeerId) {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const id = peerIdFromString(str)\n\n predicate(id, id, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values () {\n return mapIterable(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as list entries because list entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerList {\n private readonly list: string[]\n\n constructor (list?: PeerList) {\n this.list = []\n\n if (list != null) {\n for (const value of list) {\n this.list.push(value.toString())\n }\n }\n }\n\n [Symbol.iterator] () {\n return mapIterable<[number, string], PeerId>(\n this.list.entries(),\n (val) => {\n return peerIdFromString(val[1])\n }\n )\n }\n\n concat (list: PeerList) {\n const output = new PeerList(this)\n\n for (const value of list) {\n output.push(value)\n }\n\n return output\n }\n\n entries (): IterableIterator<[number, PeerId]> {\n return mapIterable<[number, string], [number, PeerId]>(\n this.list.entries(),\n (val) => {\n return [val[0], peerIdFromString(val[1])]\n }\n )\n }\n\n every (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): boolean {\n return this.list.every((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n filter (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerList {\n const output = new PeerList()\n\n this.list.forEach((str, index) => {\n const peerId = peerIdFromString(str)\n\n if (predicate(peerId, index, this)) {\n output.push(peerId)\n }\n })\n\n return output\n }\n\n find (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerId | undefined {\n const str = this.list.find((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n findIndex (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): number {\n return this.list.findIndex((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n forEach (predicate: (peerId: PeerId, index: number, arr: PeerList) => void): void {\n this.list.forEach((str, index) => {\n predicate(peerIdFromString(str), index, this)\n })\n }\n\n includes (peerId: PeerId): boolean {\n return this.list.includes(peerId.toString())\n }\n\n indexOf (peerId: PeerId): number {\n return this.list.indexOf(peerId.toString())\n }\n\n pop (): PeerId | undefined {\n const str = this.list.pop()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n push (...peerIds: PeerId[]) {\n for (const peerId of peerIds) {\n this.list.push(peerId.toString())\n }\n }\n\n shift (): PeerId | undefined {\n const str = this.list.shift()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n unshift (...peerIds: PeerId[]) {\n let len = this.list.length\n\n for (let i = peerIds.length - 1; i > -1; i--) {\n len = this.list.unshift(peerIds[i].toString())\n }\n\n return len\n }\n\n get length () {\n return this.list.length\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport type { bytes32 } from './@types/basic.js'\n\n/**\n * Storage for static keys of previously connected peers.\n */\nclass Keycache {\n private readonly storage = new PeerMap()\n\n public store (peerId: PeerId, key: bytes32): void {\n this.storage.set(peerId, key)\n }\n\n public load (peerId?: PeerId): bytes32 | null {\n if (!peerId) {\n return null\n }\n return this.storage.get(peerId) ?? null\n }\n\n public resetStorage (): void {\n this.storage.clear()\n }\n}\n\nconst KeyCache = new Keycache()\nexport {\n KeyCache\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport { pbStream, ProtobufStream } from 'it-pb-stream'\nimport { duplexPair } from 'it-pair/duplex'\nimport { pipe } from 'it-pipe'\nimport { encode, decode } from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport type { bytes } from './@types/basic.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { INoiseConnection, KeyPair } from './@types/libp2p.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { stablelib } from './crypto/stablelib.js'\nimport { decryptStream, encryptStream } from './crypto/streaming.js'\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js'\nimport type { FailedIKError } from './errors.js'\nimport { IKHandshake } from './handshake-ik.js'\nimport { XXHandshake } from './handshake-xx.js'\nimport { XXFallbackHandshake } from './handshake-xx-fallback.js'\nimport { KeyCache } from './keycache.js'\nimport { logger } from './logger.js'\nimport { getPayload } from './utils.js'\n\ninterface HandshakeParams {\n connection: ProtobufStream\n isInitiator: boolean\n localPeer: PeerId\n remotePeer?: PeerId\n}\n\nexport class Noise implements INoiseConnection {\n public protocol = '/noise'\n public crypto: ICryptoInterface\n\n private readonly prologue = new Uint8Array(0)\n private readonly staticKeys: KeyPair\n private readonly earlyData?: bytes\n private readonly useNoisePipes: boolean\n\n /**\n * @param {bytes} staticNoiseKey - x25519 private key, reuse for faster handshakes\n * @param {bytes} earlyData\n */\n constructor (staticNoiseKey?: bytes, earlyData?: bytes, crypto: ICryptoInterface = stablelib) {\n this.earlyData = earlyData ?? new Uint8Array(0)\n // disabled until properly specked\n this.useNoisePipes = false\n this.crypto = crypto\n\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKeys = this.crypto.generateX25519KeyPairFromSeed(staticNoiseKey)\n } else {\n this.staticKeys = this.crypto.generateX25519KeyPair()\n }\n }\n\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer\n * @param {any} connection - streaming iterable duplex that will be encrypted\n * @param {PeerId} remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer.\n * @returns {Promise}\n */\n public async secureOutbound (localPeer: PeerId, connection: any, remotePeer: PeerId): Promise {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: true,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remoteEarlyData: handshake.remoteEarlyData,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer.\n * @param {any} connection - streaming iterable duplex that will be encryption.\n * @param {PeerId} remotePeer - optional PeerId of the initiating peer, if known. This may only exist during transport upgrades.\n * @returns {Promise}\n */\n public async secureInbound (localPeer: PeerId, connection: any, remotePeer?: PeerId): Promise {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: false,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remoteEarlyData: handshake.remoteEarlyData,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * If Noise pipes supported, tries IK handshake first with XX as fallback if it fails.\n * If noise pipes disabled or remote peer static key is unknown, use XX.\n *\n * @param {HandshakeParams} params\n */\n private async performHandshake (params: HandshakeParams): Promise {\n const payload = await getPayload(params.localPeer, this.staticKeys.publicKey, this.earlyData)\n let tryIK = this.useNoisePipes\n if (params.isInitiator && KeyCache.load(params.remotePeer) === null) {\n // if we are initiator and remote static key is unknown, don't try IK\n tryIK = false\n }\n // Try IK if acting as responder or initiator that has remote's static key.\n if (tryIK) {\n // Try IK first\n const { remotePeer, connection, isInitiator } = params\n const ikHandshake = new IKHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n // safe to cast as we did checks\n KeyCache.load(params.remotePeer) ?? new Uint8Array(32),\n remotePeer as PeerId\n )\n\n try {\n return await this.performIKHandshake(ikHandshake)\n } catch (e) {\n const err = e as FailedIKError\n\n // IK failed, go to XX fallback\n let ephemeralKeys\n if (params.isInitiator) {\n ephemeralKeys = ikHandshake.getLocalEphemeralKeys()\n }\n return await this.performXXFallbackHandshake(params, payload, err.initialMsg as Uint8Array, ephemeralKeys)\n }\n } else {\n // run XX handshake\n return await this.performXXHandshake(params, payload)\n }\n }\n\n private async performXXFallbackHandshake (\n params: HandshakeParams,\n payload: bytes,\n initialMsg: bytes,\n ephemeralKeys?: KeyPair\n ): Promise {\n const { isInitiator, remotePeer, connection } = params\n const handshake =\n new XXFallbackHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n initialMsg,\n remotePeer,\n ephemeralKeys\n )\n\n try {\n await handshake.propose()\n await handshake.exchange()\n await handshake.finish()\n } catch (e) {\n const err = e as Error\n err.message = `Error occurred during XX Fallback handshake: ${err.message}`\n logger(err)\n throw err\n }\n\n return handshake\n }\n\n private async performXXHandshake (\n params: HandshakeParams,\n payload: bytes\n ): Promise {\n const { isInitiator, remotePeer, connection } = params\n const handshake = new XXHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n remotePeer\n )\n\n try {\n await handshake.propose()\n await handshake.exchange()\n await handshake.finish()\n\n if (this.useNoisePipes && handshake.remotePeer) {\n KeyCache.store(handshake.remotePeer, handshake.getRemoteStaticKey())\n }\n } catch (e: unknown) {\n if (e instanceof Error) {\n e.message = `Error occurred during XX handshake: ${e.message}`\n throw e\n }\n }\n\n return handshake\n }\n\n private async performIKHandshake (\n handshake: IKHandshake\n ): Promise {\n await handshake.stage0()\n await handshake.stage1()\n\n return handshake\n }\n\n private async createSecureConnection (\n connection: ProtobufStream,\n handshake: IHandshake\n ): Promise> {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair()\n const network = connection.unwrap()\n\n await pipe(\n secure, // write to wrapper\n encryptStream(handshake), // data is encrypted\n encode({ lengthEncoder: uint16BEEncode }), // prefix with message length\n network, // send to the remote peer\n decode({ lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake), // decrypt the incoming data\n secure // pipe to the wrapper\n )\n\n return user\n }\n}\n","import { pair } from './index.js'\nimport type { Duplex } from 'it-stream-types'\n\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair (): [Duplex, Duplex] {\n const a = pair()\n const b = pair()\n return [\n {\n source: a.source,\n sink: b.sink\n },\n {\n source: b.source,\n sink: a.sink\n }\n ]\n}\n","import type { Transform } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { IHandshake } from '../@types/handshake-interface.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js'\n\n// Returns generator that encrypts payload from the user\nexport function encryptStream (handshake: IHandshake): Transform {\n return async function * (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG\n if (end > chunk.length) {\n end = chunk.length\n }\n\n const data = handshake.encrypt(chunk.subarray(i, end), handshake.session)\n yield data\n }\n }\n }\n}\n\n// Decrypt received payload to the user\nexport function decryptStream (handshake: IHandshake): Transform {\n return async function * (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES\n if (end > chunk.length) {\n end = chunk.length\n }\n\n const { plaintext: decrypted, valid } = await handshake.decrypt(chunk.subarray(i, end), handshake.session)\n if (!valid) {\n throw new Error('Failed to validate decrypted chunk')\n }\n yield decrypted\n }\n }\n }\n}\n","import { Noise } from './noise.js'\n\nexport * from './crypto.js'\nexport * from './crypto/stablelib.js'\nexport * from './noise.js'\n\n/**\n * Default configuration, it will generate new noise static key and enable noise pipes (IK handshake).\n */\nexport const NOISE = new Noise()\n","export function allocUnsafe (size: number) {\n return new Uint8Array(size)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\ntype INITIATOR_NAME = 'NEW_STREAM' | 'MESSAGE' | 'CLOSE' | 'RESET'\ntype RECEIVER_NAME = 'MESSAGE' | 'CLOSE' | 'RESET'\ntype NAME = 'NEW_STREAM' | 'MESSAGE_INITIATOR' | 'CLOSE_INITIATOR' | 'RESET_INITIATOR' | 'MESSAGE_RECEIVER' | 'CLOSE_RECEIVER' | 'RESET_RECEIVER'\ntype CODE = 0 | 1 | 2 | 3 | 4 | 5 | 6\n\nexport enum MessageTypes {\n NEW_STREAM = 0,\n MESSAGE_RECEIVER = 1,\n MESSAGE_INITIATOR = 2,\n CLOSE_RECEIVER = 3,\n CLOSE_INITIATOR = 4,\n RESET_RECEIVER = 5,\n RESET_INITIATOR = 6\n}\n\nexport const MessageTypeNames: Record = Object.freeze({\n 0: 'NEW_STREAM',\n 1: 'MESSAGE_RECEIVER',\n 2: 'MESSAGE_INITIATOR',\n 3: 'CLOSE_RECEIVER',\n 4: 'CLOSE_INITIATOR',\n 5: 'RESET_RECEIVER',\n 6: 'RESET_INITIATOR'\n})\n\nexport const InitiatorMessageTypes: Record = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n})\n\nexport const ReceiverMessageTypes: Record = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n})\n\nexport interface NewStreamMessage {\n id: number\n type: MessageTypes.NEW_STREAM\n data: Uint8Array | Uint8ArrayList\n}\n\nexport interface MessageReceiverMessage {\n id: number\n type: MessageTypes.MESSAGE_RECEIVER\n data: Uint8Array | Uint8ArrayList\n}\n\nexport interface MessageInitiatorMessage {\n id: number\n type: MessageTypes.MESSAGE_INITIATOR\n data: Uint8Array | Uint8ArrayList\n}\n\nexport interface CloseReceiverMessage {\n id: number\n type: MessageTypes.CLOSE_RECEIVER\n}\n\nexport interface CloseInitiatorMessage {\n id: number\n type: MessageTypes.CLOSE_INITIATOR\n}\n\nexport interface ResetReceiverMessage {\n id: number\n type: MessageTypes.RESET_RECEIVER\n}\n\nexport interface ResetInitiatorMessage {\n id: number\n type: MessageTypes.RESET_INITIATOR\n}\n\nexport type Message = NewStreamMessage | MessageReceiverMessage | MessageInitiatorMessage | CloseReceiverMessage | CloseInitiatorMessage | ResetReceiverMessage | ResetInitiatorMessage\n","import type { Source } from 'it-stream-types'\nimport varint from 'varint'\nimport { allocUnsafe } from './alloc-unsafe.js'\nimport { Message, MessageTypes } from './message-types.js'\n\nconst POOL_SIZE = 10 * 1024\n\nclass Encoder {\n private _pool: Uint8Array\n private _poolOffset: number\n\n constructor () {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n }\n\n /**\n * Encodes the given message and returns it and its header\n */\n write (msg: Message): Uint8Array[] {\n const pool = this._pool\n let offset = this._poolOffset\n\n varint.encode(msg.id << 3 | msg.type, pool, offset)\n offset += varint.encode.bytes\n\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n varint.encode(msg.data.length, pool, offset)\n } else {\n varint.encode(0, pool, offset)\n }\n\n offset += varint.encode.bytes\n\n const header = pool.subarray(this._poolOffset, offset)\n\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n } else {\n this._poolOffset = offset\n }\n\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n return [\n header,\n msg.data instanceof Uint8Array ? msg.data : msg.data.subarray()\n ]\n }\n\n return [\n header\n ]\n }\n}\n\nconst encoder = new Encoder()\n\n/**\n * Encode and yield one or more messages\n */\nexport async function * encode (source: Source) {\n for await (const msg of source) {\n if (Array.isArray(msg)) {\n for (const m of msg) {\n yield * encoder.write(m)\n }\n } else {\n yield * encoder.write(msg)\n }\n }\n}\n","import { MessageTypeNames, MessageTypes } from './message-types.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Source } from 'it-stream-types'\nimport type { Message } from './message-types.js'\n\ninterface MessageHeader {\n id: number\n type: keyof typeof MessageTypeNames\n offset: number\n length: number\n}\n\nclass Decoder {\n private readonly _buffer: Uint8ArrayList\n private _headerInfo: MessageHeader | null\n\n constructor () {\n this._buffer = new Uint8ArrayList()\n this._headerInfo = null\n }\n\n write (chunk: Uint8Array) {\n if (chunk == null || chunk.length === 0) {\n return []\n }\n\n this._buffer.append(chunk)\n const msgs: Message[] = []\n\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer)\n } catch (_) {\n break // We haven't received enough data yet\n }\n }\n\n const { id, type, length, offset } = this._headerInfo\n const bufferedDataLength = this._buffer.length - offset\n\n if (bufferedDataLength < length) {\n break // not enough data yet\n }\n\n const msg: any = {\n id,\n type\n }\n\n if (type === MessageTypes.NEW_STREAM || type === MessageTypes.MESSAGE_INITIATOR || type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = this._buffer.subarray(offset, offset + length)\n }\n\n msgs.push(msg)\n\n this._buffer.consume(offset + length)\n this._headerInfo = null\n }\n\n return msgs\n }\n\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader (data: Uint8ArrayList): MessageHeader {\n const {\n value: h,\n offset\n } = readVarInt(data)\n const {\n value: length,\n offset: end\n } = readVarInt(data, offset)\n\n const type = h & 7\n\n // @ts-expect-error h is a number not a CODE\n if (MessageTypeNames[type] == null) {\n throw new Error(`Invalid type received: ${type}`)\n }\n\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length }\n }\n}\n\nconst MSB = 0x80\nconst REST = 0x7F\n\nfunction readVarInt (buf: Uint8ArrayList, offset: number = 0) {\n let res = 0\n let shift = 0\n let counter = offset\n let b: number\n const l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n offset = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf.get(counter++)\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n offset = counter - offset\n\n return {\n value: res,\n offset\n }\n}\n\n/**\n * Decode a chunk and yield an _array_ of decoded messages\n */\nexport async function * decode (source: Source) {\n const decoder = new Decoder()\n\n for await (const chunk of source) {\n const msgs = decoder.write(chunk)\n\n if (msgs.length > 0) {\n yield msgs\n }\n }\n}\n","import { Message, MessageTypes } from './message-types.js'\nimport type { Source, Transform } from 'it-stream-types'\n\nexport const MAX_MSG_SIZE = 1 << 20 // 1MB\n\n/**\n * Creates an iterable transform that restricts message sizes to\n * the given maximum size.\n */\nexport function restrictSize (max?: number): Transform {\n const maxSize = max ?? MAX_MSG_SIZE\n\n const checkSize = (msg: Message) => {\n if (msg.type !== MessageTypes.NEW_STREAM && msg.type !== MessageTypes.MESSAGE_INITIATOR && msg.type !== MessageTypes.MESSAGE_RECEIVER) {\n return\n }\n\n if (msg.data.byteLength > maxSize) {\n throw Object.assign(new Error('message size too large!'), { code: 'ERR_MSG_TOO_BIG' })\n }\n }\n\n return (source: Source) => {\n return (async function * restrictSize () {\n for await (const msg of source) {\n if (Array.isArray(msg)) {\n msg.forEach(checkSize)\n yield * msg\n } else {\n checkSize(msg)\n yield msg\n }\n }\n })()\n }\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { pushable } from 'it-pushable'\nimport errCode from 'err-code'\nimport { MAX_MSG_SIZE } from './restrict-size.js'\nimport { anySignal } from 'any-signal'\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { logger } from '@libp2p/logger'\nimport type { Message } from './message-types.js'\nimport type { StreamTimeline } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { MplexStream } from './mplex.js'\n\nconst log = logger('libp2p:mplex:stream')\n\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET'\nconst ERR_STREAM_ABORT = 'ERR_STREAM_ABORT'\nconst ERR_SINK_ENDED = 'ERR_SINK_ENDED'\nconst ERR_DOUBLE_SINK = 'ERR_DOUBLE_SINK'\n\nexport interface Options {\n id: number\n send: (msg: Message) => void\n name?: string\n onEnd?: (err?: Error) => void\n type?: 'initiator' | 'receiver'\n maxMsgSize?: number\n}\n\nexport function createStream (options: Options): MplexStream {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options\n\n const abortController = new AbortController()\n const resetController = new AbortController()\n const closeController = new AbortController()\n const Types = type === 'initiator' ? InitiatorMessageTypes : ReceiverMessageTypes\n const externalId = type === 'initiator' ? (`i${id}`) : `r${id}`\n const streamName = `${name == null ? id : name}`\n\n let sourceEnded = false\n let sinkEnded = false\n let sinkSunk = false\n let endErr: Error | undefined\n\n const timeline: StreamTimeline = {\n open: Date.now()\n }\n\n const onSourceEnd = (err?: Error) => {\n if (sourceEnded) {\n return\n }\n\n sourceEnded = true\n log.trace('%s stream %s source end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sinkEnded) {\n stream.stat.timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const onSinkEnd = (err?: Error) => {\n if (sinkEnded) {\n return\n }\n\n sinkEnded = true\n log.trace('%s stream %s sink end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sourceEnded) {\n timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const stream: MplexStream = {\n // Close for both Reading and Writing\n close: () => {\n log.trace('%s stream %s close', type, streamName)\n\n stream.closeRead()\n stream.closeWrite()\n },\n\n // Close for reading\n closeRead: () => {\n log.trace('%s stream %s closeRead', type, streamName)\n\n if (sourceEnded) {\n return\n }\n\n stream.source.end()\n },\n\n // Close for writing\n closeWrite: () => {\n log.trace('%s stream %s closeWrite', type, streamName)\n\n if (sinkEnded) {\n return\n }\n\n closeController.abort()\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n // Close for reading and writing (local error)\n abort: (err: Error) => {\n log.trace('%s stream %s abort', type, streamName, err)\n // End the source with the passed error\n stream.source.end(err)\n abortController.abort()\n onSinkEnd(err)\n },\n\n // Close immediately for reading and writing (remote error)\n reset: () => {\n const err = errCode(new Error('stream reset'), ERR_STREAM_RESET)\n resetController.abort()\n stream.source.end(err)\n onSinkEnd(err)\n },\n\n sink: async (source: Source) => {\n if (sinkSunk) {\n throw errCode(new Error('sink already called on stream'), ERR_DOUBLE_SINK)\n }\n\n sinkSunk = true\n\n if (sinkEnded) {\n throw errCode(new Error('stream closed for writing'), ERR_SINK_ENDED)\n }\n\n source = abortableSource(source, anySignal([\n abortController.signal,\n resetController.signal,\n closeController.signal\n ]))\n\n try {\n if (type === 'initiator') { // If initiator, open a new stream\n send({ id, type: InitiatorMessageTypes.NEW_STREAM, data: uint8ArrayFromString(streamName) })\n }\n\n const uint8ArrayList = new Uint8ArrayList()\n\n for await (const data of source) {\n uint8ArrayList.append(data)\n\n while (uint8ArrayList.length !== 0) {\n if (uint8ArrayList.length <= maxMsgSize) {\n send({ id, type: Types.MESSAGE, data: uint8ArrayList.subarray() })\n uint8ArrayList.consume(uint8ArrayList.length)\n break\n }\n\n const toSend = uint8ArrayList.length - maxMsgSize\n send({ id, type: Types.MESSAGE, data: uint8ArrayList.subarray(0, toSend) })\n uint8ArrayList.consume(toSend)\n }\n }\n } catch (err: any) {\n if (err.type === 'aborted' && err.message === 'The operation was aborted') {\n if (closeController.signal.aborted) {\n return\n }\n\n if (resetController.signal.aborted) {\n err.message = 'stream reset'\n err.code = ERR_STREAM_RESET\n }\n\n if (abortController.signal.aborted) {\n err.message = 'stream aborted'\n err.code = ERR_STREAM_ABORT\n }\n }\n\n // Send no more data if this stream was remotely reset\n if (err.code === ERR_STREAM_RESET) {\n log.trace('%s stream %s reset', type, name)\n } else {\n log.trace('%s stream %s error', type, name, err)\n try {\n send({ id, type: Types.RESET })\n } catch (err) {\n log.trace('%s stream %s error sending reset', type, name, err)\n }\n }\n\n stream.source.end(err)\n onSinkEnd(err)\n return\n }\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n source: pushable({\n onEnd: onSourceEnd\n }),\n\n stat: {\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n timeline\n },\n\n metadata: {},\n\n id: externalId\n }\n\n return stream\n}\n","import type { ComponentMetricsTracker } from '@libp2p/interface-metrics'\n\nexport interface TrackedMapInit {\n metrics: ComponentMetricsTracker\n system?: string\n component: string\n metric: string\n}\n\nclass TrackedMap extends Map {\n private readonly system: string\n private readonly component: string\n private readonly metric: string\n private readonly metrics: ComponentMetricsTracker\n\n constructor (init: TrackedMapInit) {\n super()\n\n const { system, component, metric, metrics } = init\n this.system = system ?? 'libp2p'\n this.component = component\n this.metric = metric\n this.metrics = metrics\n\n this.updateComponentMetric()\n }\n\n set (key: K, value: V) {\n super.set(key, value)\n this.updateComponentMetric()\n return this\n }\n\n delete (key: K) {\n const deleted = super.delete(key)\n this.updateComponentMetric()\n return deleted\n }\n\n clear () {\n super.clear()\n this.updateComponentMetric()\n }\n\n private updateComponentMetric () {\n this.metrics.updateComponentMetric({\n system: this.system,\n component: this.component,\n metric: this.metric,\n value: this.size\n })\n }\n}\n\nexport interface CreateTrackedMapOptions {\n metrics?: ComponentMetricsTracker\n system?: string\n component: string\n metric: string\n}\n\nexport function trackedMap (config: CreateTrackedMapOptions): Map {\n const { system, component, metric, metrics } = config\n let map: Map\n\n if (metrics != null) {\n map = new TrackedMap({ system, component, metric, metrics })\n } else {\n map = new Map()\n }\n\n return map\n}\n","import { pipe } from 'it-pipe'\nimport { Pushable, pushableV } from 'it-pushable'\nimport { abortableSource } from 'abortable-iterator'\nimport { encode } from './encode.js'\nimport { decode } from './decode.js'\nimport { restrictSize } from './restrict-size.js'\nimport { MessageTypes, MessageTypeNames, Message } from './message-types.js'\nimport { createStream } from './stream.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport type { Components } from '@libp2p/components'\nimport type { Sink } from 'it-stream-types'\nimport type { StreamMuxer, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { MplexInit } from './index.js'\nimport anySignal from 'any-signal'\n\nconst log = logger('libp2p:mplex')\n\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4 // 4MB\n\nfunction printMessage (msg: Message) {\n const output: any = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n }\n\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray())\n }\n\n if (msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16')\n }\n\n return output\n}\n\nexport interface MplexStream extends Stream {\n source: Pushable\n}\n\ninterface MplexStreamMuxerInit extends MplexInit, StreamMuxerInit {}\n\nexport class MplexStreamMuxer implements StreamMuxer {\n public protocol = '/mplex/6.7.0'\n\n public sink: Sink\n public source: AsyncIterable\n\n private _streamId: number\n private readonly _streams: { initiators: Map, receivers: Map }\n private readonly _init: MplexStreamMuxerInit\n private readonly _source: { push: (val: Message) => void, end: (err?: Error) => void }\n private readonly closeController: AbortController\n\n constructor (components: Components, init?: MplexStreamMuxerInit) {\n init = init ?? {}\n\n this._streamId = 0\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: trackedMap({ metrics: components.getMetrics(), component: 'mplex', metric: 'initiatorStreams' }),\n /**\n * Stream to ids map\n */\n receivers: trackedMap({ metrics: components.getMetrics(), component: 'mplex', metric: 'receiverStreams' })\n }\n this._init = init\n\n /**\n * An iterable sink\n */\n this.sink = this._createSink()\n\n /**\n * An iterable source\n */\n const source = this._createSource()\n this._source = source\n this.source = source\n\n /**\n * Close controller\n */\n this.closeController = new AbortController()\n }\n\n init (components: Components) {}\n\n /**\n * Returns a Map of streams and their ids\n */\n get streams () {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams: Stream[] = []\n this._streams.initiators.forEach(stream => {\n streams.push(stream)\n })\n this._streams.receivers.forEach(stream => {\n streams.push(stream)\n })\n return streams\n }\n\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream (name?: string): Stream {\n if (this.closeController.signal.aborted) {\n throw new Error('Muxer already closed')\n }\n const id = this._streamId++\n name = name == null ? id.toString() : name.toString()\n const registry = this._streams.initiators\n return this._newStream({ id, name, type: 'initiator', registry })\n }\n\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n close (err?: Error | undefined): void {\n if (this.closeController.signal.aborted) return\n\n if (err != null) {\n this.streams.forEach(s => s.abort(err))\n } else {\n this.streams.forEach(s => s.close())\n }\n this.closeController.abort()\n }\n\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream (options: { id: number, name: string }) {\n const { id, name } = options\n const registry = this._streams.receivers\n return this._newStream({ id, name, type: 'receiver', registry })\n }\n\n _newStream (options: { id: number, name: string, type: 'initiator' | 'receiver', registry: Map }) {\n const { id, name, type, registry } = options\n\n log('new %s stream %s %s', type, id, name)\n\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw errCode(new Error('Too many outbound streams open'), 'ERR_TOO_MANY_OUTBOUND_STREAMS')\n }\n\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`)\n }\n\n const send = (msg: Message) => {\n if (log.enabled) {\n log.trace('%s stream %s send', type, id, printMessage(msg))\n }\n\n if (msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = msg.data instanceof Uint8Array ? msg.data : msg.data.subarray()\n }\n\n this._source.push(msg)\n }\n\n const onEnd = () => {\n log('%s stream %s ended', type, id, name)\n registry.delete(id)\n\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream)\n }\n }\n\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize })\n registry.set(id, stream)\n return stream\n }\n\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink () {\n const sink: Sink = async source => {\n // see: https://github.com/jacobheun/any-signal/pull/18\n const abortSignals = [this.closeController.signal]\n if (this._init.signal != null) {\n abortSignals.push(this._init.signal)\n }\n source = abortableSource(source, anySignal(abortSignals))\n\n try {\n await pipe(\n source,\n decode,\n restrictSize(this._init.maxMsgSize),\n async source => {\n for await (const msg of source) {\n this._handleIncoming(msg)\n }\n }\n )\n\n this._source.end()\n } catch (err: any) {\n log('error in sink', err)\n this._source.end(err) // End the source with an error\n }\n }\n\n return sink\n }\n\n /**\n * Creates a source that restricts outgoing message sizes\n * and varint encodes them\n */\n _createSource () {\n const onEnd = (err?: Error) => {\n this.close(err)\n }\n const source = pushableV({\n objectMode: true,\n onEnd\n })\n\n return Object.assign(encode(source), {\n push: source.push,\n end: source.end,\n return: source.return\n })\n }\n\n _handleIncoming (message: Message) {\n const { id, type } = message\n\n if (log.enabled) {\n log.trace('incoming message', printMessage(message))\n }\n\n // Create a new stream?\n if (message.type === MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n log.error('Too many inbound streams open')\n\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n\n this._source.push({\n id,\n type: MessageTypes.RESET_RECEIVER\n })\n\n return\n }\n\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) })\n\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream)\n }\n\n return\n }\n\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers\n const stream = list.get(id)\n\n if (stream == null) {\n log('missing stream %s', id)\n\n return\n }\n\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE\n\n switch (type) {\n case MessageTypes.MESSAGE_INITIATOR:\n case MessageTypes.MESSAGE_RECEIVER:\n if (stream.source.readableLength > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === MessageTypes.MESSAGE_INITIATOR ? MessageTypes.RESET_RECEIVER : MessageTypes.RESET_INITIATOR\n })\n\n // Inform the stream consumer they are not fast enough\n const error = errCode(new Error('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers'), 'ERR_STREAM_INPUT_BUFFER_FULL')\n stream.abort(error)\n\n return\n }\n\n // We got data from the remote, push it into our local stream\n stream.source.push(message.data.subarray())\n break\n case MessageTypes.CLOSE_INITIATOR:\n case MessageTypes.CLOSE_RECEIVER:\n // We should expect no more data from the remote, stop reading\n stream.closeRead()\n break\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // Stop reading and writing to the stream immediately\n stream.reset()\n break\n default:\n log('unknown message type %s', type)\n }\n }\n}\n","import { Components, Initializable } from '@libp2p/components'\nimport type { StreamMuxer, StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport { MplexStreamMuxer } from './mplex.js'\n\nexport interface MplexInit {\n /**\n * The maximum size of message that can be sent in one go in bytes.\n * Messages larger than this will be split into multiple smaller\n * messages.\n */\n maxMsgSize?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw.\n */\n maxInboundStreams?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw.\n */\n maxOutboundStreams?: number\n\n /**\n * Incoming stream messages are buffered until processed by the stream\n * handler. If the buffer reaches this size in bytes the stream will\n * be reset.\n */\n maxStreamBufferSize?: number\n}\n\nexport class Mplex implements StreamMuxerFactory, Initializable {\n public protocol = '/mplex/6.7.0'\n private readonly _init: MplexInit\n private components: Components = new Components()\n\n constructor (init: MplexInit = {}) {\n this._init = init\n }\n\n init (components: Components): void {\n this.components = components\n }\n\n createStreamMuxer (init: StreamMuxerInit = {}): StreamMuxer {\n return new MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n })\n }\n}\n","/* eslint-env browser */\n\nexport default WebSocket\n","\nimport { EventIterator } from 'event-iterator'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { WebSocket, ErrorEvent, MessageEvent } from 'ws'\n\n// copied from github.com/feross/buffer\n// Some ArrayBuffers are not passing the instanceof check, so we need to do a bit more work :(\nfunction isArrayBuffer (obj: any): obj is ArrayBuffer {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number')\n}\n\nexport interface ConnectedSource extends AsyncIterable {\n connected: () => Promise\n}\n\nexport default (socket: WebSocket): ConnectedSource => {\n socket.binaryType = 'arraybuffer'\n\n const connected = async () => await new Promise((resolve, reject) => {\n if (isConnected) {\n return resolve()\n }\n if (connError != null) {\n return reject(connError)\n }\n\n const cleanUp = (cont: () => void) => {\n socket.removeEventListener('open', onOpen)\n socket.removeEventListener('error', onError)\n cont()\n }\n\n const onOpen = () => cleanUp(resolve)\n const onError = (event: ErrorEvent) => {\n cleanUp(() => reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)))\n }\n\n socket.addEventListener('open', onOpen)\n socket.addEventListener('error', onError)\n })\n\n const source = (async function * () {\n const messages = new EventIterator(\n ({ push, stop, fail }) => {\n const onMessage = (event: MessageEvent) => {\n let data: Uint8Array | null = null\n\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data)\n }\n\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data)\n }\n\n if (event.data instanceof Uint8Array) {\n data = event.data\n }\n\n if (data == null) {\n return\n }\n\n push(data)\n }\n const onError = (event: ErrorEvent) => fail(event.error ?? new Error('Socket error'))\n\n socket.addEventListener('message', onMessage)\n socket.addEventListener('error', onError)\n socket.addEventListener('close', stop)\n\n return () => {\n socket.removeEventListener('message', onMessage)\n socket.removeEventListener('error', onError)\n socket.removeEventListener('close', stop)\n }\n },\n { highWaterMark: Infinity }\n )\n\n await connected()\n\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk\n }\n }())\n\n let isConnected = socket.readyState === 1\n let connError: Error | null\n\n socket.addEventListener('open', () => {\n isConnected = true\n connError = null\n })\n\n socket.addEventListener('close', () => {\n isConnected = false\n connError = null\n })\n\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)\n }\n })\n\n return Object.assign(source, {\n connected\n })\n}\n","import type { ErrorEvent, WebSocket } from 'ws'\n\nexport default (socket: WebSocket) => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed')\n }\n\n // if open, return\n if (socket.readyState === 1) {\n return\n }\n\n return new Promise((resolve, reject) => {\n function cleanup () {\n socket.removeEventListener('open', handleOpen)\n socket.removeEventListener('error', handleErr)\n }\n\n function handleOpen () {\n cleanup()\n resolve()\n }\n\n function handleErr (event: ErrorEvent) {\n cleanup()\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`))\n }\n\n socket.addEventListener('open', handleOpen)\n socket.addEventListener('error', handleErr)\n })\n}\n","import ready from './ready.js'\nimport type { WebSocket } from 'ws'\nimport type { Sink } from 'it-stream-types'\n\nexport interface SinkOptions {\n closeOnEnd?: boolean\n}\n\nexport default (socket: WebSocket, options: SinkOptions) => {\n options = options ?? {}\n options.closeOnEnd = options.closeOnEnd !== false\n\n const sink: Sink> = async source => {\n for await (const data of source) {\n try {\n await ready(socket)\n } catch (err: any) {\n if (err.message === 'socket closed') break\n throw err\n }\n\n socket.send(data)\n }\n\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n return await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve()\n } else {\n const err = Object.assign(new Error('ws error'), { event })\n reject(err)\n }\n })\n\n setTimeout(() => socket.close())\n })\n }\n }\n\n return sink\n}\n","import source from './source.js'\nimport sink from './sink.js'\nimport type WebSocket from './web-socket.js'\nimport type { SinkOptions } from './sink.js'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface DuplexWebSocket extends Duplex> {\n connected: () => Promise\n localAddress?: string\n localPort?: number\n remoteAddress: string\n remotePort: number\n close: () => Promise\n destroy: () => void\n socket: WebSocket\n}\n\nexport interface DuplexWebSocketOptions extends SinkOptions {\n remoteAddress?: string\n remotePort?: number\n}\n\nexport default (socket: WebSocket, options?: DuplexWebSocketOptions): DuplexWebSocket => {\n options = options ?? {}\n\n const connectedSource = source(socket)\n let remoteAddress: string | undefined = options.remoteAddress\n let remotePort: number | undefined = options.remotePort\n\n if (socket.url != null) {\n // only client->server sockets have urls, server->client connections do not\n try {\n const url = new URL(socket.url)\n remoteAddress = url.hostname\n remotePort = parseInt(url.port, 10)\n } catch {}\n }\n\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port')\n }\n\n const duplex: DuplexWebSocket = {\n sink: sink(socket, options),\n source: connectedSource,\n connected: async () => await connectedSource.connected(),\n close: async () => {\n if (socket.readyState === socket.CONNECTING || socket.readyState === socket.OPEN) {\n await new Promise((resolve) => {\n socket.addEventListener('close', () => {\n resolve()\n })\n socket.close()\n })\n }\n },\n destroy: () => {\n if (socket.terminate != null) {\n socket.terminate()\n } else {\n socket.close()\n }\n },\n remoteAddress,\n remotePort,\n socket\n }\n\n return duplex\n}\n","import { relative } from 'iso-url'\n\nconst map = { http: 'ws', https: 'wss' }\nconst def = 'ws'\n\nexport default (url: string, location: string | Partial) => relative(url, location, map, def)\n","// load websocket library if we are not in the browser\nimport WebSocket from './web-socket.js'\nimport duplex from './duplex.js'\nimport wsurl from './ws-url.js'\nimport type { ClientOptions } from 'ws'\nimport type { DuplexWebSocket } from './duplex.js'\nimport type { SinkOptions } from './sink.js'\n\nexport interface WebSocketOptions extends SinkOptions {\n websocket?: ClientOptions\n}\n\nexport function connect (addr: string, opts?: WebSocketOptions): DuplexWebSocket {\n const location = typeof window === 'undefined' ? '' : window.location\n opts = opts ?? {}\n\n const url = wsurl(addr, location.toString())\n const socket = new WebSocket(url, opts.websocket)\n\n return duplex(socket, opts)\n}\n","import { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MultiaddrToUriOpts {\n assumeHttp?: boolean\n}\n\ninterface Reducer { (str: string, content: string, i: number, parts: Part[], opts?: MultiaddrToUriOpts): string }\n\nconst reduceValue: Reducer = (_, v) => v\nconst tcpUri = (str: string, port: string, parts: Part[], opts?: MultiaddrToUriOpts) => {\n // return tcp when explicitly requested\n if ((opts != null) && opts.assumeHttp === false) return `tcp://${str}:${port}`\n // check if tcp is the last protocol in multiaddr\n let protocol = 'tcp'\n let explicitPort = `:${port}`\n const last = parts[parts.length - 1]\n if (last.protocol === 'tcp') {\n // assume http and produce clean urls\n protocol = port === '443' ? 'https' : 'http'\n explicitPort = port === '443' || port === '80' ? '' : explicitPort\n }\n return `${protocol}://${str}${explicitPort}`\n}\n\nconst Reducers: Record = {\n ip4: reduceValue,\n ip6: (str, content, i, parts) => (\n parts.length === 1 && parts[0].protocol === 'ip6'\n ? content\n : `[${content}]`\n ),\n tcp: (str, content, i, parts, opts) => (\n parts.some(p => ['http', 'https', 'ws', 'wss'].includes(p.protocol))\n ? `${str}:${content}`\n : tcpUri(str, content, parts, opts)\n ),\n udp: (str, content) => `udp://${str}:${content}`,\n dnsaddr: reduceValue,\n dns4: reduceValue,\n dns6: reduceValue,\n ipfs: (str, content) => `${str}/ipfs/${content}`,\n p2p: (str, content) => `${str}/p2p/${content}`,\n http: str => `http://${str}`,\n https: str => `https://${str}`,\n ws: str => `ws://${str}`,\n wss: str => `wss://${str}`,\n 'p2p-websocket-star': str => `${str}/p2p-websocket-star`,\n 'p2p-webrtc-star': str => `${str}/p2p-webrtc-star`,\n 'p2p-webrtc-direct': str => `${str}/p2p-webrtc-direct`\n}\n\ninterface Part {\n protocol: string\n content: string\n}\n\nexport function multiaddrToUri (multiaddr: Multiaddr | string | Uint8Array, opts?: MultiaddrToUriOpts) {\n const ma = new Multiaddr(multiaddr)\n const parts = multiaddr.toString().split('/').slice(1)\n return ma\n .tuples()\n .map(tuple => ({\n protocol: parts.shift() ?? '',\n content: (tuple[1] != null) ? parts.shift() ?? '' : ''\n }))\n .reduce((str: string, part: Part, i: number, parts: Part[]) => {\n const reduce = Reducers[part.protocol]\n if (reduce == null) {\n throw new Error(`Unsupported protocol ${part.protocol}`)\n }\n return reduce(str, part.content, i, parts, opts)\n }, '')\n}\n","\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static get code () {\n return 'ABORT_ERR'\n }\n\n static get type () {\n return 'aborted'\n }\n}\n","import detectElectron from 'is-electron'\n\nexport const isEnvWithDom = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\nexport const isElectron = detectElectron()\n\n/**\n * Detects browser main thread **NOT** web worker or service worker\n */\nexport const isBrowser = isEnvWithDom && !isElectron\nexport const isElectronMain = isElectron && !isEnvWithDom\nexport const isElectronRenderer = isElectron && isEnvWithDom\nexport const isNode = typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !isElectron\n// @ts-ignore\n// eslint-disable-next-line no-undef\nexport const isWebWorker = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\n\n// defeat bundlers replacing process.env.NODE_ENV with \"development\" or whatever\nexport const isTest = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env['NODE' + (() => '_')() + 'ENV'] === 'test'\nexport const isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst cancelablePromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst errorMessage = typeof message === 'string' ? message : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = message instanceof Error ? message : new TimeoutError(errorMessage);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t} finally {\n\t\t\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { CLOSE_TIMEOUT } from './constants.js'\nimport pTimeout from 'p-timeout'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\n\nconst log = logger('libp2p:websockets:socket')\n\nexport interface SocketToConnOptions extends AbortOptions {\n localAddr?: Multiaddr\n}\n\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn (stream: DuplexWebSocket, remoteAddr: Multiaddr, options?: SocketToConnOptions): MultiaddrConnection {\n options = options ?? {}\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if ((options?.signal) != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await stream.sink(source)\n } catch (err: any) {\n if (err.type !== 'aborted') {\n log.error(err)\n }\n }\n },\n\n source: (options.signal != null) ? abortableSource(stream.source, options.signal) : stream.source,\n\n remoteAddr,\n\n timeline: { open: Date.now() },\n\n async close () {\n const start = Date.now()\n\n try {\n await pTimeout(stream.close(), {\n milliseconds: CLOSE_TIMEOUT\n })\n } catch (err) {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing stream to %s:%s after %dms, destroying it manually',\n host, port, Date.now() - start)\n\n stream.destroy()\n } finally {\n maConn.timeline.close = Date.now()\n }\n }\n }\n\n stream.socket.once != null && stream.socket.once('close', () => { // eslint-disable-line @typescript-eslint/prefer-optional-chain\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n })\n\n return maConn\n}\n","// p2p multi-address code\nexport const CODE_P2P = 421\nexport const CODE_CIRCUIT = 290\n\nexport const CODE_TCP = 6\nexport const CODE_WS = 477\nexport const CODE_WSS = 478\n\n// Time to wait for a connection to close gracefully before destroying it manually\nexport const CLOSE_TIMEOUT = 2000\n","import { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\n\nexport const WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss'))\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nexport const WebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\nexport const WebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n WebSockets,\n WebSocketsSecure,\n HTTP,\n HTTPS,\n WebRTCStar,\n WebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS\n)\n\n// Unlike ws-star, stardust can run over any transport thus removing the requirement for websockets (but don't even think about running a stardust server over webrtc-star ;) )\nexport const Stardust = or(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n WebRTCStar,\n WebRTCDirect,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = () => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction) {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = new Multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's propably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n let out = null\n args.some((arg) => {\n const res = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n if (res != null) {\n out = res\n return true\n }\n return false\n })\n\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr) {\n let ma: Multiaddr\n\n try {\n ma = new Multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches: matches,\n partialMatch: partialMatch\n }\n}\n","import * as mafmt from '@multiformats/mafmt'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport {\n CODE_CIRCUIT,\n CODE_P2P,\n CODE_TCP,\n CODE_WS,\n CODE_WSS\n} from './constants.js'\n\nexport function all (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSockets.matches(testMa) ||\n mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function dnsWss (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n\nexport function dnsWsOrWss (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n // WS\n if (mafmt.WebSockets.matches(testMa)) {\n return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS))\n }\n\n // WSS\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n","import type { AbortOptions } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\n\nexport const symbol = Symbol.for('@libp2p/transport')\n\nexport interface ConnectionHandler { (connection: Connection): void }\n\nexport interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] }\n\nexport interface CreateListenerOptions {\n handler?: ConnectionHandler\n upgrader: Upgrader\n}\n\nexport interface DialOptions extends AbortOptions {\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport is understood as something that offers a dial and listen interface to establish connections.\n */\nexport interface Transport {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [symbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial: (ma: Multiaddr, options: DialOptions) => Promise\n\n /**\n * Create transport listeners.\n */\n createListener: (options: CreateListenerOptions) => Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid addresses for the transport\n */\n filter: MultiaddrFilter\n}\n\nexport interface ListenerEvents {\n 'connection': CustomEvent\n 'listening': CustomEvent\n 'error': CustomEvent\n 'close': CustomEvent\n}\n\nexport interface Listener extends EventEmitter {\n /**\n * Start a listener\n */\n listen: (multiaddr: Multiaddr) => Promise\n /**\n * Get listen addresses\n */\n getAddrs: () => Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise}\n */\n close: () => Promise\n}\n\nexport interface UpgraderEvents {\n 'connection': CustomEvent\n 'connectionEnd': CustomEvent\n}\n\nexport interface Upgrader extends EventEmitter {\n /**\n * Upgrades an outbound connection on `transport.dial`.\n */\n upgradeOutbound: (maConn: MultiaddrConnection) => Promise\n\n /**\n * Upgrades an inbound connection on transport listener.\n */\n upgradeInbound: (maConn: MultiaddrConnection) => Promise\n}\n\nexport interface ProtocolHandler {\n (stream: Duplex, connection: Connection): void\n}\n\nexport function isTransport (other: any): other is Transport {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface TransportManagerEvents {\n 'listener:listening': CustomEvent\n 'listener:close': CustomEvent\n}\n\nexport interface TransportManager extends EventEmitter {\n add: (transport: Transport) => void\n dial: (ma: Multiaddr, options?: any) => Promise\n getAddrs: () => Multiaddr[]\n getTransports: () => Transport[]\n transportForMultiaddr: (ma: Multiaddr) => Transport | undefined\n listen: (addrs: Multiaddr[]) => Promise\n remove: (key: string) => Promise\n removeAll: () => Promise\n}\n","import { connect, WebSocketOptions } from 'it-ws/client'\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri'\nimport { AbortError } from '@libp2p/interfaces/errors'\nimport pDefer from 'p-defer'\nimport { logger } from '@libp2p/logger'\nimport { isBrowser, isWebWorker } from 'wherearewe'\nimport { createListener } from './listener.js'\nimport { socketToMaConn } from './socket-to-conn.js'\nimport * as filters from './filters.js'\nimport { Transport, MultiaddrFilter, symbol, CreateListenerOptions, DialOptions } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\nimport type { ClientOptions } from 'ws'\nimport type { Server } from 'http'\n\nconst log = logger('libp2p:websockets')\n\nexport interface WebSocketsInit extends AbortOptions, WebSocketOptions {\n filter?: MultiaddrFilter\n websocket?: ClientOptions\n server?: Server\n}\n\nexport class WebSockets implements Transport {\n private readonly init?: WebSocketsInit\n\n constructor (init?: WebSocketsInit) {\n this.init = init\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/websockets'\n }\n\n get [symbol] (): true {\n return true\n }\n\n async dial (ma: Multiaddr, options: DialOptions): Promise {\n log('dialing %s', ma)\n options = options ?? {}\n\n const socket = await this._connect(ma, options)\n const maConn = socketToMaConn(socket, ma)\n log('new outbound connection %s', maConn.remoteAddr)\n\n const conn = await options.upgrader.upgradeOutbound(maConn)\n log('outbound connection %s upgraded', maConn.remoteAddr)\n return conn\n }\n\n async _connect (ma: Multiaddr, options: AbortOptions): Promise {\n if (options?.signal?.aborted === true) {\n throw new AbortError()\n }\n const cOpts = ma.toOptions()\n log('dialing %s:%s', cOpts.host, cOpts.port)\n\n const errorPromise = pDefer()\n const errfn = (err: any) => {\n log.error('connection error:', err)\n\n errorPromise.reject(err)\n }\n\n const rawSocket = connect(toUri(ma), this.init)\n\n if (rawSocket.socket.on != null) {\n rawSocket.socket.on('error', errfn)\n } else {\n rawSocket.socket.onerror = errfn\n }\n\n if (options.signal == null) {\n await Promise.race([rawSocket.connected(), errorPromise.promise])\n\n log('connected %s', ma)\n return rawSocket\n }\n\n // Allow abort via signal during connect\n let onAbort\n const abort = new Promise((resolve, reject) => {\n onAbort = () => {\n reject(new AbortError())\n // FIXME: https://github.com/libp2p/js-libp2p-websockets/issues/121\n setTimeout(() => {\n rawSocket.close().catch(err => {\n log.error('error closing raw socket', err)\n })\n })\n }\n\n // Already aborted?\n if (options?.signal?.aborted === true) {\n return onAbort()\n }\n\n options?.signal?.addEventListener('abort', onAbort)\n })\n\n try {\n await Promise.race([abort, errorPromise.promise, rawSocket.connected()])\n } finally {\n if (onAbort != null) {\n options?.signal?.removeEventListener('abort', onAbort)\n }\n }\n\n log('connected %s', ma)\n return rawSocket\n }\n\n /**\n * Creates a Websockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener (options: CreateListenerOptions) {\n return createListener({ ...this.init, ...options })\n }\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid Websockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n filter (multiaddrs: Multiaddr[]) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs)\n }\n\n // Browser\n if (isBrowser || isWebWorker) {\n return filters.dnsWss(multiaddrs)\n }\n\n return filters.all(multiaddrs)\n }\n}\n","\nexport function createListener () {\n throw new Error('WebSocket Servers can not be created in the browser!')\n}\n","\nimport all from 'it-all'\n\n/**\n * Collect all values from the iterable and sort them using\n * the passed sorter function\n *\n * @template T\n * @param {AsyncIterable | Iterable} iterable\n * @param {(a: T, b: T) => -1 | 0 | 1} sorter\n * @returns {AsyncIterable}\n */\nexport const sortAll = (iterable, sorter) => {\n return (async function * () {\n const values = await all(iterable)\n yield * values.sort(sorter)\n })()\n}\n\n/**\n * @param {string} s\n * @param {string} r\n */\nexport const replaceStartWith = (s, r) => {\n const matcher = new RegExp('^' + r)\n return s.replace(matcher, '')\n}\n","\nimport { nanoid } from 'nanoid'\nimport { SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/f98719ea086343f7b71f32ea9d9d521d')\n * ```\n */\n static random (): Key {\n return new Key(nanoid().replace(/-/g, ''))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n *\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n","import { urlAlphabet } from './url-alphabet/index.js'\nlet random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import { BaseDatastore } from './base.js'\nimport { Key } from 'interface-datastore/key'\nimport * as Errors from './errors.js'\n\n/**\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-store').Options} Options\n */\n\n/**\n * @class MemoryDatastore\n * @implements {Datastore}\n */\nexport class MemoryDatastore extends BaseDatastore {\n constructor () {\n super()\n\n /** @type {Record} */\n this.data = {}\n }\n\n open () {\n return Promise.resolve()\n }\n\n close () {\n return Promise.resolve()\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n */\n async put (key, val) { // eslint-disable-line require-await\n this.data[key.toString()] = val\n }\n\n /**\n * @param {Key} key\n */\n async get (key) {\n const exists = await this.has(key)\n if (!exists) throw Errors.notFoundError()\n return this.data[key.toString()]\n }\n\n /**\n * @param {Key} key\n */\n async has (key) { // eslint-disable-line require-await\n return this.data[key.toString()] !== undefined\n }\n\n /**\n * @param {Key} key\n */\n async delete (key) { // eslint-disable-line require-await\n delete this.data[key.toString()]\n }\n\n async * _all () {\n yield * Object.entries(this.data)\n .map(([key, value]) => ({ key: new Key(key), value }))\n }\n\n async * _allKeys () {\n yield * Object.entries(this.data)\n .map(([key]) => new Key(key))\n }\n}\n","import { sortAll } from './utils.js'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport take from 'it-take'\n\n/**\n * @typedef {import('interface-store').Options} Options\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Batch} Batch\n */\n\n/**\n * @template O\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * @implements {Datastore}\n */\nexport class BaseDatastore {\n /**\n * @returns {Promise}\n */\n open () {\n return Promise.reject(new Error('.open is not implemented'))\n }\n\n /**\n * @returns {Promise}\n */\n close () {\n return Promise.reject(new Error('.close is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n * @returns {Promise}\n */\n put (key, val, options) {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n get (key, options) {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n has (key, options) {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n delete (key, options) {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield { key, value }\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n for await (const key of source) {\n yield this.get(key, options)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * deleteMany (source, options = {}) {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Pair[]} */\n let puts = []\n /** @type {Key[]} */\n let dels = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\n\n delete (key) {\n dels.push(key)\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options))\n puts = []\n await drain(this.deleteMany(dels, options))\n dels = []\n }\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n *\n * @param {Query} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _all (q, options) {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n *\n * @param {KeyQuery} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q, options) {\n throw new Error('._allKeys is not implemented')\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (e) =>\n e.key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (key) =>\n key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n","import errCode from 'err-code'\n\n/**\n * @param {Error} [err]\n */\nexport function dbOpenFailedError (err) {\n err = err || new Error('Cannot open database')\n return errCode(err, 'ERR_DB_OPEN_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbDeleteFailedError (err) {\n err = err || new Error('Delete failed')\n return errCode(err, 'ERR_DB_DELETE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbWriteFailedError (err) {\n err = err || new Error('Write failed')\n return errCode(err, 'ERR_DB_WRITE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function notFoundError (err) {\n err = err || new Error('Not Found')\n return errCode(err, 'ERR_NOT_FOUND')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function abortedError (err) {\n err = err || new Error('Aborted')\n return errCode(err, 'ERR_ABORTED')\n}\n","export enum messages {\n NOT_STARTED_YET = 'The libp2p node is not started yet',\n DHT_DISABLED = 'DHT is not available',\n PUBSUB_DISABLED = 'PubSub is not available',\n CONN_ENCRYPTION_REQUIRED = 'At least one connection encryption module is required',\n ERR_TRANSPORTS_REQUIRED = 'At least one transport module is required',\n ERR_PROTECTOR_REQUIRED = 'Private network is enforced, but no protector was provided',\n NOT_FOUND = 'Not found'\n}\n\nexport enum codes {\n DHT_DISABLED = 'ERR_DHT_DISABLED',\n ERR_PUBSUB_DISABLED = 'ERR_PUBSUB_DISABLED',\n PUBSUB_NOT_STARTED = 'ERR_PUBSUB_NOT_STARTED',\n DHT_NOT_STARTED = 'ERR_DHT_NOT_STARTED',\n CONN_ENCRYPTION_REQUIRED = 'ERR_CONN_ENCRYPTION_REQUIRED',\n ERR_TRANSPORTS_REQUIRED = 'ERR_TRANSPORTS_REQUIRED',\n ERR_PROTECTOR_REQUIRED = 'ERR_PROTECTOR_REQUIRED',\n ERR_PEER_DIAL_INTERCEPTED = 'ERR_PEER_DIAL_INTERCEPTED',\n ERR_CONNECTION_INTERCEPTED = 'ERR_CONNECTION_INTERCEPTED',\n ERR_INVALID_PROTOCOLS_FOR_STREAM = 'ERR_INVALID_PROTOCOLS_FOR_STREAM',\n ERR_CONNECTION_ENDED = 'ERR_CONNECTION_ENDED',\n ERR_CONNECTION_FAILED = 'ERR_CONNECTION_FAILED',\n ERR_NODE_NOT_STARTED = 'ERR_NODE_NOT_STARTED',\n ERR_ALREADY_ABORTED = 'ERR_ALREADY_ABORTED',\n ERR_TOO_MANY_ADDRESSES = 'ERR_TOO_MANY_ADDRESSES',\n ERR_NO_VALID_ADDRESSES = 'ERR_NO_VALID_ADDRESSES',\n ERR_RELAYED_DIAL = 'ERR_RELAYED_DIAL',\n ERR_DIALED_SELF = 'ERR_DIALED_SELF',\n ERR_DISCOVERED_SELF = 'ERR_DISCOVERED_SELF',\n ERR_DUPLICATE_TRANSPORT = 'ERR_DUPLICATE_TRANSPORT',\n ERR_ENCRYPTION_FAILED = 'ERR_ENCRYPTION_FAILED',\n ERR_HOP_REQUEST_FAILED = 'ERR_HOP_REQUEST_FAILED',\n ERR_INVALID_KEY = 'ERR_INVALID_KEY',\n ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE',\n ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS',\n ERR_INVALID_PEER = 'ERR_INVALID_PEER',\n ERR_MUXER_UNAVAILABLE = 'ERR_MUXER_UNAVAILABLE',\n ERR_NOT_FOUND = 'ERR_NOT_FOUND',\n ERR_TIMEOUT = 'ERR_TIMEOUT',\n ERR_TRANSPORT_UNAVAILABLE = 'ERR_TRANSPORT_UNAVAILABLE',\n ERR_TRANSPORT_DIAL_FAILED = 'ERR_TRANSPORT_DIAL_FAILED',\n ERR_UNSUPPORTED_PROTOCOL = 'ERR_UNSUPPORTED_PROTOCOL',\n ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED = 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED',\n ERR_INVALID_MULTIADDR = 'ERR_INVALID_MULTIADDR',\n ERR_SIGNATURE_NOT_VALID = 'ERR_SIGNATURE_NOT_VALID',\n ERR_FIND_SELF = 'ERR_FIND_SELF',\n ERR_NO_ROUTERS_AVAILABLE = 'ERR_NO_ROUTERS_AVAILABLE',\n ERR_CONNECTION_NOT_MULTIPLEXED = 'ERR_CONNECTION_NOT_MULTIPLEXED',\n ERR_NO_DIAL_TOKENS = 'ERR_NO_DIAL_TOKENS',\n ERR_KEYCHAIN_REQUIRED = 'ERR_KEYCHAIN_REQUIRED',\n ERR_INVALID_CMS = 'ERR_INVALID_CMS',\n ERR_MISSING_KEYS = 'ERR_MISSING_KEYS',\n ERR_NO_KEY = 'ERR_NO_KEY',\n ERR_INVALID_KEY_NAME = 'ERR_INVALID_KEY_NAME',\n ERR_INVALID_KEY_TYPE = 'ERR_INVALID_KEY_TYPE',\n ERR_KEY_ALREADY_EXISTS = 'ERR_KEY_ALREADY_EXISTS',\n ERR_INVALID_KEY_SIZE = 'ERR_INVALID_KEY_SIZE',\n ERR_KEY_NOT_FOUND = 'ERR_KEY_NOT_FOUND',\n ERR_OLD_KEY_NAME_INVALID = 'ERR_OLD_KEY_NAME_INVALID',\n ERR_NEW_KEY_NAME_INVALID = 'ERR_NEW_KEY_NAME_INVALID',\n ERR_PASSWORD_REQUIRED = 'ERR_PASSWORD_REQUIRED',\n ERR_PEM_REQUIRED = 'ERR_PEM_REQUIRED',\n ERR_CANNOT_READ_KEY = 'ERR_CANNOT_READ_KEY',\n ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY',\n ERR_MISSING_PUBLIC_KEY = 'ERR_MISSING_PUBLIC_KEY',\n ERR_INVALID_OLD_PASS_TYPE = 'ERR_INVALID_OLD_PASS_TYPE',\n ERR_INVALID_NEW_PASS_TYPE = 'ERR_INVALID_NEW_PASS_TYPE',\n ERR_INVALID_PASS_LENGTH = 'ERR_INVALID_PASS_LENGTH',\n ERR_NOT_IMPLEMENTED = 'ERR_NOT_IMPLEMENTED',\n ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK',\n ERR_INVALID_RECORD = 'ERR_INVALID_RECORD',\n ERR_ALREADY_SUCCEEDED = 'ERR_ALREADY_SUCCEEDED',\n ERR_NO_HANDLER_FOR_PROTOCOL = 'ERR_NO_HANDLER_FOR_PROTOCOL',\n ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS',\n ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS'\n}\n","import errCode from 'err-code'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport type { Source } from 'it-stream-types'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\n/**\n * Store the multiaddrs from every peer in the passed peer store\n */\nexport async function * storeAddresses (source: Source, peerStore: PeerStore) {\n yield * map(source, async (peer) => {\n // ensure we have the addresses for a given peer\n await peerStore.addressBook.add(peer.id, peer.multiaddrs)\n\n return peer\n })\n}\n\n/**\n * Filter peers by unique peer id\n */\nexport function uniquePeers (source: Source) {\n /** @type Set */\n const seen = new Set()\n\n return filter(source, (peer) => {\n // dedupe by peer id\n if (seen.has(peer.id.toString())) {\n return false\n }\n\n seen.add(peer.id.toString())\n\n return true\n })\n}\n\n/**\n * Require at least `min` peers to be yielded from `source`\n */\nexport async function * requirePeers (source: Source, min: number = 1) {\n let seen = 0\n\n for await (const peer of source) {\n seen++\n\n yield peer\n }\n\n if (seen < min) {\n throw errCode(new Error('not found'), 'NOT_FOUND')\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes, messages } from './errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './content-routing/utils.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error module with no types\n} from 'set-delayed-interval'\nimport { setMaxListeners } from 'events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:peer-routing')\n\nexport interface RefreshManagerInit {\n /**\n * Whether to enable the Refresh manager\n */\n enabled?: boolean\n\n /**\n * Boot delay to start the Refresh Manager (in ms)\n */\n bootDelay?: number\n\n /**\n * Interval between each Refresh Manager run (in ms)\n */\n interval?: number\n\n /**\n * How long to let each refresh run (in ms)\n */\n timeout?: number\n}\n\nexport interface PeerRoutingInit {\n routers: PeerRouting[]\n refreshManager?: RefreshManagerInit\n}\n\nexport class DefaultPeerRouting implements PeerRouting, Startable {\n private readonly components: Components\n private readonly routers: PeerRouting[]\n private readonly refreshManagerInit: RefreshManagerInit\n private timeoutId?: ReturnType\n private started: boolean\n private abortController?: TimeoutController\n\n constructor (components: Components, init: PeerRoutingInit) {\n this.components = components\n this.routers = init.routers\n this.refreshManagerInit = init.refreshManager ?? {}\n this.started = false\n\n this._findClosestPeersTask = this._findClosestPeersTask.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start peer routing service.\n */\n async start () {\n if (this.started || this.routers.length === 0 || this.timeoutId != null || this.refreshManagerInit.enabled === false) {\n return\n }\n\n this.timeoutId = setDelayedInterval(\n this._findClosestPeersTask, this.refreshManagerInit.interval, this.refreshManagerInit.bootDelay\n )\n\n this.started = true\n }\n\n /**\n * Recurrent task to find closest peers and add their addresses to the Address Book.\n */\n async _findClosestPeersTask () {\n if (this.abortController != null) {\n // we are already running the query\n return\n }\n\n try {\n this.abortController = new TimeoutController(this.refreshManagerInit.timeout ?? 10e3)\n\n // this controller may be used while dialing lots of peers so prevent MaxListenersExceededWarning\n // appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.abortController.signal)\n } catch {}\n\n // nb getClosestPeers adds the addresses to the address book\n await drain(this.getClosestPeers(this.components.getPeerId().toBytes(), { signal: this.abortController.signal }))\n } catch (err: any) {\n log.error(err)\n } finally {\n this.abortController?.clear()\n this.abortController = undefined\n }\n }\n\n /**\n * Stop peer routing service.\n */\n async stop () {\n clearDelayedInterval(this.timeoutId)\n\n // abort query if it is in-flight\n this.abortController?.abort()\n\n this.started = false\n }\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: PeerId, options?: AbortOptions): Promise {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n if (id.toString() === this.components.getPeerId().toString()) {\n throw errCode(new Error('Should not try to find self'), codes.ERR_FIND_SELF)\n }\n\n const output = await pipe(\n merge(\n ...this.routers.map(router => (async function * () {\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n log.error(err)\n }\n })())\n ),\n (source) => filter(source, Boolean),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n async (source) => await first(source)\n )\n\n if (output != null) {\n return output\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options?: AbortOptions): AsyncIterable {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.getClosestPeers(key, options))\n ),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\n }\n}\n","import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './utils.js'\nimport drain from 'it-drain'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { CID } from 'multiformats/cid'\nimport type { Components } from '@libp2p/components'\n\nexport interface CompoundContentRoutingInit {\n routers: ContentRouting[]\n}\n\nexport class CompoundContentRouting implements ContentRouting, Startable {\n private readonly routers: ContentRouting[]\n private started: boolean\n private readonly components: Components\n\n constructor (components: Components, init: CompoundContentRoutingInit) {\n this.routers = init.routers ?? []\n this.started = false\n this.components = components\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n async stop () {\n this.started = false\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async * findProviders (key: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content this.routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.findProviders(key, options))\n ),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\n }\n\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide (key: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n await Promise.all(this.routers.map(async (router) => await router.provide(key, options)))\n }\n\n /**\n * Store the given key/value pair in the available content routings\n */\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions) {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.getDHT()\n\n if (dht != null) {\n await drain(dht.put(key, value, options))\n }\n }\n\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.getDHT()\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Get the `n` values to the given key without sorting\n */\n async * getMany (key: Uint8Array, nVals: number, options: AbortOptions) { // eslint-disable-line require-await\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n if (nVals == null || nVals === 0) {\n return\n }\n\n let gotValues = 0\n const dht = this.components.getDHT()\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n yield { from: event.from, val: event.value }\n\n gotValues++\n\n if (gotValues === nVals) {\n break\n }\n }\n }\n }\n\n if (gotValues === 0) {\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n }\n}\n","import { peerIdFromString } from '@libp2p/peer-id'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\n\nfunction peerIdFromMultiaddr (ma: Multiaddr) {\n const idStr = ma.getPeerId()\n\n if (idStr == null) {\n throw errCode(\n new Error(`${ma.toString()} does not have a valid peer type`),\n codes.ERR_INVALID_MULTIADDR\n )\n }\n\n try {\n return peerIdFromString(idStr)\n } catch (err: any) {\n throw errCode(\n new Error(`${ma.toString()} is not a valid peer type`),\n codes.ERR_INVALID_MULTIADDR\n )\n }\n}\n\n/**\n * Converts the given `peer` to a `Peer` object.\n */\nexport function getPeer (peer: PeerId | Multiaddr | string): PeerInfo {\n if (isPeerId(peer)) {\n return {\n id: peer,\n multiaddrs: [],\n protocols: []\n }\n }\n\n if (typeof peer === 'string') {\n peer = new Multiaddr(peer)\n }\n\n let addr\n\n if (Multiaddr.isMultiaddr(peer)) {\n addr = peer\n peer = peerIdFromMultiaddr(peer)\n }\n\n return {\n id: peer,\n multiaddrs: addr != null ? [addr] : [],\n protocols: []\n }\n}\n","import type { AddressManagerEvents } from '@libp2p/interface-address-manager'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Components } from '@libp2p/components'\n\nexport interface AddressManagerInit {\n announceFilter?: AddressFilter\n\n /**\n * list of multiaddrs string representation to listen\n */\n listen?: string[]\n\n /**\n * list of multiaddrs string representation to announce\n */\n announce?: string[]\n\n /**\n * list of multiaddrs string representation to never announce\n */\n noAnnounce?: string[]\n}\n\nexport interface AddressFilter {\n (addrs: Multiaddr[]): Multiaddr[]\n}\n\nconst defaultAddressFilter = (addrs: Multiaddr[]): Multiaddr[] => addrs\n\nexport class DefaultAddressManager extends EventEmitter {\n private readonly components: Components\n private readonly listen: Set\n private readonly announce: Set\n private readonly observed: Set\n private readonly announceFilter: AddressFilter\n\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor (components: Components, init: AddressManagerInit) {\n super()\n\n const { listen = [], announce = [] } = init\n\n this.components = components\n this.listen = new Set(listen.map(ma => ma.toString()))\n this.announce = new Set(announce.map(ma => ma.toString()))\n this.observed = new Set()\n this.announceFilter = init.announceFilter ?? defaultAddressFilter\n }\n\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs (): Multiaddr[] {\n return Array.from(this.listen).map((a) => new Multiaddr(a))\n }\n\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs (): Multiaddr[] {\n return Array.from(this.announce).map((a) => new Multiaddr(a))\n }\n\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs (): Multiaddr[] {\n return Array.from(this.observed).map((a) => new Multiaddr(a))\n }\n\n /**\n * Add peer observed addresses\n */\n addObservedAddr (addr: string | Multiaddr): void {\n let ma = new Multiaddr(addr)\n const remotePeer = ma.getPeerId()\n\n // strip our peer id if it has been passed\n if (remotePeer != null) {\n const remotePeerId = peerIdFromString(remotePeer)\n\n // use same encoding for comparison\n if (remotePeerId.equals(this.components.getPeerId())) {\n ma = ma.decapsulate(new Multiaddr(`/p2p/${this.components.getPeerId().toString()}`))\n }\n }\n\n const addrString = ma.toString()\n\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return\n }\n\n this.observed.add(addrString)\n this.dispatchEvent(new CustomEvent('change:addresses'))\n }\n\n getAddresses (): Multiaddr[] {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString())\n\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.getTransportManager().getAddrs().map(ma => ma.toString())\n }\n\n addrs = addrs.concat(this.getObservedAddrs().map(ma => ma.toString()))\n\n // dedupe multiaddrs\n const addrSet = new Set(addrs)\n\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => new Multiaddr(str)))\n .map(ma => {\n if (ma.getPeerId() === this.components.getPeerId().toString()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${this.components.getPeerId().toString()}`)\n })\n }\n}\n","/**\n * Thin ESM wrapper for CJS named exports.\n *\n * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1\n */\n\nimport mergeOptions from './index.js';\nexport default mergeOptions;\n","/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor:visibility-change-emitter')\n\ninterface VisibilityChangeEmitterEvents {\n 'visibilityChange': CustomEvent\n}\n\ntype Hidden = 'hidden' | 'mozHidden' | 'msHidden' | 'webkitHidden'\n\n/**\n * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.\n *\n * Warning: This does not work on all browsers, but should work on all modern browsers\n *\n * @example\n *\n * const myVisibilityEmitter = new VisibilityChangeEmitter();\n *\n * myVisibilityEmitter.on('visibilityChange', (pageInFocus) => {\n * if ( pageInFocus ){\n * // Page is in focus\n * console.log('In focus');\n * }\n * else {\n * // Page is blurred\n * console.log('Out of focus');\n * }\n * });\n * // To access the visibility state directly, call:\n * console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());\n */\nexport class VisibilityChangeEmitter extends EventEmitter {\n private hidden: Hidden\n private visibilityChange: string\n\n constructor () {\n super()\n\n this.hidden = 'hidden'\n this.visibilityChange = 'visibilityChange'\n\n if (globalThis.document != null) {\n this._initializeVisibilityVarNames()\n this._addVisibilityChangeListener()\n }\n }\n\n /**\n * document.hidden and document.visibilityChange are the two variables we need to check for;\n * Since these variables are named differently in different browsers, this function sets\n * the appropriate name based on the browser being used. Once executed, tha actual names of\n * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange\n * respectively\n *\n * @private\n */\n _initializeVisibilityVarNames () {\n let hidden: Hidden = 'hidden'\n let visibilityChange = 'visibilitychange'\n\n if (typeof globalThis.document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support\n hidden = 'hidden'\n visibilityChange = 'visibilitychange'\n // @ts-expect-error mozHidden is a non-standard field name\n } else if (typeof globalThis.document.mozHidden !== 'undefined') {\n hidden = 'mozHidden'\n visibilityChange = 'mozvisibilitychange'\n // @ts-expect-error msHidden is a non-standard field name\n } else if (typeof globalThis.document.msHidden !== 'undefined') {\n hidden = 'msHidden'\n visibilityChange = 'msvisibilitychange'\n // @ts-expect-error webkitHidden is a non-standard field name\n } else if (typeof globalThis.document.webkitHidden !== 'undefined') {\n hidden = 'webkitHidden'\n visibilityChange = 'webkitvisibilitychange'\n }\n\n this.hidden = hidden\n this.visibilityChange = visibilityChange\n }\n\n /**\n * Adds an event listener on the document that listens to changes in document.visibilityChange\n * (or whatever name by which the visibilityChange variable is known in the browser)\n *\n * @private\n */\n _addVisibilityChangeListener () {\n // @ts-expect-error cannot index document object with string key\n if (typeof globalThis.document.addEventListener === 'undefined' || typeof document[this.hidden] === 'undefined') {\n log('Checking page visibility requires a browser that supports the Page Visibility API.')\n } else {\n // Handle page visibility change\n globalThis.document.addEventListener(this.visibilityChange, this._handleVisibilityChange.bind(this), false)\n }\n }\n\n /**\n * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and\n * ```undefined``` if the page visibility API is not supported by the browser.\n */\n isVisible () {\n // @ts-expect-error cannot index document object with string key\n if (this.hidden === undefined || document[this.hidden] === undefined) {\n return undefined\n }\n\n // @ts-expect-error cannot index document object with string key\n return document[this.hidden] == null\n }\n\n /**\n * The function that is called when document.visibilityChange has changed\n * It emits an event called visibilityChange and sends the value of document.hidden as a\n * parameter\n *\n * @private\n */\n _handleVisibilityChange () {\n // @ts-expect-error cannot index document object with string key\n const visible = globalThis.document[this.hidden] === false\n log(visible ? 'Page Visible' : 'Page Hidden')\n\n // Emit the event\n this.dispatchEvent(new CustomEvent('visibilityChange', {\n detail: visible\n }))\n }\n}\n","/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { VisibilityChangeEmitter } from './visibility-change-emitter.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor')\n\nexport interface LatencyMonitorEvents {\n 'data': CustomEvent\n}\n\nexport interface LatencyMonitorInit {\n /**\n * How often to add a latency check event (ms)\n */\n latencyCheckIntervalMs?: number\n\n /**\n * How often to summarize latency check events. null or 0 disables event firing\n */\n dataEmitIntervalMs?: number\n\n /**\n * What cb-style async function to use\n */\n asyncTestFn?: (cb: () => void) => void\n\n /**\n * What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.\n */\n latencyRandomPercentage?: number\n}\n\nexport interface SummaryObject {\n /**\n * How many events were called\n */\n events: number\n\n /**\n * What was the min time for a cb to be called\n */\n minMs: number\n\n /**\n * What was the max time for a cb to be called\n */\n maxMs: number\n\n /**\n * What was the average time for a cb to be called\n */\n avgMs: number\n\n /**\n * How long this interval was in ms\n */\n lengthMs: number\n}\n\ninterface LatencyData {\n startTime: number\n events: number\n minMs: number\n maxMs: number\n totalMs: number\n}\n\n/**\n * A class to monitor latency of any async function which works in a browser or node. This works by periodically calling\n * the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this.\n * This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0.\n *\n * @extends {EventEmitter}\n *\n * The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop\n * and timing how long it takes to get back.\n *\n * @example\n * const monitor = new LatencyMonitor();\n * monitor.on('data', (summary) => console.log('Event Loop Latency: %O', summary));\n *\n * @example\n * const monitor = new LatencyMonitor({latencyCheckIntervalMs: 1000, dataEmitIntervalMs: 60000, asyncTestFn:ping});\n * monitor.on('data', (summary) => console.log('Ping Pong Latency: %O', summary));\n */\nexport class LatencyMonitor extends EventEmitter {\n private readonly latencyCheckIntervalMs: number\n private readonly latencyRandomPercentage: number\n private readonly latencyCheckMultiply: number\n private readonly latencyCheckSubtract: number\n private readonly dataEmitIntervalMs?: number\n private readonly asyncTestFn?: (cb: () => void) => void\n\n private readonly now: (num?: any) => any\n private readonly getDeltaMS: (num: number) => number\n private visibilityChangeEmitter?: VisibilityChangeEmitter\n private latencyData: LatencyData\n private checkLatencyID?: NodeJS.Timeout\n private emitIntervalID?: NodeJS.Timeout\n\n constructor (init: LatencyMonitorInit = {}) {\n super()\n\n const { latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = init\n\n // 0 isn't valid here, so its ok to use ||\n this.latencyCheckIntervalMs = latencyCheckIntervalMs ?? 500 // 0.5s\n this.latencyRandomPercentage = latencyRandomPercentage ?? 10\n this.latencyCheckMultiply = 2 * (this.latencyRandomPercentage / 100.0) * this.latencyCheckIntervalMs\n this.latencyCheckSubtract = this.latencyCheckMultiply / 2\n\n this.dataEmitIntervalMs = (dataEmitIntervalMs === null || dataEmitIntervalMs === 0)\n ? undefined\n : dataEmitIntervalMs ?? 5 * 1000 // 5s\n log('latencyCheckIntervalMs: %s dataEmitIntervalMs: %s',\n this.latencyCheckIntervalMs, this.dataEmitIntervalMs)\n if (this.dataEmitIntervalMs != null) {\n log('Expecting ~%s events per summary', this.latencyCheckIntervalMs / this.dataEmitIntervalMs)\n } else {\n log('Not emitting summaries')\n }\n\n this.asyncTestFn = asyncTestFn // If there is no asyncFn, we measure latency\n\n // If process: use high resolution timer\n if (globalThis.process?.hrtime != null) {\n log('Using process.hrtime for timing')\n this.now = globalThis.process.hrtime // eslint-disable-line no-undef\n this.getDeltaMS = (startTime) => {\n const hrtime = this.now(startTime)\n return (hrtime[0] * 1000) + (hrtime[1] / 1000000)\n }\n // Let's try for a timer that only monotonically increases\n } else if (typeof window !== 'undefined' && window.performance?.now != null) {\n log('Using performance.now for timing')\n this.now = window.performance.now.bind(window.performance)\n this.getDeltaMS = (startTime) => Math.round(this.now() - startTime)\n } else {\n log('Using Date.now for timing')\n this.now = Date.now\n this.getDeltaMS = (startTime) => this.now() - startTime\n }\n\n this.latencyData = this.initLatencyData()\n }\n\n start () {\n // We check for isBrowser because of browsers set max rates of timeouts when a page is hidden,\n // so we fall back to another library\n // See: http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs\n if (isBrowser()) {\n this.visibilityChangeEmitter = new VisibilityChangeEmitter()\n\n this.visibilityChangeEmitter.addEventListener('visibilityChange', (evt) => {\n const { detail: pageInFocus } = evt\n\n if (pageInFocus) {\n this._startTimers()\n } else {\n this._emitSummary()\n this._stopTimers()\n }\n })\n }\n\n if (this.visibilityChangeEmitter?.isVisible() === true) {\n this._startTimers()\n }\n }\n\n stop () {\n this._stopTimers()\n }\n\n /**\n * Start internal timers\n *\n * @private\n */\n _startTimers () {\n // Timer already started, ignore this\n if (this.checkLatencyID != null) {\n return\n }\n\n this.checkLatency()\n\n if (this.dataEmitIntervalMs != null) {\n this.emitIntervalID = setInterval(() => this._emitSummary(), this.dataEmitIntervalMs)\n if (typeof this.emitIntervalID.unref === 'function') {\n this.emitIntervalID.unref() // Doesn't block exit\n }\n }\n }\n\n /**\n * Stop internal timers\n *\n * @private\n */\n _stopTimers () {\n if (this.checkLatencyID != null) {\n clearTimeout(this.checkLatencyID)\n this.checkLatencyID = undefined\n }\n if (this.emitIntervalID != null) {\n clearInterval(this.emitIntervalID)\n this.emitIntervalID = undefined\n }\n }\n\n /**\n * Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show\n *\n * @private\n */\n _emitSummary () {\n const summary = this.getSummary()\n if (summary.events > 0) {\n this.dispatchEvent(new CustomEvent('data', {\n detail: summary\n }))\n }\n }\n\n /**\n * Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue,\n * it will not count for this time period\n */\n getSummary (): SummaryObject {\n // We might want to adjust for the number of expected events\n // Example: first 1 event it comes back, then such a long blocker that the next emit check comes\n // Then this fires - looks like no latency!!\n const latency = {\n events: this.latencyData.events,\n minMs: this.latencyData.minMs,\n maxMs: this.latencyData.maxMs,\n avgMs: this.latencyData.events > 0\n ? this.latencyData.totalMs / this.latencyData.events\n : Number.POSITIVE_INFINITY,\n lengthMs: this.getDeltaMS(this.latencyData.startTime)\n }\n this.latencyData = this.initLatencyData() // Clear\n\n log.trace('Summary: %O', latency)\n return latency\n }\n\n /**\n * Randomly calls an async fn every roughly latencyCheckIntervalMs (plus some randomness). If no async fn is found,\n * it will simply report on event loop latency.\n */\n checkLatency () {\n // Randomness is needed to avoid alignment by accident to regular things in the event loop\n const randomness = (Math.random() * this.latencyCheckMultiply) - this.latencyCheckSubtract\n\n // We use this to ensure that in case some overlap somehow, we don't take the wrong startTime/offset\n const localData = {\n deltaOffset: Math.ceil(this.latencyCheckIntervalMs + randomness),\n startTime: this.now()\n }\n\n const cb = () => {\n // We are already stopped, ignore this datapoint\n if (this.checkLatencyID == null) {\n return\n }\n const deltaMS = this.getDeltaMS(localData.startTime) - localData.deltaOffset\n this.checkLatency() // Start again ASAP\n\n // Add the data point. If this gets complex, refactor it\n this.latencyData.events++\n this.latencyData.minMs = Math.min(this.latencyData.minMs, deltaMS)\n this.latencyData.maxMs = Math.max(this.latencyData.maxMs, deltaMS)\n this.latencyData.totalMs += deltaMS\n log.trace('MS: %s Data: %O', deltaMS, this.latencyData)\n }\n log.trace('localData: %O', localData)\n\n this.checkLatencyID = setTimeout(() => {\n // This gets rid of including event loop\n if (this.asyncTestFn != null) {\n // Clear timing related things\n localData.deltaOffset = 0\n localData.startTime = this.now()\n this.asyncTestFn(cb)\n } else {\n // setTimeout is not more accurate than 1ms, so this will ensure positive numbers. Add 1 to emitted data to remove.\n // This is not the best, but for now it'll be just fine. This isn't meant to be sub ms accurate.\n localData.deltaOffset -= 1\n // If there is no function to test, we mean check latency which is a special case that is really cb => cb()\n // We avoid that for the few extra function all overheads. Also, we want to keep the timers different\n cb()\n }\n }, localData.deltaOffset)\n\n if (typeof this.checkLatencyID.unref === 'function') {\n this.checkLatencyID.unref() // Doesn't block exit\n }\n }\n\n initLatencyData (): LatencyData {\n return {\n startTime: this.now(),\n minMs: Number.POSITIVE_INFINITY,\n maxMs: Number.NEGATIVE_INFINITY,\n events: 0,\n totalMs: 0\n }\n }\n}\n\nfunction isBrowser () {\n return typeof globalThis.window !== 'undefined'\n}\n","\nexport const OPEN = 'OPEN'\nexport const CLOSING = 'CLOSING'\nexport const CLOSED = 'CLOSED'\n","import errCode from 'err-code'\nimport { anySignal } from 'any-signal'\nimport FIFO from 'p-fifo'\nimport { setMaxListeners } from 'events'\nimport { codes } from '../../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Dialer } from './index.js'\n\nconst log = logger('libp2p:dialer:dial-request')\n\nexport interface DialAction {\n (m: Multiaddr, options: AbortOptions): Promise\n}\n\nexport interface DialRequestOptions {\n addrs: Multiaddr[]\n dialAction: DialAction\n dialer: Dialer\n}\n\nexport class DialRequest {\n private readonly addrs: Multiaddr[]\n private readonly dialer: Dialer\n private readonly dialAction: DialAction\n\n /**\n * Manages running the `dialAction` on multiple provided `addrs` in parallel\n * up to a maximum determined by the number of tokens returned\n * from `dialer.getTokens`. Once a DialRequest is created, it can be\n * started using `DialRequest.run(options)`. Once a single dial has succeeded,\n * all other dials in the request will be cancelled.\n */\n constructor (options: DialRequestOptions) {\n const {\n addrs,\n dialAction,\n dialer\n } = options\n\n this.addrs = addrs\n this.dialer = dialer\n this.dialAction = dialAction\n }\n\n async run (options: AbortOptions = {}): Promise {\n const tokens = this.dialer.getTokens(this.addrs.length)\n\n // If no tokens are available, throw\n if (tokens.length < 1) {\n throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS)\n }\n\n const tokenHolder = new FIFO()\n\n for (const token of tokens) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n }\n\n const dialAbortControllers: Array<(AbortController | undefined)> = this.addrs.map(() => {\n const controller = new AbortController()\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n return controller\n })\n\n if (options.signal != null) {\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, options.signal)\n } catch {}\n }\n\n let completedDials = 0\n let done = false\n\n try {\n return await Promise.any(this.addrs.map(async (addr, i) => {\n const token = await tokenHolder.shift() // get token\n // End attempt once another attempt succeeded\n if (done) {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED)\n }\n\n const controller = dialAbortControllers[i]\n if (controller == null) {\n throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS)\n }\n let conn\n try {\n const signal = controller.signal\n conn = await this.dialAction(addr, { ...options, signal: (options.signal != null) ? anySignal([signal, options.signal]) : signal })\n // Remove the successful AbortController so it is not aborted\n dialAbortControllers[i] = undefined\n } finally {\n completedDials++\n // If we have more or equal dials remaining than tokens, recycle the token, otherwise release it\n if (this.addrs.length - completedDials >= tokens.length) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n } else {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n }\n }\n\n if (conn == null) {\n // Notify Promise.any that attempt was not successful\n // to prevent from returning undefined despite there\n // were successful dial attempts\n throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED)\n } else {\n // This dial succeeded, don't attempt anything else\n done = true\n }\n\n return conn\n }))\n } finally {\n // success/failure happened, abort everything else\n dialAbortControllers.forEach(c => {\n if (c !== undefined) {\n c.abort()\n }\n })\n tokens.forEach(token => this.dialer.releaseToken(token)) // release tokens back to the dialer\n }\n }\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport isIpPrivate from 'private-ip'\n\n/**\n * Check if a given multiaddr has a private address.\n */\nexport function isPrivate (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return Boolean(isIpPrivate(address))\n}\n","import type { Address } from '@libp2p/interface-peer-store'\nimport { isPrivate } from './multiaddr/is-private.js'\n\n/**\n * Compare function for array.sort().\n * This sort aims to move the private addresses to the end of the array.\n * In case of equality, a certified address will come first.\n */\nexport function publicAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n const isAPrivate = isPrivate(a.multiaddr)\n const isBPrivate = isPrivate(b.multiaddr)\n\n if (isAPrivate && !isBPrivate) {\n return 1\n } else if (!isAPrivate && isBPrivate) {\n return -1\n }\n // Check certified?\n if (a.isCertified && !b.isCertified) {\n return -1\n } else if (!a.isCertified && b.isCertified) {\n return 1\n }\n\n return 0\n}\n","\n/**\n * How long in ms a dial attempt is allowed to take\n */\nexport const DIAL_TIMEOUT = 30e3\n\n/**\n * How long in ms an inbound connection upgrade is allowed to take\n */\nexport const INBOUND_UPGRADE_TIMEOUT = 30e3\n\n/**\n * Maximum allowed concurrent dials\n */\nexport const MAX_PARALLEL_DIALS = 100\n\n/**\n * Allowed parallel dials per DialRequest\n */\nexport const MAX_PER_PEER_DIALS = 4\n\n/**\n * Maximum number of allowed addresses to attempt to dial\n */\nexport const MAX_ADDRS_TO_DIAL = 25\n\nexport const METRICS = {\n computeThrottleMaxQueueSize: 1000,\n computeThrottleTimeout: 2000,\n movingAverageIntervals: [\n 60 * 1000, // 1 minute\n 5 * 60 * 1000, // 5 minutes\n 15 * 60 * 1000 // 15 minutes\n ],\n maxOldPeersRetention: 50\n}\n","import { logger } from '@libp2p/logger'\nimport all from 'it-all'\nimport filter from 'it-filter'\nimport { pipe } from 'it-pipe'\nimport errCode from 'err-code'\nimport { Multiaddr, Resolver } from '@multiformats/multiaddr'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { AbortError } from '@libp2p/interfaces/errors'\nimport { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'events'\nimport { DialAction, DialRequest } from './dial-request.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport { codes } from '../../errors.js'\nimport {\n DIAL_TIMEOUT,\n MAX_PARALLEL_DIALS,\n MAX_PER_PEER_DIALS,\n MAX_ADDRS_TO_DIAL\n} from '../../constants.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { getPeer } from '../../get-peer.js'\nimport sort from 'it-sort'\nimport { Components, Initializable } from '@libp2p/components'\nimport map from 'it-map'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { ComponentMetricsTracker } from '@libp2p/interface-metrics'\n\nconst log = logger('libp2p:dialer')\n\nconst METRICS_COMPONENT = 'dialler'\nconst METRICS_PENDING_DIALS = 'pending-dials'\nconst METRICS_PENDING_DIAL_TARGETS = 'pending-dial-targets'\n\nexport interface DialTarget {\n id: string\n addrs: Multiaddr[]\n}\n\nexport interface PendingDial {\n dialRequest: DialRequest\n controller: TimeoutController\n promise: Promise\n destroy: () => void\n}\n\nexport interface PendingDialTarget {\n resolve: (value: any) => void\n reject: (err: Error) => void\n}\n\nexport interface DialerInit {\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take\n */\n dialTimeout?: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n metrics?: ComponentMetricsTracker\n}\n\nexport class Dialer implements Startable, Initializable {\n private components: Components = new Components()\n private readonly addressSorter: AddressSorter\n private readonly maxAddrsToDial: number\n private readonly timeout: number\n private readonly maxDialsPerPeer: number\n public tokens: number[]\n public pendingDials: Map\n public pendingDialTargets: Map\n private started: boolean\n\n constructor (init: DialerInit = {}) {\n this.started = false\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxAddrsToDial = init.maxAddrsToDial ?? MAX_ADDRS_TO_DIAL\n this.timeout = init.dialTimeout ?? DIAL_TIMEOUT\n this.maxDialsPerPeer = init.maxDialsPerPeer ?? MAX_PER_PEER_DIALS\n this.tokens = [...new Array(init.maxParallelDials ?? MAX_PARALLEL_DIALS)].map((_, index) => index)\n this.pendingDials = trackedMap({\n component: METRICS_COMPONENT,\n metric: METRICS_PENDING_DIALS,\n metrics: init.metrics\n })\n this.pendingDialTargets = trackedMap({\n component: METRICS_COMPONENT,\n metric: METRICS_PENDING_DIAL_TARGETS,\n metrics: init.metrics\n })\n\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n Multiaddr.resolvers.set(key, value)\n }\n }\n\n init (components: Components): void {\n this.components = components\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n /**\n * Clears any pending dials\n */\n async stop () {\n this.started = false\n\n for (const dial of this.pendingDials.values()) {\n try {\n dial.controller.abort()\n } catch (err: any) {\n log.error(err)\n }\n }\n this.pendingDials.clear()\n\n for (const pendingTarget of this.pendingDialTargets.values()) {\n pendingTarget.reject(new AbortError('Dialer was destroyed'))\n }\n this.pendingDialTargets.clear()\n }\n\n /**\n * Connects to a given `peer` by dialing all of its known addresses.\n * The dial to the first address that is successfully able to upgrade a connection\n * will be used.\n */\n async dial (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (this.components.getPeerId().equals(id)) {\n throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF)\n }\n\n log('check multiaddrs %p', id)\n\n if (multiaddrs != null && multiaddrs.length > 0) {\n log('storing multiaddrs %p', id, multiaddrs)\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n if (await this.components.getConnectionGater().denyDialPeer(id)) {\n throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED)\n }\n\n log('creating dial target for %p', id)\n\n const dialTarget = await this._createCancellableDialTarget(id, options)\n\n if (dialTarget.addrs.length === 0) {\n throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES)\n }\n\n const pendingDial = this.pendingDials.get(dialTarget.id) ?? this._createPendingDial(dialTarget, options)\n\n try {\n const connection = await pendingDial.promise\n log('dial succeeded to %s', dialTarget.id)\n return connection\n } catch (err: any) {\n log('dial failed to %s', dialTarget.id, err)\n // Error is a timeout\n if (pendingDial.controller.signal.aborted) {\n err.code = codes.ERR_TIMEOUT\n }\n log.error(err)\n throw err\n } finally {\n pendingDial.destroy()\n }\n }\n\n /**\n * Connects to a given `peer` by dialing all of its known addresses.\n * The dial to the first address that is successfully able to upgrade a connection\n * will be used.\n */\n async _createCancellableDialTarget (peer: PeerId, options: AbortOptions): Promise {\n // Make dial target promise cancellable\n const id = `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n const cancellablePromise = new Promise((resolve, reject) => {\n this.pendingDialTargets.set(id, { resolve, reject })\n })\n\n try {\n const dialTarget = await Promise.race([\n this._createDialTarget(peer, options),\n cancellablePromise\n ])\n\n return dialTarget\n } finally {\n this.pendingDialTargets.delete(id)\n }\n }\n\n /**\n * Creates a DialTarget. The DialTarget is used to create and track\n * the DialRequest to a given peer.\n * If a multiaddr is received it should be the first address attempted.\n * Multiaddrs not supported by the available transports will be filtered out.\n */\n async _createDialTarget (peer: PeerId, options: AbortOptions): Promise {\n const knownAddrs = await pipe(\n await this.components.getPeerStore().addressBook.get(peer),\n (source) => filter(source, async (address) => {\n return !(await this.components.getConnectionGater().denyDialMultiaddr(peer, address.multiaddr))\n }),\n (source) => sort(source, this.addressSorter),\n (source) => map(source, (address) => {\n const ma = address.multiaddr\n\n if (peer.toString() === ma.getPeerId()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${peer.toString()}`)\n }),\n async (source) => await all(source)\n )\n\n const addrs: Multiaddr[] = []\n for (const a of knownAddrs) {\n const resolvedAddrs = await this._resolve(a, options)\n resolvedAddrs.forEach(ra => addrs.push(ra))\n }\n\n // Multiaddrs not supported by the available transports will be filtered out.\n const supportedAddrs = addrs.filter(a => this.components.getTransportManager().transportForMultiaddr(a))\n\n if (supportedAddrs.length > this.maxAddrsToDial) {\n await this.components.getPeerStore().delete(peer)\n throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES)\n }\n\n return {\n id: peer.toString(),\n addrs: supportedAddrs\n }\n }\n\n /**\n * Creates a PendingDial that wraps the underlying DialRequest\n */\n _createPendingDial (dialTarget: DialTarget, options: AbortOptions = {}): PendingDial {\n /**\n * @param {Multiaddr} addr\n * @param {{ signal: { aborted: any; }; }} options\n */\n const dialAction: DialAction = async (addr, options = {}) => {\n if (options.signal?.aborted === true) {\n throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)\n }\n\n return await this.components.getTransportManager().dial(addr, options).catch(err => {\n log.error('dial to %s failed', addr, err)\n throw err\n })\n }\n\n const dialRequest = new DialRequest({\n addrs: dialTarget.addrs,\n dialAction,\n dialer: this\n })\n\n // Combine the timeout signal and options.signal, if provided\n const timeoutController = new TimeoutController(this.timeout)\n\n const signals = [timeoutController.signal]\n ;(options.signal != null) && signals.push(options.signal)\n const signal = anySignal(signals)\n\n // this signal will potentially be used while dialing lots of\n // peers so prevent MaxListenersExceededWarning appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, signal)\n } catch {}\n\n const pendingDial = {\n dialRequest,\n controller: timeoutController,\n promise: dialRequest.run({ ...options, signal }),\n destroy: () => {\n timeoutController.clear()\n this.pendingDials.delete(dialTarget.id)\n }\n }\n this.pendingDials.set(dialTarget.id, pendingDial)\n\n return pendingDial\n }\n\n getTokens (num: number) {\n const total = Math.min(num, this.maxDialsPerPeer, this.tokens.length)\n const tokens = this.tokens.splice(0, total)\n log('%d tokens request, returning %d, %d remaining', num, total, this.tokens.length)\n return tokens\n }\n\n releaseToken (token: number) {\n // Guard against duplicate releases\n if (this.tokens.includes(token)) {\n return\n }\n\n log('token %d released', token)\n this.tokens.push(token)\n }\n\n /**\n * Resolve multiaddr recursively\n */\n async _resolve (ma: Multiaddr, options: AbortOptions): Promise {\n // TODO: recursive logic should live in multiaddr once dns4/dns6 support is in place\n // Now only supporting resolve for dnsaddr\n const resolvableProto = ma.protoNames().includes('dnsaddr')\n\n // Multiaddr is not resolvable? End recursion!\n if (!resolvableProto) {\n return [ma]\n }\n\n const resolvedMultiaddrs = await this._resolveRecord(ma, options)\n const recursiveMultiaddrs = await Promise.all(resolvedMultiaddrs.map(async (nm) => {\n return await this._resolve(nm, options)\n }))\n\n const addrs = recursiveMultiaddrs.flat()\n return addrs.reduce((array, newM) => {\n if (array.find(m => m.equals(newM)) == null) {\n array.push(newM)\n }\n return array\n }, ([]))\n }\n\n /**\n * Resolve a given multiaddr. If this fails, an empty array will be returned\n */\n async _resolveRecord (ma: Multiaddr, options: AbortOptions): Promise {\n try {\n ma = new Multiaddr(ma.toString()) // Use current multiaddr module\n const multiaddrs = await ma.resolve(options)\n return multiaddrs\n } catch (err) {\n log.error(`multiaddr ${ma.toString()} could not be resolved`, err)\n return []\n }\n }\n}\n","\nexport const KEEP_ALIVE = 'keep-alive'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport mergeOptions from 'merge-options'\nimport { LatencyMonitor, SummaryObject } from './latency-monitor.js'\n// @ts-expect-error retimer does not have types\nimport retimer from 'retimer'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { codes } from '../errors.js'\nimport { isPeerId, PeerId } from '@libp2p/interface-peer-id'\nimport { setMaxListeners } from 'events'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport { Components, Initializable } from '@libp2p/components'\nimport * as STATUS from '@libp2p/interface-connection/status'\nimport { Dialer } from './dialer/index.js'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { Resolver } from '@multiformats/multiaddr'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { KEEP_ALIVE } from '@libp2p/interface-peer-store/tags'\n\nconst log = logger('libp2p:connection-manager')\n\nconst defaultOptions: Partial = {\n maxConnections: Infinity,\n minConnections: 0,\n maxData: Infinity,\n maxSentData: Infinity,\n maxReceivedData: Infinity,\n maxEventLoopDelay: Infinity,\n pollInterval: 2000,\n autoDialInterval: 10000,\n movingAverageInterval: 60000\n}\n\nconst METRICS_SYSTEM = 'libp2p'\nconst METRICS_COMPONENT = 'connection-manager'\nconst STARTUP_RECONNECT_TIMEOUT = 60000\n\nexport interface ConnectionManagerInit {\n /**\n * The maximum number of connections to keep open\n */\n maxConnections: number\n\n /**\n * The minimum number of connections to keep open\n */\n minConnections: number\n\n /**\n * The max data (in and out), per average interval to allow\n */\n maxData?: number\n\n /**\n * The max outgoing data, per average interval to allow\n */\n maxSentData?: number\n\n /**\n * The max incoming data, per average interval to allow\n */\n maxReceivedData?: number\n\n /**\n * The upper limit the event loop can take to run\n */\n maxEventLoopDelay?: number\n\n /**\n * How often, in milliseconds, metrics and latency should be checked\n */\n pollInterval?: number\n\n /**\n * How often, in milliseconds, to compute averages\n */\n movingAverageInterval?: number\n\n /**\n * If true, try to connect to all discovered peers up to the connection manager limit\n */\n autoDial?: boolean\n\n /**\n * How long to wait between attempting to keep our number of concurrent connections\n * above minConnections\n */\n autoDialInterval: number\n\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take, including DNS resolution\n * of the multiaddr, opening a socket and upgrading it to a Connection.\n */\n dialTimeout?: number\n\n /**\n * When a new inbound connection is opened, the upgrade process (e.g. protect,\n * encrypt, multiplex etc) must complete within this number of ms.\n */\n inboundUpgradeTimeout: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n\n /**\n * On startup we try to dial any peer that has previously been\n * tagged with KEEP_ALIVE up to this timeout in ms. (default: 60000)\n */\n startupReconnectTimeout?: number\n}\n\nexport interface ConnectionManagerEvents {\n 'peer:connect': CustomEvent\n 'peer:disconnect': CustomEvent\n}\n\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager extends EventEmitter implements ConnectionManager, Startable, Initializable {\n public readonly dialer: Dialer\n private components = new Components()\n private readonly opts: Required\n private readonly connections: Map\n private started: boolean\n private timer?: ReturnType\n private readonly latencyMonitor: LatencyMonitor\n private readonly startupReconnectTimeout: number\n private connectOnStartupController?: TimeoutController\n private readonly dialTimeout: number\n\n constructor (init: ConnectionManagerInit) {\n super()\n\n this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n\n if (this.opts.maxConnections < this.opts.minConnections) {\n throw errCode(new Error('Connection Manager maxConnections must be greater than minConnections'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log('options: %o', this.opts)\n\n /**\n * Map of connections per peer\n */\n this.connections = new Map()\n\n this.started = false\n this._checkMetrics = this._checkMetrics.bind(this)\n\n this.latencyMonitor = new LatencyMonitor({\n latencyCheckIntervalMs: init.pollInterval,\n dataEmitIntervalMs: init.pollInterval\n })\n\n try {\n // This emitter gets listened to a lot\n setMaxListeners?.(Infinity, this)\n } catch {}\n\n this.dialer = new Dialer(this.opts)\n\n this.onConnect = this.onConnect.bind(this)\n this.onDisconnect = this.onDisconnect.bind(this)\n\n this.startupReconnectTimeout = init.startupReconnectTimeout ?? STARTUP_RECONNECT_TIMEOUT\n this.dialTimeout = init.dialTimeout ?? 30000\n }\n\n init (components: Components): void {\n this.components = components\n\n this.dialer.init(components)\n\n // track inbound/outbound connections\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'connections',\n label: 'direction',\n value: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n }\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.stat.direction === 'inbound') {\n metric.inbound++\n } else {\n metric.outbound++\n }\n }\n }\n\n return metric\n }\n })\n\n // track total number of streams per protocol\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'protocol-streams-total',\n label: 'protocol',\n value: () => {\n const metric: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n metric[key] = (metric[key] ?? 0) + 1\n }\n }\n }\n\n return metric\n }\n })\n\n // track 90th percentile of streams per protocol\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'protocol-streams-per-connection-90th-percentile',\n label: 'protocol',\n value: () => {\n const allStreams: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams: Record = {}\n\n for (const stream of conn.streams) {\n const key = `${stream.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n streams[key] = (streams[key] ?? 0) + 1\n }\n\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? []\n allStreams[protocol].push(count)\n }\n }\n }\n\n const metric: Record = {}\n\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b)\n\n const index = Math.floor(counts.length * 0.9)\n metric[protocol] = counts[index]\n }\n\n return metric\n }\n })\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start () {\n if (this.components.getMetrics() != null) {\n this.timer = this.timer ?? retimer(this._checkMetrics, this.opts.pollInterval)\n }\n\n // latency monitor\n this.latencyMonitor.start()\n this._onLatencyMeasure = this._onLatencyMeasure.bind(this)\n this.latencyMonitor.addEventListener('data', this._onLatencyMeasure)\n await this.dialer.start()\n\n this.started = true\n log('started')\n }\n\n async afterStart () {\n this.components.getUpgrader().addEventListener('connection', this.onConnect)\n this.components.getUpgrader().addEventListener('connectionEnd', this.onDisconnect)\n\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers: PeerId[] = []\n\n for (const peer of await this.components.getPeerStore().all()) {\n const tags = await this.components.getPeerStore().getTags(peer.id)\n const hasKeepAlive = tags.filter(tag => tag.name === KEEP_ALIVE).length > 0\n\n if (hasKeepAlive) {\n keepAlivePeers.push(peer.id)\n }\n }\n\n this.connectOnStartupController?.clear()\n this.connectOnStartupController = new TimeoutController(this.startupReconnectTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.connectOnStartupController.signal)\n } catch {}\n\n await Promise.all(\n keepAlivePeers.map(async peer => {\n await this.openConnection(peer, {\n signal: this.connectOnStartupController?.signal\n })\n .catch(err => {\n log.error(err)\n })\n })\n )\n })\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n this.connectOnStartupController?.clear()\n })\n }\n\n async beforeStop () {\n // if we are still dialing KEEP_ALIVE peers, abort those dials\n this.connectOnStartupController?.abort()\n this.components.getUpgrader().removeEventListener('connection', this.onConnect)\n this.components.getUpgrader().removeEventListener('connectionEnd', this.onDisconnect)\n }\n\n /**\n * Stops the Connection Manager\n */\n async stop () {\n this.timer?.clear()\n\n this.latencyMonitor.removeEventListener('data', this._onLatencyMeasure)\n this.latencyMonitor.stop()\n await this.dialer.stop()\n\n this.started = false\n await this._close()\n log('stopped')\n }\n\n /**\n * Cleans up the connections\n */\n async _close () {\n // Close all connections we're tracking\n const tasks: Array> = []\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close()\n } catch (err) {\n log.error(err)\n }\n })())\n }\n }\n\n log('closing %d connections', tasks.length)\n await Promise.all(tasks)\n this.connections.clear()\n }\n\n /**\n * Checks the libp2p metrics to determine if any values have exceeded\n * the configured maximums.\n *\n * @private\n */\n async _checkMetrics () {\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n try {\n const movingAverages = metrics.getGlobal().getMovingAverages()\n const received = movingAverages.dataReceived[this.opts.movingAverageInterval].movingAverage\n await this._checkMaxLimit('maxReceivedData', received)\n const sent = movingAverages.dataSent[this.opts.movingAverageInterval].movingAverage\n await this._checkMaxLimit('maxSentData', sent)\n const total = received + sent\n await this._checkMaxLimit('maxData', total)\n log.trace('metrics update', total)\n } finally {\n this.timer = retimer(this._checkMetrics, this.opts.pollInterval)\n }\n }\n }\n\n onConnect (evt: CustomEvent) {\n void this._onConnect(evt).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close()\n return\n }\n\n const peerId = connection.remotePeer\n const peerIdStr = peerId.toString()\n const storedConns = this.connections.get(peerIdStr)\n\n if (storedConns != null) {\n storedConns.push(connection)\n } else {\n this.connections.set(peerIdStr, [connection])\n }\n\n if (peerId.publicKey != null) {\n await this.components.getPeerStore().keyBook.set(peerId, peerId.publicKey)\n }\n\n const numConnections = this.getConnections().length\n const toPrune = numConnections - this.opts.maxConnections\n\n await this._checkMaxLimit('maxConnections', numConnections, toPrune)\n this.dispatchEvent(new CustomEvent('peer:connect', { detail: connection }))\n }\n\n /**\n * Removes the connection from tracking\n */\n onDisconnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return\n }\n\n const peerId = connection.remotePeer.toString()\n let storedConn = this.connections.get(peerId)\n\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id)\n this.connections.set(peerId, storedConn)\n } else if (storedConn != null) {\n this.connections.delete(peerId)\n this.dispatchEvent(new CustomEvent('peer:disconnect', { detail: connection }))\n\n this.components.getMetrics()?.onPeerDisconnected(connection.remotePeer)\n }\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n if (peerId != null) {\n return this.connections.get(peerId.toString()) ?? []\n }\n\n let conns: Connection[] = []\n\n for (const c of this.connections.values()) {\n conns = conns.concat(c)\n }\n\n return conns\n }\n\n async openConnection (peerId: PeerId, options: AbortOptions = {}): Promise {\n log('dial to %p', peerId)\n const existingConnections = this.getConnections(peerId)\n\n if (existingConnections.length > 0) {\n log('had an existing connection to %p', peerId)\n\n return existingConnections[0]\n }\n\n let timeoutController: TimeoutController | undefined\n\n if (options?.signal == null) {\n timeoutController = new TimeoutController(this.dialTimeout)\n options.signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n const connection = await this.dialer.dial(peerId, options)\n let peerConnections = this.connections.get(peerId.toString())\n\n if (peerConnections == null) {\n peerConnections = []\n this.connections.set(peerId.toString(), peerConnections)\n }\n\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false\n\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true\n }\n }\n\n if (!trackedConnection) {\n peerConnections.push(connection)\n }\n\n return connection\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n }\n }\n\n async closeConnections (peerId: PeerId): Promise {\n const connections = this.connections.get(peerId.toString()) ?? []\n\n await Promise.all(\n connections.map(async connection => {\n return await connection.close()\n })\n )\n }\n\n /**\n * Get all open connections with a peer\n */\n getAll (peerId: PeerId): Connection[] {\n if (!isPeerId(peerId)) {\n throw errCode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const id = peerId.toString()\n const connections = this.connections.get(id)\n\n // Return all open connections\n if (connections != null) {\n return connections.filter(connection => connection.stat.status === STATUS.OPEN)\n }\n\n return []\n }\n\n /**\n * If the event loop is slow, maybe close a connection\n */\n _onLatencyMeasure (evt: CustomEvent) {\n const { detail: summary } = evt\n\n this._checkMaxLimit('maxEventLoopDelay', summary.avgMs, 1)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * If the `value` of `name` has exceeded its limit, maybe close a connection\n */\n async _checkMaxLimit (name: keyof ConnectionManagerInit, value: number, toPrune: number = 1) {\n const limit = this.opts[name]\n log.trace('checking limit of %s. current value: %d of %d', name, value, limit)\n if (value > limit) {\n log('%s: limit exceeded: %p, %d/%d, pruning %d connection(s)', this.components.getPeerId(), name, value, limit, toPrune)\n await this._maybePruneConnections(toPrune)\n }\n }\n\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async _maybePruneConnections (toPrune: number) {\n const connections = this.getConnections()\n\n if (connections.length <= this.opts.minConnections || toPrune < 1) {\n return\n }\n\n const peerValues = new PeerMap()\n\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer\n\n if (peerValues.has(remotePeer)) {\n continue\n }\n\n const tags = await this.components.getPeerStore().getTags(remotePeer)\n\n // sum all tag values\n peerValues.set(remotePeer, tags.reduce((acc, curr) => {\n return acc + curr.value\n }, 0))\n }\n\n // sort by value, lowest to highest\n const sortedConnections = connections.sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0\n const peerBValue = peerValues.get(b.remotePeer) ?? 0\n\n if (peerAValue > peerBValue) {\n return 1\n }\n\n if (peerAValue < peerBValue) {\n return -1\n }\n\n return 0\n })\n\n // close some connections\n const toClose = []\n\n for (const connection of sortedConnections) {\n log('too many connections open - closing a connection to %p', connection.remotePeer)\n toClose.push(connection)\n\n if (toClose.length === toPrune) {\n break\n }\n }\n\n // close connections\n await Promise.all(\n toClose.map(async connection => {\n try {\n await connection.close()\n } catch (err) {\n log.error(err)\n }\n\n // TODO: should not need to invoke this manually\n this.onDisconnect(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n })\n )\n }\n}\n","import { logger } from '@libp2p/logger'\nimport mergeOptions from 'merge-options'\n// @ts-expect-error retimer does not have types\nimport retimer from 'retimer'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:connection-manager:auto-dialler')\n\nexport interface AutoDiallerInit {\n /**\n * Should preemptively guarantee connections are above the low watermark\n */\n enabled?: boolean\n\n /**\n * The minimum number of connections to avoid pruning\n */\n minConnections?: number\n\n /**\n * How often, in milliseconds, it should preemptively guarantee connections are above the low watermark\n */\n autoDialInterval?: number\n}\n\nconst defaultOptions: Partial = {\n enabled: true,\n minConnections: 0,\n autoDialInterval: 10000\n}\n\nexport class AutoDialler implements Startable {\n private readonly components: Components\n private readonly options: Required\n private running: boolean\n private autoDialTimeout?: ReturnType\n\n /**\n * Proactively tries to connect to known peers stored in the PeerStore.\n * It will keep the number of connections below the upper limit and sort\n * the peers to connect based on wether we know their keys and protocols.\n */\n constructor (components: Components, init: AutoDiallerInit) {\n this.components = components\n this.options = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n this.running = false\n this._autoDial = this._autoDial.bind(this)\n\n log('options: %j', this.options)\n }\n\n isStarted () {\n return this.running\n }\n\n /**\n * Starts the auto dialer\n */\n async start () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = true\n\n void this._autoDial().catch(err => {\n log.error('could start autodial', err)\n })\n\n log('started')\n }\n\n /**\n * Stops the auto dialler\n */\n async stop () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = false\n\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n log('stopped')\n }\n\n async _autoDial () {\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n const minConnections = this.options.minConnections\n\n // Already has enough connections\n if (this.components.getConnectionManager().getConnections().length >= minConnections) {\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n\n return\n }\n\n // Sort peers on whether we know protocols or public keys for them\n const allPeers = await this.components.getPeerStore().all()\n\n const peers = await pipe(\n // shuffle the peers\n allPeers.sort(() => Math.random() > 0.5 ? 1 : -1),\n (source) => filter(source, (peer) => !peer.id.equals(this.components.getPeerId())),\n (source) => sort(source, (a, b) => {\n if (b.protocols.length > a.protocols.length) {\n return 1\n } else if (b.id.publicKey != null && a.id.publicKey == null) {\n return 1\n }\n return -1\n }),\n async (source) => await all(source)\n )\n\n for (let i = 0; this.running && i < peers.length && this.components.getConnectionManager().getConnections().length < minConnections; i++) {\n // Connection Manager was stopped during async dial\n if (!this.running) {\n return\n }\n\n const peer = peers[i]\n\n if (this.components.getConnectionManager().getConnections(peer.id).length === 0) {\n log('connecting to a peerStore stored peer %p', peer.id)\n try {\n await this.components.getConnectionManager().openConnection(peer.id)\n } catch (err: any) {\n log.error('could not connect to peerStore stored peer', err)\n }\n }\n }\n\n // Connection Manager was stopped\n if (!this.running) {\n return\n }\n\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface CircuitRelay {\n type?: CircuitRelay.Type\n srcPeer?: CircuitRelay.Peer\n dstPeer?: CircuitRelay.Peer\n code?: CircuitRelay.Status\n}\n\nexport namespace CircuitRelay {\n export enum Status {\n SUCCESS = 'SUCCESS',\n HOP_SRC_ADDR_TOO_LONG = 'HOP_SRC_ADDR_TOO_LONG',\n HOP_DST_ADDR_TOO_LONG = 'HOP_DST_ADDR_TOO_LONG',\n HOP_SRC_MULTIADDR_INVALID = 'HOP_SRC_MULTIADDR_INVALID',\n HOP_DST_MULTIADDR_INVALID = 'HOP_DST_MULTIADDR_INVALID',\n HOP_NO_CONN_TO_DST = 'HOP_NO_CONN_TO_DST',\n HOP_CANT_DIAL_DST = 'HOP_CANT_DIAL_DST',\n HOP_CANT_OPEN_DST_STREAM = 'HOP_CANT_OPEN_DST_STREAM',\n HOP_CANT_SPEAK_RELAY = 'HOP_CANT_SPEAK_RELAY',\n HOP_CANT_RELAY_TO_SELF = 'HOP_CANT_RELAY_TO_SELF',\n STOP_SRC_ADDR_TOO_LONG = 'STOP_SRC_ADDR_TOO_LONG',\n STOP_DST_ADDR_TOO_LONG = 'STOP_DST_ADDR_TOO_LONG',\n STOP_SRC_MULTIADDR_INVALID = 'STOP_SRC_MULTIADDR_INVALID',\n STOP_DST_MULTIADDR_INVALID = 'STOP_DST_MULTIADDR_INVALID',\n STOP_RELAY_REFUSED = 'STOP_RELAY_REFUSED',\n MALFORMED_MESSAGE = 'MALFORMED_MESSAGE'\n }\n\n enum __StatusValues {\n SUCCESS = 100,\n HOP_SRC_ADDR_TOO_LONG = 220,\n HOP_DST_ADDR_TOO_LONG = 221,\n HOP_SRC_MULTIADDR_INVALID = 250,\n HOP_DST_MULTIADDR_INVALID = 251,\n HOP_NO_CONN_TO_DST = 260,\n HOP_CANT_DIAL_DST = 261,\n HOP_CANT_OPEN_DST_STREAM = 262,\n HOP_CANT_SPEAK_RELAY = 270,\n HOP_CANT_RELAY_TO_SELF = 280,\n STOP_SRC_ADDR_TOO_LONG = 320,\n STOP_DST_ADDR_TOO_LONG = 321,\n STOP_SRC_MULTIADDR_INVALID = 350,\n STOP_DST_MULTIADDR_INVALID = 351,\n STOP_RELAY_REFUSED = 390,\n MALFORMED_MESSAGE = 400\n }\n\n export namespace Status {\n export const codec = () => {\n return enumeration(__StatusValues)\n }\n }\n\n export enum Type {\n HOP = 'HOP',\n STOP = 'STOP',\n STATUS = 'STATUS',\n CAN_HOP = 'CAN_HOP'\n }\n\n enum __TypeValues {\n HOP = 1,\n STOP = 2,\n STATUS = 3,\n CAN_HOP = 4\n }\n\n export namespace Type {\n export const codec = () => {\n return enumeration(__TypeValues)\n }\n }\n\n export interface Peer {\n id: Uint8Array\n addrs: Uint8Array[]\n }\n\n export namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.id != null) {\n writer.uint32(10)\n writer.bytes(obj.id)\n } else {\n throw new Error('Protocol error: required field \"id\" was not found in object')\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n writer.uint32(18)\n writer.bytes(value)\n }\n } else {\n throw new Error('Protocol error: required field \"addrs\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.addrs = obj.addrs ?? []\n obj.addrs.push(reader.bytes())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n obj.addrs = obj.addrs ?? []\n\n if (obj.id == null) {\n throw new Error('Protocol error: value for required field \"id\" was not found in protobuf')\n }\n\n if (obj.addrs == null) {\n throw new Error('Protocol error: value for required field \"addrs\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.type != null) {\n writer.uint32(8)\n CircuitRelay.Type.codec().encode(obj.type, writer)\n }\n\n if (obj.srcPeer != null) {\n writer.uint32(18)\n CircuitRelay.Peer.codec().encode(obj.srcPeer, writer)\n }\n\n if (obj.dstPeer != null) {\n writer.uint32(26)\n CircuitRelay.Peer.codec().encode(obj.dstPeer, writer)\n }\n\n if (obj.code != null) {\n writer.uint32(32)\n CircuitRelay.Status.codec().encode(obj.code, writer)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.type = CircuitRelay.Type.codec().decode(reader)\n break\n case 2:\n obj.srcPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 3:\n obj.dstPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 4:\n obj.code = CircuitRelay.Status.codec().decode(reader)\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: CircuitRelay): Uint8Array => {\n return encodeMessage(obj, CircuitRelay.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): CircuitRelay => {\n return decodeMessage(buf, CircuitRelay.codec())\n }\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:stream:converter')\n\nexport interface Timeline {\n /**\n * Connection opening timestamp\n */\n open: number\n\n /**\n * Connection upgraded timestamp\n */\n upgraded?: number\n\n /**\n * Connection closed timestamp\n */\n close?: number\n}\n\ninterface StreamOptions {\n signal?: AbortSignal\n\n}\n\ninterface StreamProperties {\n stream: Duplex\n remoteAddr: Multiaddr\n localAddr: Multiaddr\n}\n\n/**\n * Convert a duplex iterable into a MultiaddrConnection.\n * https://github.com/libp2p/interface-transport#multiaddrconnection\n */\nexport function streamToMaConnection (props: StreamProperties, options: StreamOptions = {}) {\n const { stream, remoteAddr } = props\n const { sink, source } = stream\n\n const mapSource = (async function * () {\n for await (const list of source) {\n yield * list\n }\n }())\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if (options.signal != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await sink(source)\n await close()\n } catch (err: any) {\n // If aborted we can safely ignore\n if (err.type !== 'aborted') {\n // If the source errored the socket will already have been destroyed by\n // toIterable.duplex(). If the socket errored it will already be\n // destroyed. There's nothing to do here except log the error & return.\n log(err)\n }\n }\n },\n source: (options.signal != null) ? abortableSource(mapSource, options.signal) : mapSource,\n remoteAddr,\n /** @type {Timeline} */\n timeline: { open: Date.now(), close: undefined },\n async close () {\n await sink(async function * () {\n yield new Uint8Array(0)\n }())\n await close()\n }\n }\n\n async function close () {\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n return await Promise.resolve()\n }\n\n return maConn\n}\n","\nexport const RELAY_CODEC = '/libp2p/circuit/relay/0.1.0'\n","import { Multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { StreamHandler } from './stream-handler.js'\n\n/**\n * Write a response\n */\nfunction writeResponse (streamHandler: StreamHandler, status: CircuitRelay.Status) {\n streamHandler.write({\n type: CircuitRelay.Type.STATUS,\n code: status\n })\n}\n\n/**\n * Validate incomming HOP/STOP message\n */\nexport function validateAddrs (msg: CircuitRelay, streamHandler: StreamHandler) {\n try {\n if (msg.dstPeer?.addrs != null) {\n msg.dstPeer.addrs.forEach((addr) => {\n return new Multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_DST_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_DST_MULTIADDR_INVALID)\n throw err\n }\n\n try {\n if (msg.srcPeer?.addrs != null) {\n msg.srcPeer.addrs.forEach((addr) => {\n return new Multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_SRC_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_SRC_MULTIADDR_INVALID)\n throw err\n }\n}\n","import { logger } from '@libp2p/logger'\nimport * as lp from 'it-length-prefixed'\nimport { Handshake, handshake } from 'it-handshake'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stream-handler')\n\nexport interface StreamHandlerOptions {\n /**\n * A duplex iterable\n */\n stream: Stream\n\n /**\n * max bytes length of message\n */\n maxLength?: number\n}\n\nexport class StreamHandler {\n private readonly stream: Stream\n private readonly shake: Handshake\n private readonly decoder: Source\n\n constructor (options: StreamHandlerOptions) {\n const { stream, maxLength = 4096 } = options\n\n this.stream = stream\n this.shake = handshake(this.stream)\n this.decoder = lp.decode.fromReader(this.shake.reader, { maxDataLength: maxLength })\n }\n\n /**\n * Read and decode message\n */\n async read () {\n // @ts-expect-error FIXME is a source, needs to be a generator\n const msg = await this.decoder.next()\n\n if (msg.value != null) {\n const value = CircuitRelay.decode(msg.value)\n log('read message type', value.type)\n return value\n }\n\n log('read received no value, closing stream')\n // End the stream, we didn't get data\n this.close()\n }\n\n /**\n * Encode and write array of buffers\n */\n write (msg: CircuitRelay) {\n log('write message type %s', msg.type)\n this.shake.write(lp.encode.single(CircuitRelay.encode(msg)))\n }\n\n /**\n * Return the handshake rest stream and invalidate handler\n */\n rest () {\n this.shake.rest()\n return this.shake.stream\n }\n\n /**\n * @param {CircuitRelay} msg - An unencoded CircuitRelay protobuf message\n */\n end (msg: CircuitRelay) {\n this.write(msg)\n this.close()\n }\n\n /**\n * Close the stream\n */\n close () {\n log('closing the stream')\n void this.rest().sink([]).catch(err => {\n log.error(err)\n })\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { validateAddrs } from './utils.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stop')\n\nexport interface HandleStopOptions {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n}\n\n/**\n * Handles incoming STOP requests\n */\nexport function handleStop (options: HandleStopOptions): Duplex | undefined {\n const {\n connection,\n request,\n streamHandler\n } = options\n\n // Validate the STOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid stop request via peer %p %o', connection.remotePeer, err)\n return\n }\n\n // The request is valid\n log('stop request is valid')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n\n return streamHandler.rest()\n}\n\nexport interface StopOptions extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Creates a STOP request\n */\nexport async function stop (options: StopOptions) {\n const {\n connection,\n request,\n signal\n } = options\n\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n log('starting stop request to %p', connection.remotePeer)\n const streamHandler = new StreamHandler({ stream })\n\n streamHandler.write(request)\n const response = await streamHandler.read()\n\n if (response == null) {\n streamHandler.close()\n return\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('stop request to %p was successful', connection.remotePeer)\n return streamHandler.rest()\n }\n\n log('stop request failed with code %d', response.code)\n streamHandler.close()\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { validateAddrs } from './utils.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { pipe } from 'it-pipe'\nimport { codes as Errors } from '../../errors.js'\nimport { stop } from './stop.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { Duplex } from 'it-stream-types'\nimport type { Circuit } from '../transport.js'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:hop')\n\nexport interface HopRequest {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n circuit: Circuit\n connectionManager: ConnectionManager\n}\n\nexport async function handleHop (hopRequest: HopRequest): Promise {\n const {\n connection,\n request,\n streamHandler,\n circuit,\n connectionManager\n } = hopRequest\n\n // Ensure hop is enabled\n if (!circuit.hopEnabled()) {\n log('HOP request received but we are not acting as a relay')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n }\n\n // Validate the HOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid hop request via peer %p %o', connection.remotePeer, err)\n\n return\n }\n\n if (request.dstPeer == null) {\n log('HOP request received but we do not receive a dstPeer')\n return\n }\n\n // Get the connection to the destination (stop) peer\n const destinationPeer = peerIdFromBytes(request.dstPeer.id)\n\n const destinationConnections = connectionManager.getConnections(destinationPeer)\n if (destinationConnections.length === 0 && !circuit.hopActive()) {\n log('HOP request received but we are not connected to the destination peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // TODO: Handle being an active relay\n if (destinationConnections.length === 0) {\n log('did not have connection to remote peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // Handle the incoming HOP request by performing a STOP request\n const stopRequest = {\n type: CircuitPB.Type.STOP,\n dstPeer: request.dstPeer,\n srcPeer: request.srcPeer\n }\n\n let destinationStream: Duplex\n try {\n log('performing STOP request')\n const result = await stop({\n connection: destinationConnections[0],\n request: stopRequest\n })\n\n if (result == null) {\n throw new Error('Could not stop')\n }\n\n destinationStream = result\n } catch (err: any) {\n log.error(err)\n\n return\n }\n\n log('hop request from %p is valid', connection.remotePeer)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n const sourceStream = streamHandler.rest()\n\n log('creating related connections')\n // Short circuit the two streams to create the relayed connection\n return await pipe(\n sourceStream,\n destinationStream,\n sourceStream\n )\n}\n\nexport interface HopConfig extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Performs a HOP request to a relay peer, to request a connection to another\n * peer. A new, virtual, connection will be created between the two via the relay.\n */\nexport async function hop (options: HopConfig): Promise> {\n const {\n connection,\n request,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write(request)\n\n const response = await streamHandler.read()\n\n if (response == null) {\n throw errCode(new Error('HOP request had no response'), Errors.ERR_HOP_REQUEST_FAILED)\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('hop request was successful')\n\n return streamHandler.rest()\n }\n\n log('hop request failed with code %d, closing stream', response.code)\n streamHandler.close()\n\n throw errCode(new Error(`HOP request failed with code \"${response.code ?? 'unknown'}\"`), Errors.ERR_HOP_REQUEST_FAILED)\n}\n\nexport interface CanHopOptions extends AbortOptions {\n connection: Connection\n}\n\n/**\n * Performs a CAN_HOP request to a relay peer, in order to understand its capabilities\n */\nexport async function canHop (options: CanHopOptions) {\n const {\n connection,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write({\n type: CircuitPB.Type.CAN_HOP\n })\n\n const response = await streamHandler.read()\n await streamHandler.close()\n\n if (response == null || response.code !== CircuitPB.Status.SUCCESS) {\n return false\n }\n\n return true\n}\n\nexport interface HandleCanHopOptions {\n connection: Connection\n streamHandler: StreamHandler\n circuit: Circuit\n}\n\n/**\n * Creates an unencoded CAN_HOP response based on the Circuits configuration\n */\nexport function handleCanHop (options: HandleCanHopOptions) {\n const {\n connection,\n streamHandler,\n circuit\n } = options\n const canHop = circuit.hopEnabled()\n log('can hop (%s) request from %p', canHop, connection.remotePeer)\n streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: canHop ? CircuitPB.Status.SUCCESS : CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mafmt from '@multiformats/mafmt'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay as CircuitPB } from './pb/index.js'\nimport { codes } from '../errors.js'\nimport { streamToMaConnection } from '@libp2p/utils/stream-to-ma-conn'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { createListener } from './listener.js'\nimport { handleCanHop, handleHop, hop } from './circuit/hop.js'\nimport { handleStop } from './circuit/stop.js'\nimport { StreamHandler } from './circuit/stream-handler.js'\nimport { symbol } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { Components, Initializable } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Listener, Transport, CreateListenerOptions, ConnectionHandler } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { RelayConfig } from '../index.js'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\n\nconst log = logger('libp2p:circuit')\n\nexport class Circuit implements Transport, Initializable {\n private handler?: ConnectionHandler\n private components: Components = new Components()\n private readonly _init: RelayConfig\n\n constructor (init: RelayConfig) {\n this._init = init\n }\n\n init (components: Components): void {\n this.components = components\n void this.components.getRegistrar().handle(RELAY_CODEC, (data) => {\n void this._onProtocol(data).catch(err => {\n log.error(err)\n })\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n hopEnabled () {\n return true\n }\n\n hopActive () {\n return true\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return 'libp2p/circuit-relay-v1'\n }\n\n async _onProtocol (data: IncomingStreamData) {\n const { connection, stream } = data\n const controller = new TimeoutController(this._init.hop.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n try {\n const source = abortableDuplex(stream, controller.signal)\n const streamHandler = new StreamHandler({\n stream: {\n ...stream,\n ...source\n }\n })\n const request = await streamHandler.read()\n\n if (request == null) {\n log('request was invalid, could not read from stream')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n\n let virtualConnection: Duplex | undefined\n\n switch (request.type) {\n case CircuitPB.Type.CAN_HOP: {\n log('received CAN_HOP request from %p', connection.remotePeer)\n await handleCanHop({ circuit: this, connection, streamHandler })\n break\n }\n case CircuitPB.Type.HOP: {\n log('received HOP request from %p', connection.remotePeer)\n await handleHop({\n connection,\n request,\n streamHandler,\n circuit: this,\n connectionManager: this.components.getConnectionManager()\n })\n break\n }\n case CircuitPB.Type.STOP: {\n log('received STOP request from %p', connection.remotePeer)\n virtualConnection = await handleStop({\n connection,\n request,\n streamHandler\n })\n break\n }\n default: {\n log('Request of type %s not supported', request.type)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n }\n\n if (virtualConnection != null) {\n const remoteAddr = connection.remoteAddr\n .encapsulate('/p2p-circuit')\n .encapsulate(new Multiaddr(request.dstPeer?.addrs[0]))\n const localAddr = new Multiaddr(request.srcPeer?.addrs[0])\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr,\n localAddr\n })\n const type = request.type === CircuitPB.Type.HOP ? 'relay' : 'inbound'\n log('new %s connection %s', type, maConn.remoteAddr)\n\n const conn = await this.components.getUpgrader().upgradeInbound(maConn)\n log('%s connection %s upgraded', type, maConn.remoteAddr)\n\n if (this.handler != null) {\n this.handler(conn)\n }\n }\n } finally {\n controller.clear()\n }\n }\n\n /**\n * Dial a peer over a relay\n */\n async dial (ma: Multiaddr, options: AbortOptions = {}): Promise {\n // Check the multiaddr to see if it contains a relay and a destination peer\n const addrs = ma.toString().split('/p2p-circuit')\n const relayAddr = new Multiaddr(addrs[0])\n const destinationAddr = new Multiaddr(addrs[addrs.length - 1])\n const relayId = relayAddr.getPeerId()\n const destinationId = destinationAddr.getPeerId()\n\n if (relayId == null || destinationId == null) {\n const errMsg = 'Circuit relay dial failed as addresses did not have peer id'\n log.error(errMsg)\n throw errCode(new Error(errMsg), codes.ERR_RELAYED_DIAL)\n }\n\n const relayPeer = peerIdFromString(relayId)\n const destinationPeer = peerIdFromString(destinationId)\n\n let disconnectOnFailure = false\n const relayConnections = this.components.getConnectionManager().getConnections(relayPeer)\n let relayConnection = relayConnections[0]\n\n if (relayConnection == null) {\n await this.components.getPeerStore().addressBook.add(relayPeer, [relayAddr])\n relayConnection = await this.components.getConnectionManager().openConnection(relayPeer, options)\n disconnectOnFailure = true\n }\n\n try {\n const virtualConnection = await hop({\n ...options,\n connection: relayConnection,\n request: {\n type: CircuitPB.Type.HOP,\n srcPeer: {\n id: this.components.getPeerId().toBytes(),\n addrs: this.components.getAddressManager().getAddresses().map(addr => addr.bytes)\n },\n dstPeer: {\n id: destinationPeer.toBytes(),\n addrs: [new Multiaddr(destinationAddr).bytes]\n }\n }\n })\n\n const localAddr = relayAddr.encapsulate(`/p2p-circuit/p2p/${this.components.getPeerId().toString()}`)\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr: ma,\n localAddr\n })\n log('new outbound connection %s', maConn.remoteAddr)\n\n return await this.components.getUpgrader().upgradeOutbound(maConn)\n } catch (err: any) {\n log.error('Circuit relay dial failed', err)\n disconnectOnFailure && await relayConnection.close()\n throw err\n }\n }\n\n /**\n * Create a listener\n */\n createListener (options: CreateListenerOptions): Listener {\n // Called on successful HOP and STOP requests\n this.handler = options.handler\n\n return createListener({\n connectionManager: this.components.getConnectionManager(),\n peerStore: this.components.getPeerStore()\n })\n }\n\n /**\n * Filter check for all Multiaddrs that this transport can dial on\n *\n * @param {Multiaddr[]} multiaddrs\n * @returns {Multiaddr[]}\n */\n filter (multiaddrs: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n return mafmt.Circuit.matches(ma)\n })\n }\n}\n","import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Listener } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface ListenerOptions {\n peerStore: PeerStore\n connectionManager: ConnectionManager\n}\n\nexport function createListener (options: ListenerOptions): Listener {\n const listeningAddrs = new Map()\n\n /**\n * Add swarm handler and listen for incoming connections\n */\n async function listen (addr: Multiaddr): Promise {\n const addrString = addr.toString().split('/p2p-circuit').find(a => a !== '')\n const ma = new Multiaddr(addrString)\n\n const relayPeerStr = ma.getPeerId()\n\n if (relayPeerStr == null) {\n throw new Error('Could not determine relay peer from multiaddr')\n }\n\n const relayPeerId = peerIdFromString(relayPeerStr)\n\n await options.peerStore.addressBook.add(relayPeerId, [ma])\n\n const relayConn = await options.connectionManager.openConnection(relayPeerId)\n const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit')\n\n listeningAddrs.set(relayConn.remotePeer.toString(), relayedAddr)\n listener.dispatchEvent(new CustomEvent('listening'))\n }\n\n /**\n * Get fixed up multiaddrs\n *\n * NOTE: This method will grab the peers multiaddrs and expand them such that:\n *\n * a) If it's an existing /p2p-circuit address for a specific relay i.e.\n * `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the\n * address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where\n * `QmPeer` is this peers id\n * b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit\n * addr, such when dialing over a relay with this address, it will create the circuit using\n * the encapsulated transport address. This is useful when for example, a peer should only\n * be dialed over TCP rather than any other transport\n *\n * @returns {Multiaddr[]}\n */\n function getAddrs () {\n const addrs = []\n for (const addr of listeningAddrs.values()) {\n addrs.push(addr)\n }\n return addrs\n }\n\n const listener: Listener = Object.assign(new EventEmitter(), {\n close: async () => await Promise.resolve(),\n listen,\n getAddrs\n })\n\n // Remove listeningAddrs when a peer disconnects\n options.connectionManager.addEventListener('peer:disconnect', (evt) => {\n const { detail: connection } = evt\n const deleted = listeningAddrs.delete(connection.remotePeer.toString())\n\n if (deleted) {\n // Announce listen addresses change\n listener.dispatchEvent(new CustomEvent('close'))\n }\n })\n\n return listener\n}\n","import { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * Convert a namespace string into a cid\n */\nexport async function namespaceToCid (namespace: string): Promise {\n const bytes = new TextEncoder().encode(namespace)\n const hash = await sha256.digest(bytes)\n\n return CID.createV0(hash)\n}\n","const minute = 60 * 1000\n\n/**\n * Delay before HOP relay service is advertised on the network\n */\nexport const ADVERTISE_BOOT_DELAY = 15 * minute\n\n/**\n * Delay Between HOP relay service advertisements on the network\n */\nexport const ADVERTISE_TTL = 30 * minute\n\n/**\n * Multicodec code\n */\nexport const CIRCUIT_PROTO_CODE = 290\n\n/**\n * PeerStore metadaBook key for HOP relay service\n */\nexport const HOP_METADATA_KEY = 'hop_relay'\n\n/**\n * PeerStore metadaBook value for HOP relay service\n */\nexport const HOP_METADATA_VALUE = 'true'\n\n/**\n * Relay HOP relay service namespace for discovery\n */\nexport const RELAY_RENDEZVOUS_NS = '/libp2p/relay'\n","import { logger } from '@libp2p/logger'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { canHop } from './circuit/hop.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n CIRCUIT_PROTO_CODE,\n HOP_METADATA_KEY,\n HOP_METADATA_VALUE,\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressSorter, PeerProtocolsChangeData } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Components } from '@libp2p/components'\nimport sort from 'it-sort'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\n\nconst log = logger('libp2p:auto-relay')\n\nconst noop = () => {}\n\nexport interface AutoRelayInit {\n addressSorter?: AddressSorter\n maxListeners?: number\n onError?: (error: Error, msg?: string) => void\n}\n\nexport class AutoRelay {\n private readonly components: Components\n private readonly addressSorter: AddressSorter\n private readonly maxListeners: number\n private readonly listenRelays: Set\n private readonly onError: (error: Error, msg?: string) => void\n\n constructor (components: Components, init: AutoRelayInit) {\n this.components = components\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxListeners = init.maxListeners ?? 1\n this.listenRelays = new Set()\n this.onError = init.onError ?? noop\n\n this._onProtocolChange = this._onProtocolChange.bind(this)\n this._onPeerDisconnected = this._onPeerDisconnected.bind(this)\n\n this.components.getPeerStore().addEventListener('change:protocols', (evt) => {\n void this._onProtocolChange(evt).catch(err => {\n log.error(err)\n })\n })\n this.components.getConnectionManager().addEventListener('peer:disconnect', this._onPeerDisconnected)\n }\n\n /**\n * Check if a peer supports the relay protocol.\n * If the protocol is not supported, check if it was supported before and remove it as a listen relay.\n * If the protocol is supported, check if the peer supports **HOP** and add it as a listener if\n * inside the threshold.\n */\n async _onProtocolChange (evt: CustomEvent) {\n const {\n peerId,\n protocols\n } = evt.detail\n const id = peerId.toString()\n\n // Check if it has the protocol\n const hasProtocol = protocols.find(protocol => protocol === RELAY_CODEC)\n\n // If no protocol, check if we were keeping the peer before as a listenRelay\n if (hasProtocol == null) {\n if (this.listenRelays.has(id)) {\n await this._removeListenRelay(id)\n }\n\n return\n }\n\n if (this.listenRelays.has(id)) {\n return\n }\n\n // If protocol, check if can hop, store info in the metadataBook and listen on it\n try {\n const connections = this.components.getConnectionManager().getConnections(peerId)\n\n if (connections.length === 0) {\n return\n }\n\n const connection = connections[0]\n\n // Do not hop on a relayed connection\n if (connection.remoteAddr.protoCodes().includes(CIRCUIT_PROTO_CODE)) {\n log(`relayed connection to ${id} will not be used to hop on`)\n return\n }\n\n const supportsHop = await canHop({ connection })\n\n if (supportsHop) {\n await this.components.getPeerStore().metadataBook.setValue(peerId, HOP_METADATA_KEY, uint8ArrayFromString(HOP_METADATA_VALUE))\n await this._addListenRelay(connection, id)\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n /**\n * Peer disconnects\n */\n _onPeerDisconnected (evt: CustomEvent) {\n const connection = evt.detail\n const peerId = connection.remotePeer\n const id = peerId.toString()\n\n // Not listening on this relay\n if (!this.listenRelays.has(id)) {\n return\n }\n\n this._removeListenRelay(id).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Attempt to listen on the given relay connection\n */\n async _addListenRelay (connection: Connection, id: string): Promise {\n try {\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n // Get peer known addresses and sort them with public addresses first\n const remoteAddrs = await pipe(\n await this.components.getPeerStore().addressBook.get(connection.remotePeer),\n (source) => sort(source, this.addressSorter),\n async (source) => await all(source)\n )\n\n // Attempt to listen on relay\n const result = await Promise.all(\n remoteAddrs.map(async addr => {\n try {\n let multiaddr = addr.multiaddr\n\n if (multiaddr.getPeerId() == null) {\n multiaddr = multiaddr.encapsulate(`/p2p/${connection.remotePeer.toString()}`)\n }\n\n multiaddr = multiaddr.encapsulate('/p2p-circuit')\n\n // Announce multiaddrs will update on listen success by TransportManager event being triggered\n await this.components.getTransportManager().listen([multiaddr])\n return true\n } catch (err: any) {\n log.error('error listening on circuit address', err)\n this.onError(err)\n }\n\n return false\n })\n )\n\n if (result.includes(true)) {\n this.listenRelays.add(id)\n }\n } catch (err: any) {\n this.onError(err)\n this.listenRelays.delete(id)\n }\n }\n\n /**\n * Remove listen relay\n */\n async _removeListenRelay (id: string) {\n if (this.listenRelays.delete(id)) {\n // TODO: this should be responsibility of the connMgr\n await this._listenOnAvailableHopRelays([id])\n }\n }\n\n /**\n * Try to listen on available hop relay connections.\n * The following order will happen while we do not have enough relays.\n * 1. Check the metadata store for known relays, try to listen on the ones we are already connected.\n * 2. Dial and try to listen on the peers we know that support hop but are not connected.\n * 3. Search the network.\n */\n async _listenOnAvailableHopRelays (peersToIgnore: string[] = []) {\n // TODO: The peer redial issue on disconnect should be handled by connection gating\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n const knownHopsToDial = []\n const peers = await this.components.getPeerStore().all()\n\n // Check if we have known hop peers to use and attempt to listen on the already connected\n for (const { id, metadata } of peers) {\n const idStr = id.toString()\n\n // Continue to next if listening on this or peer to ignore\n if (this.listenRelays.has(idStr)) {\n continue\n }\n\n if (peersToIgnore.includes(idStr)) {\n continue\n }\n\n const supportsHop = metadata.get(HOP_METADATA_KEY)\n\n // Continue to next if it does not support Hop\n if ((supportsHop == null) || uint8ArrayToString(supportsHop) !== HOP_METADATA_VALUE) {\n continue\n }\n\n const connections = this.components.getConnectionManager().getConnections(id)\n\n // If not connected, store for possible later use.\n if (connections.length === 0) {\n knownHopsToDial.push(id)\n continue\n }\n\n await this._addListenRelay(connections[0], idStr)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to listen on known peers that are not connected\n for (const peerId of knownHopsToDial) {\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to find relays to hop on the network\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n for await (const provider of this.components.getContentRouting().findProviders(cid)) {\n if (provider.multiaddrs.length === 0) {\n continue\n }\n\n const peerId = provider.id\n\n if (peerId.equals(this.components.getPeerId())) {\n // Skip the provider if it's us as dialing will fail\n continue\n }\n\n await this.components.getPeerStore().addressBook.add(peerId, provider.multiaddrs)\n\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n async _tryToListenOnRelay (peerId: PeerId) {\n try {\n const connection = await this.components.getConnectionManager().openConnection(peerId)\n await this._addListenRelay(connection, peerId.toString())\n } catch (err: any) {\n log.error('Could not use %p as relay', peerId, err)\n this.onError(err, `could not connect and listen on known hop relay ${peerId.toString()}`)\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { codes } from '../errors.js'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error set-delayed-interval does not export types\n} from 'set-delayed-interval'\nimport { AutoRelay } from './auto-relay.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport type { RelayConfig } from '../index.js'\n\nconst log = logger('libp2p:relay')\n\nexport interface RelayAdvertiseConfig {\n bootDelay?: number\n enabled?: boolean\n ttl?: number\n}\n\nexport interface AutoRelayConfig {\n enabled?: boolean\n\n /**\n * maximum number of relays to listen\n */\n maxListeners: number\n}\n\nexport interface RelayInit extends RelayConfig {\n addressSorter?: AddressSorter\n}\n\nexport class Relay implements Startable {\n private readonly components: Components\n private readonly init: RelayInit\n // @ts-expect-error this field isn't used anywhere?\n private readonly autoRelay?: AutoRelay\n private timeout?: any\n private started: boolean\n\n /**\n * Creates an instance of Relay\n */\n constructor (components: Components, init: RelayInit) {\n this.components = components\n // Create autoRelay if enabled\n this.autoRelay = init.autoRelay?.enabled !== false\n ? new AutoRelay(components, {\n addressSorter: init.addressSorter,\n ...init.autoRelay\n })\n : undefined\n\n this.started = false\n this.init = init\n this._advertiseService = this._advertiseService.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start Relay service\n */\n async start () {\n // Advertise service if HOP enabled\n if (this.init.hop.enabled !== false && this.init.advertise.enabled !== false) {\n this.timeout = setDelayedInterval(\n this._advertiseService, this.init.advertise.ttl, this.init.advertise.bootDelay\n )\n }\n\n this.started = true\n }\n\n /**\n * Stop Relay service\n */\n async stop () {\n if (this.timeout != null) {\n clearDelayedInterval(this.timeout)\n }\n\n this.started = false\n }\n\n /**\n * Advertise hop relay service in the network.\n */\n async _advertiseService () {\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n await this.components.getContentRouting().provide(cid)\n } catch (err: any) {\n if (err.code === codes.ERR_NO_ROUTERS_AVAILABLE) {\n log.error('a content router, such as a DHT, must be provided in order to advertise the relay service', err)\n // Stop the advertise\n await this.stop()\n } else {\n log.error(err)\n }\n }\n }\n}\n","import 'node-forge/lib/x509.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\n\nconst pki = forge.pki\n\n/**\n * Gets a self-signed X.509 certificate for the key.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n *\n * TODO: move to libp2p-crypto package\n */\nexport const certificateForKey = (key: any, privateKey: forge.pki.rsa.PrivateKey) => {\n const publicKey = pki.rsa.setPublicKey(privateKey.n, privateKey.e)\n const cert = pki.createCertificate()\n cert.publicKey = publicKey\n cert.serialNumber = '01'\n cert.validity.notBefore = new Date()\n cert.validity.notAfter = new Date()\n cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10) // eslint-disable-line @typescript-eslint/restrict-plus-operands\n const attrs = [{\n name: 'organizationName',\n value: 'ipfs'\n }, {\n shortName: 'OU',\n value: 'keystore'\n }, {\n name: 'commonName',\n value: key.id\n }]\n cert.setSubject(attrs)\n cert.setIssuer(attrs)\n cert.setExtensions([{\n name: 'basicConstraints',\n cA: true\n }, {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n }, {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n emailProtection: true,\n timeStamping: true\n }, {\n name: 'nsCertType',\n client: true,\n server: true,\n email: true,\n objsign: true,\n sslCA: true,\n emailCA: true,\n objCA: true\n }])\n // self-sign certificate\n cert.sign(privateKey)\n\n return cert\n}\n\n/**\n * Finds the first item in a collection that is matched in the\n * `asyncCompare` function.\n *\n * `asyncCompare` is an async function that must\n * resolve to either `true` or `false`.\n *\n * @param {Array} array\n * @param {function(*)} asyncCompare - An async function that returns a boolean\n */\nexport async function findAsync (array: T[], asyncCompare: (val: T) => Promise) {\n const promises = array.map(asyncCompare)\n const results = await Promise.all(promises)\n const index = results.findIndex(result => result)\n return array[index]\n}\n","import 'node-forge/lib/pkcs7.js'\nimport 'node-forge/lib/pbe.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { certificateForKey, findAsync } from './util.js'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { codes } from '../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { KeyChain } from './index.js'\n\nconst log = logger('libp2p:keychain:cms')\n\nconst privates = new WeakMap()\n\n/**\n * Cryptographic Message Syntax (aka PKCS #7)\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content.\n *\n * See RFC 5652 for all the details.\n */\nexport class CMS {\n private readonly keychain: KeyChain\n\n /**\n * Creates a new instance with a keychain\n */\n constructor (keychain: KeyChain, dek: string) {\n if (keychain == null) {\n throw errCode(new Error('keychain is required'), codes.ERR_KEYCHAIN_REQUIRED)\n }\n\n this.keychain = keychain\n privates.set(this, { dek })\n }\n\n /**\n * Creates some protected data.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n */\n async encrypt (name: string, plain: Uint8Array): Promise {\n if (!(plain instanceof Uint8Array)) {\n throw errCode(new Error('Plain data must be a Uint8Array'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const key = await this.keychain.findKeyByName(name)\n const pem = await this.keychain.getPrivateKey(name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n const certificate = await certificateForKey(key, privateKey)\n\n // create a p7 enveloped message\n const p7 = forge.pkcs7.createEnvelopedData()\n p7.addRecipient(certificate)\n p7.content = forge.util.createBuffer(plain)\n p7.encrypt()\n\n // convert message to DER\n const der = forge.asn1.toDer(p7.toAsn1()).getBytes()\n return uint8ArrayFromString(der, 'ascii')\n }\n\n /**\n * Reads some protected data.\n *\n * The keychain must contain one of the keys used to encrypt the data. If none of the keys\n * exists, an Error is returned with the property 'missingKeys'. It is array of key ids.\n */\n async decrypt (cmsData: Uint8Array): Promise {\n if (!(cmsData instanceof Uint8Array)) {\n throw errCode(new Error('CMS data is required'), codes.ERR_INVALID_PARAMETERS)\n }\n\n let cms: any\n try {\n const buf = forge.util.createBuffer(uint8ArrayToString(cmsData, 'ascii'))\n const obj = forge.asn1.fromDer(buf)\n\n cms = forge.pkcs7.messageFromAsn1(obj)\n } catch (err: any) {\n log.error(err)\n throw errCode(new Error('Invalid CMS'), codes.ERR_INVALID_CMS)\n }\n\n // Find a recipient whose key we hold. We only deal with recipient certs\n // issued by ipfs (O=ipfs).\n const recipients: any = cms.recipients\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'O' && a.value === 'ipfs'))\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'CN'))\n // @ts-expect-error cms types not defined\n .map(r => {\n return {\n recipient: r,\n // @ts-expect-error cms types not defined\n keyId: r.issuer.find(a => a.shortName === 'CN').value\n }\n })\n\n const r = await findAsync(recipients, async (recipient: any) => {\n try {\n const key = await this.keychain.findKeyById(recipient.keyId)\n if (key != null) {\n return true\n }\n } catch (err: any) {\n return false\n }\n return false\n })\n\n if (r == null) {\n // @ts-expect-error cms types not defined\n const missingKeys: string[] = recipients.map(r => r.keyId)\n throw errCode(new Error(`Decryption needs one of the key(s): ${missingKeys.join(', ')}`), codes.ERR_MISSING_KEYS, {\n missingKeys\n })\n }\n\n const key = await this.keychain.findKeyById(r.keyId)\n\n if (key == null) {\n throw errCode(new Error('No key available to decrypto'), codes.ERR_NO_KEY)\n }\n\n const pem = await this.keychain.getPrivateKey(key.name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n cms.decrypt(r.recipient, privateKey)\n return uint8ArrayFromString(cms.content.getBytes(), 'ascii')\n }\n}\n","/* eslint max-nested-callbacks: [\"error\", 5] */\n\nimport { logger } from '@libp2p/logger'\nimport sanitize from 'sanitize-filename'\nimport mergeOptions from 'merge-options'\nimport { Key } from 'interface-datastore/key'\nimport { CMS } from './cms.js'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Components } from '@libp2p/components'\nimport { pbkdf2, randomBytes } from '@libp2p/crypto'\nimport type { Startable } from '@libp2p/interfaces/dist/src/startable'\n\nconst log = logger('libp2p:keychain')\n\nexport interface DekOptions {\n hash: string\n salt: string\n iterationCount: number\n keyLength: number\n}\n\nexport interface KeyChainInit {\n pass?: string\n dek?: DekOptions\n}\n\n/**\n * Information about a key.\n */\nexport interface KeyInfo {\n /**\n * The universally unique key id\n */\n id: string\n\n /**\n * The local key name.\n */\n name: string\n}\n\nconst keyPrefix = '/pkcs8/'\nconst infoPrefix = '/info/'\nconst privates = new WeakMap()\n\n// NIST SP 800-132\nconst NIST = {\n minKeyLength: 112 / 8,\n minSaltLength: 128 / 8,\n minIterationCount: 1000\n}\n\nconst defaultOptions = {\n // See https://cryptosense.com/parametesr-choice-for-pbkdf2/\n dek: {\n keyLength: 512 / 8,\n iterationCount: 10000,\n salt: 'you should override this value with a crypto secure random number',\n hash: 'sha2-512'\n }\n}\n\nfunction validateKeyName (name: string) {\n if (name == null) {\n return false\n }\n if (typeof name !== 'string') {\n return false\n }\n return name === sanitize(name.trim()) && name.length > 0\n}\n\n/**\n * Throws an error after a delay\n *\n * This assumes than an error indicates that the keychain is under attack. Delay returning an\n * error to make brute force attacks harder.\n */\nasync function randomDelay () {\n const min = 200\n const max = 1000\n const delay = Math.random() * (max - min) + min\n\n await new Promise(resolve => setTimeout(resolve, delay))\n}\n\n/**\n * Converts a key name into a datastore name\n */\nfunction DsName (name: string) {\n return new Key(keyPrefix + name)\n}\n\n/**\n * Converts a key name into a datastore info name\n */\nfunction DsInfoName (name: string) {\n return new Key(infoPrefix + name)\n}\n\n/**\n * Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.\n *\n * A key in the store has two entries\n * - '/info/*key-name*', contains the KeyInfo for the key\n * - '/pkcs8/*key-name*', contains the PKCS #8 for the key\n *\n */\nexport class KeyChain implements Startable {\n private readonly components: Components\n private init: KeyChainInit\n private started: boolean\n\n /**\n * Creates a new instance of a key chain\n */\n constructor (components: Components, init: KeyChainInit) {\n this.components = components\n this.init = mergeOptions(defaultOptions, init)\n\n // Enforce NIST SP 800-132\n if (this.init.pass != null && this.init.pass?.length < 20) {\n throw new Error('pass must be least 20 characters')\n }\n if (this.init.dek?.keyLength != null && this.init.dek.keyLength < NIST.minKeyLength) {\n throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)\n }\n if (this.init.dek?.salt?.length != null && this.init.dek.salt.length < NIST.minSaltLength) {\n throw new Error(`dek.saltLength must be least ${NIST.minSaltLength} bytes`)\n }\n if (this.init.dek?.iterationCount != null && this.init.dek.iterationCount < NIST.minIterationCount) {\n throw new Error(`dek.iterationCount must be least ${NIST.minIterationCount}`)\n }\n\n const dek = this.init.pass != null && this.init.dek?.salt != null\n ? pbkdf2(\n this.init.pass,\n this.init.dek?.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n\n privates.set(this, { dek })\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n const dsname = DsInfoName('self')\n\n if (!(await this.components.getDatastore().has(dsname))) {\n await this.importPeer('self', this.components.getPeerId())\n }\n\n this.started = true\n }\n\n stop () {\n this.started = false\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data\n * using the Cryptographic Message Syntax (CMS).\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content\n */\n get cms () {\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n\n return new CMS(this, dek)\n }\n\n /**\n * Generates the options for a keychain. A random salt is produced.\n *\n * @returns {object}\n */\n static generateOptions (): KeyChainInit {\n const options = Object.assign({}, defaultOptions)\n const saltLength = Math.ceil(NIST.minSaltLength / 3) * 3 // no base64 padding\n options.dek.salt = uint8ArrayToString(randomBytes(saltLength), 'base64')\n return options\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data.\n * The default options for a keychain.\n *\n * @returns {object}\n */\n static get options () {\n return defaultOptions\n }\n\n /**\n * Create a new key.\n *\n * @param {string} name - The local key name; cannot already exist.\n * @param {string} type - One of the key types; 'rsa'.\n * @param {number} [size = 2048] - The key size in bits. Used for rsa keys only\n */\n async createKey (name: string, type: 'RSA' | 'Ed25519', size = 2048): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error('Invalid key name'), codes.ERR_INVALID_KEY_NAME)\n }\n\n if (typeof type !== 'string') {\n await randomDelay()\n throw errCode(new Error('Invalid key type'), codes.ERR_INVALID_KEY_TYPE)\n }\n\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error('Key name already exists'), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n switch (type.toLowerCase()) {\n case 'rsa':\n if (!Number.isSafeInteger(size) || size < 2048) {\n await randomDelay()\n throw errCode(new Error('Invalid RSA key size'), codes.ERR_INVALID_KEY_SIZE)\n }\n break\n default:\n break\n }\n\n let keyInfo\n try {\n const keypair = await generateKeyPair(type, size)\n const kid = await keypair.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await keypair.export(dek)\n keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n\n await batch.commit()\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n return keyInfo\n }\n\n /**\n * List all the keys.\n *\n * @returns {Promise}\n */\n async listKeys () {\n const query = {\n prefix: infoPrefix\n }\n\n const info = []\n for await (const value of this.components.getDatastore().query(query)) {\n info.push(JSON.parse(uint8ArrayToString(value.value)))\n }\n\n return info\n }\n\n /**\n * Find a key by it's id\n */\n async findKeyById (id: string): Promise {\n try {\n const keys = await this.listKeys()\n return keys.find((k) => k.id === id)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Find a key by it's name.\n *\n * @param {string} name - The local key name.\n * @returns {Promise}\n */\n async findKeyByName (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n const dsname = DsInfoName(name)\n try {\n const res = await this.components.getDatastore().get(dsname)\n return JSON.parse(uint8ArrayToString(res))\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Remove an existing key.\n *\n * @param {string} name - The local key name; must already exist.\n * @returns {Promise}\n */\n async removeKey (name: string) {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n const dsname = DsName(name)\n const keyInfo = await this.findKeyByName(name)\n const batch = this.components.getDatastore().batch()\n batch.delete(dsname)\n batch.delete(DsInfoName(name))\n await batch.commit()\n return keyInfo\n }\n\n /**\n * Rename a key\n *\n * @param {string} oldName - The old local key name; must already exist.\n * @param {string} newName - The new local key name; must not already exist.\n * @returns {Promise}\n */\n async renameKey (oldName: string, newName: string): Promise {\n if (!validateKeyName(oldName) || oldName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid old key name '${oldName}'`), codes.ERR_OLD_KEY_NAME_INVALID)\n }\n if (!validateKeyName(newName) || newName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid new key name '${newName}'`), codes.ERR_NEW_KEY_NAME_INVALID)\n }\n const oldDsname = DsName(oldName)\n const newDsname = DsName(newName)\n const oldInfoName = DsInfoName(oldName)\n const newInfoName = DsInfoName(newName)\n\n const exists = await this.components.getDatastore().has(newDsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${newName}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n try {\n const pem = await this.components.getDatastore().get(oldDsname)\n const res = await this.components.getDatastore().get(oldInfoName)\n\n const keyInfo = JSON.parse(uint8ArrayToString(res))\n keyInfo.name = newName\n const batch = this.components.getDatastore().batch()\n batch.put(newDsname, pem)\n batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))\n batch.delete(oldDsname)\n batch.delete(oldInfoName)\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Export an existing key as a PEM encrypted PKCS #8 string\n */\n async exportKey (name: string, password: string) {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (password == null) {\n await randomDelay()\n throw errCode(new Error('Password is required'), codes.ERR_PASSWORD_REQUIRED)\n }\n\n const dsname = DsName(name)\n try {\n const res = await this.components.getDatastore().get(dsname)\n const pem = uint8ArrayToString(res)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = await importKey(pem, dek)\n return await privateKey.export(password)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Import a new key from a PEM encoded PKCS #8 string\n *\n * @param {string} name - The local key name; must not already exist.\n * @param {string} pem - The PEM encoded PKCS #8 string\n * @param {string} password - The password.\n * @returns {Promise}\n */\n async importKey (name: string, pem: string, password: string): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (pem == null) {\n await randomDelay()\n throw errCode(new Error('PEM encoded key is required'), codes.ERR_PEM_REQUIRED)\n }\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n let privateKey\n try {\n privateKey = await importKey(pem, password)\n } catch (err: any) {\n await randomDelay()\n throw errCode(new Error('Cannot read the key, most likely the password is wrong'), codes.ERR_CANNOT_READ_KEY)\n }\n\n let kid\n try {\n kid = await privateKey.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n pem = await privateKey.export(dek)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n const keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n\n return keyInfo\n }\n\n /**\n * Import a peer key\n */\n async importPeer (name: string, peer: PeerId): Promise {\n try {\n if (!validateKeyName(name)) {\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (peer == null) {\n throw errCode(new Error('PeerId is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n if (peer.privateKey == null) {\n throw errCode(new Error('PeerId.privKey is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n\n const privateKey = await unmarshalPrivateKey(peer.privateKey)\n\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await privateKey.export(dek)\n const keyInfo: KeyInfo = {\n name: name,\n id: peer.toString()\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Gets the private key as PEM encoded PKCS #8 string\n */\n async getPrivateKey (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n try {\n const dsname = DsName(name)\n const res = await this.components.getDatastore().get(dsname)\n return uint8ArrayToString(res)\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Rotate keychain password and re-encrypt all associated keys\n */\n async rotateKeychainPass (oldPass: string, newPass: string) {\n if (typeof oldPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid old pass type '${typeof oldPass}'`), codes.ERR_INVALID_OLD_PASS_TYPE)\n }\n if (typeof newPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid new pass type '${typeof newPass}'`), codes.ERR_INVALID_NEW_PASS_TYPE)\n }\n if (newPass.length < 20) {\n await randomDelay()\n throw errCode(new Error(`Invalid pass length ${newPass.length}`), codes.ERR_INVALID_PASS_LENGTH)\n }\n log('recreating keychain')\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const oldDek = cached.dek\n this.init.pass = newPass\n const newDek = newPass != null && this.init.dek?.salt != null\n ? pbkdf2(\n newPass,\n this.init.dek.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n privates.set(this, { dek: newDek })\n const keys = await this.listKeys()\n for (const key of keys) {\n const res = await this.components.getDatastore().get(DsName(key.name))\n const pem = uint8ArrayToString(res)\n const privateKey = await importKey(pem, oldDek)\n const password = newDek.toString()\n const keyAsPEM = await privateKey.export(password)\n\n // Update stored key\n const batch = this.components.getDatastore().batch()\n const keyInfo = {\n name: key.name,\n id: key.id\n }\n batch.put(DsName(key.name), uint8ArrayFromString(keyAsPEM))\n batch.put(DsInfoName(key.name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n }\n log('keychain reconstructed')\n }\n}\n","import type { MovingAverage } from '@libp2p/interface-metrics'\n\nexport class DefaultMovingAverage {\n public movingAverage: number\n public variance: number\n public deviation: number\n public forecast: number\n private readonly timespan: number\n private previousTime?: number\n\n constructor (timespan: number) {\n if (typeof timespan !== 'number') {\n throw new Error('must provide a timespan to the moving average constructor')\n }\n\n if (timespan <= 0) {\n throw new Error('must provide a timespan > 0 to the moving average constructor')\n }\n\n this.timespan = timespan\n this.movingAverage = 0\n this.variance = 0\n this.deviation = 0\n this.forecast = 0\n }\n\n alpha (t: number, pt: number) {\n return 1 - (Math.exp(-(t - pt) / this.timespan))\n }\n\n push (time: number, value: number) {\n if (this.previousTime != null) {\n // calculate moving average\n const a = this.alpha(time, this.previousTime)\n const diff = value - this.movingAverage\n const incr = a * diff\n this.movingAverage = a * value + (1 - a) * this.movingAverage\n // calculate variance & deviation\n this.variance = (1 - a) * (this.variance + diff * incr)\n this.deviation = Math.sqrt(this.variance)\n // calculate forecast\n this.forecast = this.movingAverage + a * diff\n } else {\n this.movingAverage = value\n }\n\n this.previousTime = time\n }\n}\n\nexport function createMovingAverage (timespan: number): MovingAverage {\n return new DefaultMovingAverage(timespan)\n}\n","import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { createMovingAverage } from './moving-average.js'\n// @ts-expect-error no types\nimport retimer from 'retimer'\nimport type { MovingAverages, Stats, TransferStats } from '@libp2p/interface-metrics'\n\nexport interface StatsEvents {\n 'update': CustomEvent\n}\n\nexport interface StatsInit {\n enabled: boolean\n initialCounters: ['dataReceived', 'dataSent']\n movingAverageIntervals: number[]\n computeThrottleMaxQueueSize: number\n computeThrottleTimeout: number\n}\n\nexport class DefaultStats extends EventEmitter implements Stats {\n private readonly enabled: boolean\n public queue: Array<[string, number, number]>\n private stats: TransferStats\n private frequencyLastTime: number\n private frequencyAccumulators: Record\n private movingAverages: MovingAverages\n private timeout?: any\n private readonly computeThrottleMaxQueueSize: number\n private readonly computeThrottleTimeout: number\n private readonly movingAverageIntervals: number[]\n\n /**\n * A queue based manager for stat processing\n */\n constructor (init: StatsInit) {\n super()\n\n this.enabled = init.enabled\n this.queue = []\n this.stats = {\n dataReceived: 0n,\n dataSent: 0n\n }\n this.frequencyLastTime = Date.now()\n this.frequencyAccumulators = {}\n this.movingAverages = {\n dataReceived: [],\n dataSent: []\n }\n this.computeThrottleMaxQueueSize = init.computeThrottleMaxQueueSize\n this.computeThrottleTimeout = init.computeThrottleTimeout\n\n this._update = this._update.bind(this)\n\n this.movingAverageIntervals = init.movingAverageIntervals\n\n for (let i = 0; i < init.initialCounters.length; i++) {\n const key = init.initialCounters[i]\n this.stats[key] = 0n\n this.movingAverages[key] = []\n\n for (let k = 0; k < this.movingAverageIntervals.length; k++) {\n const interval = this.movingAverageIntervals[k]\n const ma = this.movingAverages[key][interval] = createMovingAverage(interval)\n ma.push(this.frequencyLastTime, 0)\n }\n }\n }\n\n /**\n * Initializes the internal timer if there are items in the queue. This\n * should only need to be called if `Stats.stop` was previously called, as\n * `Stats.push` will also start the processing\n */\n start () {\n if (!this.enabled) {\n return\n }\n\n if (this.queue.length > 0) {\n this._resetComputeTimeout()\n }\n }\n\n /**\n * Stops processing and computing of stats by clearing the internal\n * timer\n */\n stop () {\n if (this.timeout != null) {\n this.timeout.clear()\n this.timeout = null\n }\n }\n\n /**\n * Returns a clone of the current stats.\n */\n getSnapshot () {\n return Object.assign({}, this.stats)\n }\n\n /**\n * Returns a clone of the internal movingAverages\n */\n getMovingAverages (): MovingAverages {\n return Object.assign({}, this.movingAverages)\n }\n\n /**\n * Pushes the given operation data to the queue, along with the\n * current Timestamp, then resets the update timer.\n */\n push (counter: string, inc: number) {\n this.queue.push([counter, inc, Date.now()])\n this._resetComputeTimeout()\n }\n\n /**\n * Resets the timeout for triggering updates.\n */\n _resetComputeTimeout () {\n this.timeout = retimer(this._update, this._nextTimeout())\n }\n\n /**\n * Calculates and returns the timeout for the next update based on\n * the urgency of the update.\n */\n _nextTimeout () {\n // calculate the need for an update, depending on the queue length\n const urgency = this.queue.length / this.computeThrottleMaxQueueSize\n const timeout = Math.max(this.computeThrottleTimeout * (1 - urgency), 0)\n return timeout\n }\n\n /**\n * If there are items in the queue, they will will be processed and\n * the frequency for all items will be updated based on the Timestamp\n * of the last item in the queue. The `update` event will also be emitted\n * with the latest stats.\n *\n * If there are no items in the queue, no action is taken.\n */\n _update () {\n this.timeout = null\n if (this.queue.length > 0) {\n let last: [string, number, number] = ['', 0, 0]\n\n for (last of this.queue) {\n this._applyOp(last)\n }\n\n this.queue = []\n\n if (last.length > 2 && last[0] !== '') {\n this._updateFrequency(last[2]) // contains timestamp of last op\n }\n\n this.dispatchEvent(new CustomEvent('update', {\n detail: this.stats\n }))\n }\n }\n\n /**\n * For each key in the stats, the frequency and moving averages\n * will be updated via Stats._updateFrequencyFor based on the time\n * difference between calls to this method.\n */\n _updateFrequency (latestTime: number) {\n const timeDiff = latestTime - this.frequencyLastTime\n\n this._updateFrequencyFor('dataReceived', timeDiff, latestTime)\n this._updateFrequencyFor('dataSent', timeDiff, latestTime)\n\n this.frequencyLastTime = latestTime\n }\n\n /**\n * Updates the `movingAverages` for the given `key` and also\n * resets the `frequencyAccumulator` for the `key`.\n */\n _updateFrequencyFor (key: 'dataReceived' | 'dataSent', timeDiffMS: number, latestTime: number) {\n const count = this.frequencyAccumulators[key] ?? 0\n this.frequencyAccumulators[key] = 0\n // if `timeDiff` is zero, `hz` becomes Infinity, so we fallback to 1ms\n const safeTimeDiff = timeDiffMS ?? 1\n const hz = (count / safeTimeDiff) * 1000\n\n let movingAverages = this.movingAverages[key]\n if (movingAverages == null) {\n movingAverages = this.movingAverages[key] = []\n }\n\n const intervals = this.movingAverageIntervals\n\n for (let i = 0; i < intervals.length; i++) {\n const movingAverageInterval = intervals[i]\n let movingAverage = movingAverages[movingAverageInterval]\n if (movingAverage == null) {\n movingAverage = movingAverages[movingAverageInterval] = createMovingAverage(movingAverageInterval)\n }\n movingAverage.push(latestTime, hz)\n }\n }\n\n /**\n * For the given operation, `op`, the stats and `frequencyAccumulator`\n * will be updated or initialized if they don't already exist.\n */\n _applyOp (op: [string, number, number]) {\n const key = op[0]\n const inc = op[1]\n\n if (typeof inc !== 'number') {\n throw new Error('invalid increment number')\n }\n\n let n: bigint\n\n if (!Object.prototype.hasOwnProperty.call(this.stats, key)) {\n // @ts-expect-error cannot index type with key\n n = this.stats[key] = 0n\n } else {\n // @ts-expect-error cannot index type with key\n n = this.stats[key]\n }\n\n // @ts-expect-error cannot index type with key\n this.stats[key] = n + BigInt(inc)\n\n if (this.frequencyAccumulators[key] == null) {\n this.frequencyAccumulators[key] = 0\n }\n\n this.frequencyAccumulators[key] += inc\n }\n}\n","import { pipe } from 'it-pipe'\nimport each from 'it-foreach'\nimport LRU from 'hashlru'\nimport { METRICS as defaultOptions } from '../constants.js'\nimport { DefaultStats, StatsInit } from './stats.js'\nimport type { ComponentMetricsUpdate, Metrics, Stats, TrackedMetric, TrackStreamOptions } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\n\nconst initialCounters: ['dataReceived', 'dataSent'] = [\n 'dataReceived',\n 'dataSent'\n]\n\nconst directionToEvent = {\n in: 'dataReceived',\n out: 'dataSent'\n}\n\nexport interface OnMessageOptions {\n remotePeer: PeerId\n protocol?: string\n direction: 'in' | 'out'\n dataLength: number\n}\n\nexport interface MetricsInit {\n enabled: boolean\n computeThrottleMaxQueueSize: number\n computeThrottleTimeout: number\n movingAverageIntervals: number[]\n maxOldPeersRetention: number\n}\n\nexport class DefaultMetrics implements Metrics, Startable {\n public globalStats: DefaultStats\n\n private readonly enabled: boolean\n private readonly peerStats: Map\n private readonly protocolStats: Map\n private readonly oldPeers: ReturnType\n private running: boolean\n private readonly systems: Map>>\n private readonly statsInit: StatsInit\n\n constructor (init: MetricsInit) {\n this.enabled = init.enabled\n this.statsInit = {\n ...init,\n initialCounters\n }\n this.globalStats = new DefaultStats(this.statsInit)\n this.peerStats = new Map()\n this.protocolStats = new Map()\n this.oldPeers = LRU(init.maxOldPeersRetention ?? defaultOptions.maxOldPeersRetention)\n this.running = false\n this._onMessage = this._onMessage.bind(this)\n this.systems = new Map()\n }\n\n isStarted () {\n return this.running\n }\n\n /**\n * Must be called for stats to saved. Any data pushed for tracking\n * will be ignored.\n */\n async start () {\n if (!this.enabled) {\n return\n }\n\n this.running = true\n }\n\n /**\n * Stops all averages timers and prevents new data from being tracked.\n * Once `stop` is called, `start` must be called to resume stats tracking.\n */\n async stop () {\n if (!this.running) {\n return\n }\n\n this.running = false\n this.globalStats.stop()\n\n for (const stats of this.peerStats.values()) {\n stats.stop()\n }\n\n for (const stats of this.protocolStats.values()) {\n stats.stop()\n }\n }\n\n /**\n * Gets the global `Stats` object\n */\n getGlobal () {\n return this.globalStats\n }\n\n /**\n * Returns a list of `PeerId` strings currently being tracked\n */\n getPeers () {\n return Array.from(this.peerStats.keys())\n }\n\n getComponentMetrics () {\n return this.systems\n }\n\n updateComponentMetric (update: ComponentMetricsUpdate) {\n const { system = 'libp2p', component, metric, value, label, help } = update\n\n if (!this.systems.has(system)) {\n this.systems.set(system, new Map())\n }\n\n const systemMetrics = this.systems.get(system)\n\n if (systemMetrics == null) {\n throw new Error('Unknown metric system')\n }\n\n if (!systemMetrics.has(component)) {\n systemMetrics.set(component, new Map())\n }\n\n const componentMetrics = systemMetrics.get(component)\n\n if (componentMetrics == null) {\n throw new Error('Unknown metric component')\n }\n\n componentMetrics.set(metric, {\n label,\n help,\n calculate: typeof value !== 'function' ? () => value : value\n })\n }\n\n /**\n * Returns the `Stats` object for the given `PeerId` whether it\n * is a live peer, or in the disconnected peer LRU cache.\n */\n forPeer (peerId: PeerId): Stats | undefined {\n const idString = peerId.toString()\n return this.peerStats.get(idString) ?? this.oldPeers.get(idString)\n }\n\n /**\n * Returns a list of all protocol strings currently being tracked\n */\n getProtocols (): string[] {\n return Array.from(this.protocolStats.keys())\n }\n\n /**\n * Returns the `Stats` object for the given `protocol`\n */\n forProtocol (protocol: string): Stats | undefined {\n return this.protocolStats.get(protocol)\n }\n\n /**\n * Should be called when all connections to a given peer\n * have closed. The `Stats` collection for the peer will\n * be stopped and moved to an LRU for temporary retention.\n */\n onPeerDisconnected (peerId: PeerId) {\n const idString = peerId.toString()\n const peerStats = this.peerStats.get(idString)\n\n if (peerStats != null) {\n peerStats.stop()\n\n this.peerStats.delete(idString)\n this.oldPeers.set(idString, peerStats)\n }\n }\n\n /**\n * Takes the metadata for a message and tracks it in the\n * appropriate categories. If the protocol is present, protocol\n * stats will also be tracked.\n */\n _onMessage (opts: OnMessageOptions) {\n if (!this.running) {\n return\n }\n\n const { remotePeer, protocol, direction, dataLength } = opts\n\n const key = directionToEvent[direction]\n\n let peerStats = this.forPeer(remotePeer)\n if (peerStats == null) {\n const stats = new DefaultStats(this.statsInit)\n this.peerStats.set(remotePeer.toString(), stats)\n peerStats = stats\n }\n\n // Peer and global stats\n peerStats.push(key, dataLength)\n this.globalStats.push(key, dataLength)\n\n // Protocol specific stats\n if (protocol != null) {\n let protocolStats = this.forProtocol(protocol)\n\n if (protocolStats == null) {\n const stats = new DefaultStats(this.statsInit)\n this.protocolStats.set(protocol, stats)\n protocolStats = stats\n }\n\n protocolStats.push(key, dataLength)\n }\n }\n\n /**\n * Replaces the `PeerId` string with the given `peerId`.\n * If stats are already being tracked for the given `peerId`, the\n * placeholder stats will be merged with the existing stats.\n *\n * @param {PeerId} placeholder - A peerId string\n * @param {PeerId} peerId\n * @returns {void}\n */\n updatePlaceholder (placeholder: PeerId, peerId: PeerId) {\n if (!this.running) {\n return\n }\n\n const placeholderString = placeholder.toString()\n const placeholderStats = this.peerStats.get(placeholderString) ?? this.oldPeers.get(placeholderString)\n const peerIdString = peerId.toString()\n const existingStats = this.peerStats.get(peerIdString) ?? this.oldPeers.get(peerIdString)\n let mergedStats = placeholderStats\n\n // If we already have stats, merge the two\n if (existingStats != null) {\n // If existing, merge\n mergedStats = mergeStats(existingStats, mergedStats)\n // Attempt to delete from the old peers list just in case it was tracked there\n this.oldPeers.remove(peerIdString)\n }\n\n this.peerStats.delete(placeholder.toString())\n this.peerStats.set(peerIdString, mergedStats)\n mergedStats.start()\n }\n\n /**\n * Tracks data running through a given Duplex Iterable `stream`. If\n * the `peerId` is not provided, a placeholder string will be created and\n * returned. This allows lazy tracking of a peer when the peer is not yet known.\n * When the `PeerId` is known, `Metrics.updatePlaceholder` should be called\n * with the placeholder string returned from here, and the known `PeerId`.\n */\n trackStream (opts: TrackStreamOptions): void {\n const { stream, remotePeer, protocol } = opts\n\n if (!this.running) {\n return\n }\n\n const source = stream.source\n stream.source = each(source, chunk => this._onMessage({\n remotePeer,\n protocol,\n direction: 'in',\n dataLength: chunk.byteLength\n }))\n\n const sink = stream.sink\n stream.sink = async source => {\n return await pipe(\n source,\n (source) => each(source, chunk => {\n this._onMessage({\n remotePeer,\n protocol,\n direction: 'out',\n dataLength: chunk.byteLength\n })\n }),\n sink\n )\n }\n }\n}\n\n/**\n * Merges `other` into `target`. `target` will be modified\n * and returned\n */\nfunction mergeStats (target: DefaultStats, other: DefaultStats) {\n target.stop()\n other.stop()\n\n // Merge queues\n target.queue = [...target.queue, ...other.queue]\n\n // TODO: how to merge moving averages?\n return target\n}\n","export default async function pReflect(promise) {\n\ttry {\n\t\tconst value = await promise;\n\n\t\treturn {\n\t\t\tstatus: 'fulfilled',\n\t\t\tvalue,\n\t\t\tisFulfilled: true,\n\t\t\tisRejected: false\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tstatus: 'rejected',\n\t\t\treason: error,\n\t\t\tisFulfilled: false,\n\t\t\tisRejected: true\n\t\t};\n\t}\n}\n\nexport function isFulfilled(promiseResult) {\n\treturn 'value' in promiseResult;\n}\n\nexport function isRejected(promiseResult) {\n\treturn 'reason' in promiseResult;\n}\n","import checkPrivateRedeclaration from \"./checkPrivateRedeclaration.js\";\nexport default function _classPrivateFieldInitSpec(obj, privateMap, value) {\n checkPrivateRedeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}","export default function _checkPrivateRedeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}","export default function _classExtractFieldDescriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n\n return privateMap.get(receiver);\n}","import classApplyDescriptorSet from \"./classApplyDescriptorSet.js\";\nimport classExtractFieldDescriptor from \"./classExtractFieldDescriptor.js\";\nexport default function _classPrivateFieldSet(receiver, privateMap, value) {\n var descriptor = classExtractFieldDescriptor(receiver, privateMap, \"set\");\n classApplyDescriptorSet(receiver, descriptor, value);\n return value;\n}","export default function _classApplyDescriptorSet(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n\n descriptor.value = value;\n }\n}","import classApplyDescriptorGet from \"./classApplyDescriptorGet.js\";\nimport classExtractFieldDescriptor from \"./classExtractFieldDescriptor.js\";\nexport default function _classPrivateFieldGet(receiver, privateMap) {\n var descriptor = classExtractFieldDescriptor(receiver, privateMap, \"get\");\n return classApplyDescriptorGet(receiver, descriptor);\n}","export default function _classApplyDescriptorGet(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n\n return descriptor.value;\n}","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\t\treturn current.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n}\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tif (queue.size > 0) {\n\t\t\tqueue.dequeue()();\n\t\t}\n\t};\n\n\tconst run = async (fn, resolve, args) => {\n\t\tactiveCount++;\n\n\t\tconst result = (async () => fn(...args))();\n\n\t\tresolve(result);\n\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\tnext();\n\t};\n\n\tconst enqueue = (fn, resolve, args) => {\n\t\tqueue.enqueue(run.bind(undefined, fn, resolve, args));\n\n\t\t(async () => {\n\t\t\t// This function needs to wait until the next microtask before comparing\n\t\t\t// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously\n\t\t\t// when the run function is dequeued and called. The comparison in the if-statement\n\t\t\t// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.\n\t\t\tawait Promise.resolve();\n\n\t\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\t\tqueue.dequeue()();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst generator = (fn, ...args) => new Promise(resolve => {\n\t\tenqueue(fn, resolve, args);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue: () => {\n\t\t\t\tqueue.clear();\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n","import pReflect from 'p-reflect';\nimport pLimit from 'p-limit';\n\nexport default async function pSettle(array, options = {}) {\n\tconst {concurrency = Number.POSITIVE_INFINITY} = options;\n\tconst limit = pLimit(concurrency);\n\n\treturn Promise.all(array.map(element => {\n\t\tif (element && typeof element.then === 'function') {\n\t\t\treturn pReflect(element);\n\t\t}\n\n\t\tif (typeof element === 'function') {\n\t\t\treturn pReflect(limit(() => element()));\n\t\t}\n\n\t\treturn pReflect(Promise.resolve(element));\n\t}));\n}\n","import { logger } from '@libp2p/logger'\nimport pSettle from 'p-settle'\nimport { codes } from './errors.js'\nimport errCode from 'err-code'\nimport type { Listener, Transport, TransportManager, TransportManagerEvents } from '@libp2p/interface-transport'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport { trackedMap } from '@libp2p/tracked-map'\n\nconst log = logger('libp2p:transports')\n\nexport interface TransportManagerInit {\n faultTolerance?: FaultTolerance\n}\n\nexport class DefaultTransportManager extends EventEmitter implements TransportManager, Startable {\n private readonly components: Components\n private readonly transports: Map\n private readonly listeners: Map\n private readonly faultTolerance: FaultTolerance\n private started: boolean\n\n constructor (components: Components, init: TransportManagerInit = {}) {\n super()\n\n this.components = components\n this.started = false\n this.transports = new Map()\n this.listeners = trackedMap({\n component: 'transport-manager',\n metric: 'listeners',\n metrics: this.components.getMetrics()\n })\n this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL\n }\n\n /**\n * Adds a `Transport` to the manager\n */\n add (transport: Transport) {\n const tag = transport[Symbol.toStringTag]\n\n if (tag == null) {\n throw errCode(new Error('Transport must have a valid tag'), codes.ERR_INVALID_KEY)\n }\n\n if (this.transports.has(tag)) {\n throw errCode(new Error('There is already a transport with this tag'), codes.ERR_DUPLICATE_TRANSPORT)\n }\n\n log('adding transport %s', tag)\n\n this.transports.set(tag, transport)\n\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, [])\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.getAddressManager().getListenAddrs()\n\n await this.listen(addrs)\n\n this.started = true\n }\n\n /**\n * Stops all listeners\n */\n async stop () {\n const tasks = []\n for (const [key, listeners] of this.listeners) {\n log('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n }\n\n await Promise.all(tasks)\n log('all listeners closed')\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, [])\n }\n\n this.started = false\n }\n\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial (ma: Multiaddr, options?: AbortOptions): Promise {\n const transport = this.transportForMultiaddr(ma)\n\n if (transport == null) {\n throw errCode(new Error(`No transport available for address ${String(ma)}`), codes.ERR_TRANSPORT_UNAVAILABLE)\n }\n\n try {\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.getUpgrader()\n })\n } catch (err: any) {\n if (err.code == null) {\n err.code = codes.ERR_TRANSPORT_DIAL_FAILED\n }\n\n throw err\n }\n }\n\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs (): Multiaddr[] {\n let addrs: Multiaddr[] = []\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()]\n }\n }\n return addrs\n }\n\n /**\n * Returns all the transports instances\n */\n getTransports () {\n return Array.of(...this.transports.values())\n }\n\n /**\n * Finds a transport that matches the given Multiaddr\n */\n transportForMultiaddr (ma: Multiaddr) {\n for (const transport of this.transports.values()) {\n const addrs = transport.filter([ma])\n\n if (addrs.length > 0) {\n return transport\n }\n }\n }\n\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen (addrs: Multiaddr[]) {\n if (addrs == null || addrs.length === 0) {\n log('no addresses were provided for listening, this node is dial only')\n return\n }\n\n const couldNotListen = []\n\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.filter(addrs)\n const tasks = []\n\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n log('creating listener for %s on %s', key, addr)\n const listener = transport.createListener({\n upgrader: this.components.getUpgrader()\n })\n\n let listeners = this.listeners.get(key)\n\n if (listeners == null) {\n listeners = []\n this.listeners.set(key, listeners)\n }\n\n listeners.push(listener)\n\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.dispatchEvent(new CustomEvent('listener:listening', {\n detail: listener\n }))\n })\n listener.addEventListener('close', () => {\n this.dispatchEvent(new CustomEvent('listener:close', {\n detail: listener\n }))\n })\n\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr))\n }\n\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key)\n continue\n }\n\n const results = await pSettle(tasks)\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.isFulfilled)\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw errCode(new Error(`Transport (${key}) could not listen on any available address`), codes.ERR_NO_VALID_ADDRESSES)\n }\n }\n\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`\n if (this.faultTolerance === FaultTolerance.FATAL_ALL) {\n throw errCode(new Error(message), codes.ERR_NO_VALID_ADDRESSES)\n }\n log(`libp2p in dial mode only: ${message}`)\n }\n }\n\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove (key: string) {\n log('removing %s', key)\n\n // Close any running listeners\n for (const listener of this.listeners.get(key) ?? []) {\n await listener.close()\n }\n\n this.transports.delete(key)\n this.listeners.delete(key)\n }\n\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll () {\n const tasks = []\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key))\n }\n\n await Promise.all(tasks)\n }\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n","\nexport const PROTOCOL_ID = '/multistream/1.0.0'\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport first from 'it-first'\nimport { abortableSource } from 'abortable-iterator'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Pushable } from 'it-pushable'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Source } from 'it-stream-types'\nimport type { Reader } from 'it-reader'\nimport type { MultistreamSelectInit } from '.'\n\nconst NewLine = uint8ArrayFromString('\\n')\n\nexport function encode (buffer: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const list = new Uint8ArrayList(buffer, NewLine)\n\n return lp.encode.single(list)\n}\n\n/**\n * `write` encodes and writes a single buffer\n */\nexport function write (writer: Pushable, buffer: Uint8Array | Uint8ArrayList, options: MultistreamSelectInit = {}) {\n const encoded = encode(buffer)\n\n if (options.writeBytes === true) {\n writer.push(encoded.subarray())\n } else {\n writer.push(encoded)\n }\n}\n\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport function writeAll (writer: Pushable, buffers: Uint8Array[], options: MultistreamSelectInit = {}) {\n const list = new Uint8ArrayList()\n\n for (const buf of buffers) {\n list.append(encode(buf))\n }\n\n if (options.writeBytes === true) {\n writer.push(list.subarray())\n } else {\n writer.push(list)\n }\n}\n\nexport async function read (reader: Reader, options?: AbortOptions): Promise {\n let byteLength = 1 // Read single byte chunks until the length is known\n const varByteSource = { // No return impl - we want the reader to remain readable\n [Symbol.asyncIterator]: () => varByteSource,\n next: async () => await reader.next(byteLength)\n }\n\n let input: Source = varByteSource\n\n // If we have been passed an abort signal, wrap the input source in an abortable\n // iterator that will throw if the operation is aborted\n if (options?.signal != null) {\n input = abortableSource(varByteSource, options.signal)\n }\n\n // Once the length has been parsed, read chunk for that length\n const onLength = (l: number) => {\n byteLength = l\n }\n\n const buf = await pipe(\n input,\n lp.decode({ onLength }),\n async (source) => await first(source)\n )\n\n if (buf == null) {\n throw errCode(new Error('no buffer returned'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n if (buf.get(buf.byteLength - 1) !== NewLine[0]) {\n throw errCode(new Error('missing newline'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n return buf.sublist(0, -1) // Remove newline\n}\n\nexport async function readString (reader: Reader, options?: AbortOptions) {\n const buf = await read(reader, options)\n\n return uint8ArrayToString(buf.subarray())\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { PROTOCOL_ID } from './index.js'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:select')\n\nexport async function select (stream: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options: MultistreamSelectInit = {}): Promise> {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols]\n const { reader, writer, rest, stream: shakeStream } = handshake(stream)\n\n const protocol = protocols.shift()\n\n if (protocol == null) {\n throw new Error('At least one protocol must be specified')\n }\n\n log('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol)\n const p1 = uint8ArrayFromString(PROTOCOL_ID)\n const p2 = uint8ArrayFromString(protocol)\n multistream.writeAll(writer, [p1, p2], options)\n\n let response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n }\n\n // We're done\n if (response === protocol) {\n rest()\n return { stream: shakeStream, protocol }\n }\n\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n log('select: write \"%s\"', protocol)\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n const response = await multistream.readString(reader, options)\n log('select: read \"%s\" for \"%s\"', response, protocol)\n\n if (response === protocol) {\n rest() // End our writer so others can start writing to stream\n return { stream: shakeStream, protocol }\n }\n }\n\n rest()\n throw errCode(new Error('protocol selection failed'), 'ERR_UNSUPPORTED_PROTOCOL')\n}\n","import { logger } from '@libp2p/logger'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { PROTOCOL_ID } from './constants.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:handle')\n\nexport async function handle (stream: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: MultistreamSelectInit): Promise> {\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n const { writer, reader, rest, stream: shakeStream } = handshake(stream)\n\n while (true) {\n const protocol = await multistream.readString(reader, options)\n log('read \"%s\"', protocol)\n\n if (protocol === PROTOCOL_ID) {\n log('respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n multistream.write(writer, uint8ArrayFromString(PROTOCOL_ID), options)\n continue\n }\n\n if (protocols.includes(protocol)) {\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n log('respond with \"%s\" for \"%s\"', protocol, protocol)\n rest()\n return { stream: shakeStream, protocol }\n }\n\n if (protocol === 'ls') {\n // \\n\\n\\n\n multistream.write(writer, new Uint8ArrayList(...protocols.map(p => multistream.encode(uint8ArrayFromString(p)))), options)\n // multistream.writeAll(writer, protocols.map(p => uint8ArrayFromString(p)))\n log('respond with \"%s\" for %s', protocols, protocol)\n continue\n }\n\n multistream.write(writer, uint8ArrayFromString('na'), options)\n log('respond with \"na\" for \"%s\"', protocol)\n }\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type * as Status from './status.js'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface ConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\nexport type Direction = 'inbound' | 'outbound'\n\nexport interface ConnectionStat {\n /**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the connection\n */\n timeline: ConnectionTimeline\n\n /**\n * Once a multiplexer has been negotiated for this stream, it will be set on the stat object\n */\n multiplexer?: string\n\n /**\n * Once a connection encrypter has been negotiated for this stream, it will be set on the stat object\n */\n encryption?: string\n\n /**\n * The current status of the connection\n */\n status: keyof typeof Status\n}\n\nexport interface StreamTimeline {\n open: number\n close?: number\n}\n\nexport interface StreamStat {\n /**\n * Outbound streams are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the stream\n */\n timeline: StreamTimeline\n\n /**\n * Once a protocol has been negotiated for this stream, it will be set on the stat object\n */\n protocol?: string\n}\n\n/**\n * A Stream is a data channel between two peers that\n * can be written to and read from at both ends.\n *\n * It may be encrypted and multiplexed depending on the\n * configuration of the nodes.\n */\nexport interface Stream extends Duplex {\n /**\n * Close a stream for reading and writing\n */\n close: () => void\n\n /**\n * Close a stream for reading only\n */\n closeRead: () => void\n\n /**\n * Close a stream for writing only\n */\n closeWrite: () => void\n\n /**\n * Call when a local error occurs, should close the stream for reading and writing\n */\n abort: (err: Error) => void\n\n /**\n * Call when a remote error occurs, should close the stream for reading and writing\n */\n reset: () => void\n\n /**\n * Unique identifier for a stream\n */\n id: string\n\n /**\n * Stats about this stream\n */\n stat: StreamStat\n\n /**\n * User defined stream metadata\n */\n metadata: Record\n}\n\n/**\n * A Connection is a high-level representation of a connection\n * to a remote peer that may have been secured by encryption and\n * multiplexed, depending on the configuration of the nodes\n * between which the connection is made.\n */\nexport interface Connection {\n id: string\n stat: ConnectionStat\n remoteAddr: Multiaddr\n remotePeer: PeerId\n tags: string[]\n streams: Stream[]\n\n newStream: (multicodecs: string | string[], options?: AbortOptions) => Promise\n addStream: (stream: Stream) => void\n removeStream: (id: string) => void\n close: () => Promise\n}\n\nexport const symbol = Symbol.for('@libp2p/connection')\n\nexport function isConnection (other: any): other is Connection {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface ConnectionGater {\n /**\n * denyDialMultiaddr tests whether we're permitted to Dial the\n * specified peer.\n *\n * This is called by the dialer.connectToPeer implementation before\n * dialling a peer.\n *\n * Return true to prevent dialing the passed peer.\n */\n denyDialPeer: (peerId: PeerId) => Promise\n\n /**\n * denyDialMultiaddr tests whether we're permitted to dial the specified\n * multiaddr for the given peer.\n *\n * This is called by the dialer.connectToPeer implementation after it has\n * resolved the peer's addrs, and prior to dialling each.\n *\n * Return true to prevent dialing the passed peer on the passed multiaddr.\n */\n denyDialMultiaddr: (peerId: PeerId, multiaddr: Multiaddr) => Promise\n\n /**\n * denyInboundConnection tests whether an incipient inbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has accepted a connection from its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyInboundConnection: (maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundConnection tests whether an incipient outbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has created a connection with its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyOutboundConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyInboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyOutboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyInboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyOutboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * Used by the address book to filter passed addresses.\n *\n * Return true to allow storing the passed multiaddr for the passed peer.\n */\n filterMultiaddrForPeer: (peer: PeerId, multiaddr: Multiaddr) => Promise\n}\n\nexport interface ConnectionProtector {\n\n /**\n * Takes a given Connection and creates a private encryption stream\n * between its two peers from the PSK the Protector instance was\n * created with.\n */\n protect: (connection: MultiaddrConnection) => Promise\n}\n\nexport interface MultiaddrConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * A MultiaddrConnection is returned by transports after dialing\n * a peer. It is a low-level primitive and is the raw connection\n * without encryption or stream multiplexing.\n */\nexport interface MultiaddrConnection extends Duplex {\n close: (err?: Error) => Promise\n remoteAddr: Multiaddr\n timeline: MultiaddrConnectionTimeline\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { OPEN, CLOSING, CLOSED } from '@libp2p/interface-connection/status'\nimport { symbol } from '@libp2p/interface-connection'\nimport type { Connection, ConnectionStat, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\nconst log = logger('libp2p:connection')\n\ninterface ConnectionInit {\n remoteAddr: Multiaddr\n remotePeer: PeerId\n newStream: (protocols: string[], options?: AbortOptions) => Promise\n close: () => Promise\n getStreams: () => Stream[]\n stat: ConnectionStat\n}\n\n/**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\nexport class ConnectionImpl implements Connection {\n /**\n * Connection identifier.\n */\n public readonly id: string\n\n /**\n * Observed multiaddr of the remote peer\n */\n public readonly remoteAddr: Multiaddr\n\n /**\n * Remote peer id\n */\n public readonly remotePeer: PeerId\n\n /**\n * Connection metadata\n */\n public readonly stat: ConnectionStat\n\n /**\n * User provided tags\n *\n */\n public tags: string[]\n\n /**\n * Reference to the new stream function of the multiplexer\n */\n private readonly _newStream: (protocols: string[], options?: AbortOptions) => Promise\n\n /**\n * Reference to the close function of the raw connection\n */\n private readonly _close: () => Promise\n\n /**\n * Reference to the getStreams function of the muxer\n */\n private readonly _getStreams: () => Stream[]\n\n private _closing: boolean\n\n /**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\n constructor (init: ConnectionInit) {\n const { remoteAddr, remotePeer, newStream, close, getStreams, stat } = init\n\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`\n this.remoteAddr = remoteAddr\n this.remotePeer = remotePeer\n this.stat = {\n ...stat,\n status: OPEN\n }\n this._newStream = newStream\n this._close = close\n this._getStreams = getStreams\n this.tags = []\n this._closing = false\n }\n\n get [Symbol.toStringTag] () {\n return 'Connection'\n }\n\n get [symbol] () {\n return true\n }\n\n /**\n * Get all the streams of the muxer\n */\n get streams () {\n return this._getStreams()\n }\n\n /**\n * Create a new stream from this connection\n */\n async newStream (protocols: string | string[], options?: AbortOptions): Promise {\n if (this.stat.status === CLOSING) {\n throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED')\n }\n\n if (this.stat.status === CLOSED) {\n throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED')\n }\n\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n const stream = await this._newStream(protocols, options)\n\n stream.stat.direction = 'outbound'\n\n return stream\n }\n\n /**\n * Add a stream when it is opened to the registry\n */\n addStream (stream: Stream) {\n stream.stat.direction = 'inbound'\n }\n\n /**\n * Remove stream registry after it is closed\n */\n removeStream (id: string) {\n\n }\n\n /**\n * Close the connection\n */\n async close () {\n if (this.stat.status === CLOSED || this._closing) {\n return\n }\n\n this.stat.status = CLOSING\n\n // close all streams - this can throw if we're not multiplexed\n try {\n this.streams.forEach(s => s.close())\n } catch (err) {\n log.error(err)\n }\n\n // Close raw connection\n this._closing = true\n await this._close()\n this._closing = false\n\n this.stat.timeline.close = Date.now()\n this.stat.status = CLOSED\n }\n}\n\nexport function createConnection (init: ConnectionInit): Connection {\n return new ConnectionImpl(init)\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isTopology, StreamHandlerOptions, StreamHandlerRecord } from '@libp2p/interface-registrar'\nimport merge from 'merge-options'\nimport type { Registrar, StreamHandler, Topology } from '@libp2p/interface-registrar'\nimport type { PeerProtocolsChangeData } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:registrar')\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar implements Registrar {\n private readonly topologies: Map>\n private readonly handlers: Map\n private readonly components: Components\n\n constructor (components: Components) {\n this.topologies = new Map()\n this.handlers = new Map()\n this.components = components\n\n this._onDisconnect = this._onDisconnect.bind(this)\n this._onProtocolChange = this._onProtocolChange.bind(this)\n\n this.components.getConnectionManager().addEventListener('peer:disconnect', this._onDisconnect)\n\n // happens after identify\n this.components.getPeerStore().addEventListener('change:protocols', this._onProtocolChange)\n }\n\n getProtocols () {\n return Array.from(new Set([\n ...this.topologies.keys(),\n ...this.handlers.keys()\n ])).sort()\n }\n\n getHandler (protocol: string) {\n const handler = this.handlers.get(protocol)\n\n if (handler == null) {\n throw errCode(new Error(`No handler registered for protocol ${protocol}`), codes.ERR_NO_HANDLER_FOR_PROTOCOL)\n }\n\n return handler\n }\n\n getTopologies (protocol: string) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n return []\n }\n\n return [\n ...topologies.values()\n ]\n }\n\n /**\n * Registers the `handler` for each protocol\n */\n async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise {\n if (this.handlers.has(protocol)) {\n throw errCode(new Error(`Handler already registered for protocol ${protocol}`), codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED)\n }\n\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts)\n\n this.handlers.set(protocol, {\n handler,\n options\n })\n\n // Add new protocols to self protocols in the Protobook\n await this.components.getPeerStore().protoBook.add(this.components.getPeerId(), [protocol])\n }\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle (protocols: string | string[]) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols]\n\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol)\n })\n\n // Remove protocols from self protocols in the Protobook\n await this.components.getPeerStore().protoBook.remove(this.components.getPeerId(), protocolList)\n }\n\n /**\n * Register handlers for a set of multicodecs given\n */\n async register (protocol: string, topology: Topology): Promise {\n if (!isTopology(topology)) {\n log.error('topology must be an instance of interfaces/topology')\n throw errCode(new Error('topology must be an instance of interfaces/topology'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n\n let topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n topologies = new Map()\n this.topologies.set(protocol, topologies)\n }\n\n topologies.set(id, topology)\n\n // Set registrar\n await topology.setRegistrar(this)\n\n return id\n }\n\n /**\n * Unregister topology\n */\n unregister (id: string) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id)\n\n if (topologies.size === 0) {\n this.topologies.delete(protocol)\n }\n }\n }\n }\n\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect (evt: CustomEvent) {\n const connection = evt.detail\n\n void this.components.getPeerStore().protoBook.get(connection.remotePeer)\n .then(peerProtocols => {\n for (const protocol of peerProtocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(connection.remotePeer)\n }\n }\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Check if a new peer support the multicodecs for this topology\n */\n _onProtocolChange (evt: CustomEvent) {\n const { peerId, protocols, oldProtocols } = evt.detail\n\n const removed = oldProtocols.filter(protocol => !protocols.includes(protocol))\n const added = protocols.filter(protocol => !oldProtocols.includes(protocol))\n\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(peerId)\n }\n }\n\n for (const protocol of added) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n const connection = this.components.getConnectionManager().getConnections(peerId)[0]\n\n if (connection == null) {\n continue\n }\n\n topology.onConnect(peerId, connection)\n }\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mss from '@libp2p/multistream-select'\nimport { pipe } from 'it-pipe'\n// @ts-expect-error mutable-proxy does not export types\nimport mutableProxy from 'mutable-proxy'\nimport { codes } from './errors.js'\nimport { createConnection } from '@libp2p/connection'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { MultiaddrConnection, Connection, Stream } from '@libp2p/interface-connection'\nimport type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Upgrader, UpgraderEvents } from '@libp2p/interface-transport'\nimport type { Duplex } from 'it-stream-types'\nimport { Components, isInitializable } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:upgrader')\n\ninterface CreateConectionOptions {\n cryptoProtocol: string\n direction: 'inbound' | 'outbound'\n maConn: MultiaddrConnection\n upgradedConn: Duplex\n remotePeer: PeerId\n muxerFactory?: StreamMuxerFactory\n}\n\ninterface OnStreamOptions {\n connection: Connection\n stream: Stream\n protocol: string\n}\n\nexport interface CryptoResult extends SecuredConnection {\n protocol: string\n}\n\nexport interface UpgraderInit {\n connectionEncryption: ConnectionEncrypter[]\n muxers: StreamMuxerFactory[]\n\n /**\n * An amount of ms by which an inbound connection upgrade\n * must complete\n */\n inboundUpgradeTimeout: number\n}\n\nfunction findIncomingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxInboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_INBOUND_STREAMS\n}\n\nfunction findOutgoingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxOutboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_OUTBOUND_STREAMS\n}\n\nfunction countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection) {\n let streamCount = 0\n\n connection.streams.forEach(stream => {\n if (stream.stat.direction === direction && stream.stat.protocol === protocol) {\n streamCount++\n }\n })\n\n return streamCount\n}\n\nexport class DefaultUpgrader extends EventEmitter implements Upgrader {\n private readonly components: Components\n private readonly connectionEncryption: Map\n private readonly muxers: Map\n private readonly inboundUpgradeTimeout: number\n\n constructor (components: Components, init: UpgraderInit) {\n super()\n\n this.components = components\n this.connectionEncryption = new Map()\n\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter)\n })\n\n this.muxers = new Map()\n\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer)\n })\n\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout\n }\n\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound (maConn: MultiaddrConnection): Promise {\n let encryptedConn\n let remotePeer\n let upgradedConn: Duplex\n let muxerFactory: StreamMuxerFactory | undefined\n let cryptoProtocol\n let setPeer\n let proxyPeer\n const metrics = this.components.getMetrics()\n\n const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const abortableStream = abortableDuplex(maConn, timeoutController.signal)\n maConn.source = abortableStream.source\n maConn.sink = abortableStream.sink\n\n if (await this.components.getConnectionGater().denyInboundConnection(maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())\n const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n setPeer({ toString: () => idString })\n metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })\n }\n\n log('starting the inbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n const protector = this.components.getConnectionProtector()\n\n if (protector != null) {\n log('protecting the inbound connection')\n protectedConn = await protector.protect(maConn)\n }\n\n try {\n // Encrypt the connection\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptInbound(protectedConn))\n\n if (await this.components.getConnectionGater().denyInboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n // Multiplex the connection\n if (this.muxers.size > 0) {\n const multiplexed = await this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers)\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n } else {\n upgradedConn = encryptedConn\n }\n } catch (err: any) {\n log.error('Failed to upgrade inbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n if (await this.components.getConnectionGater().denyInboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n metrics.updatePlaceholder(proxyPeer, remotePeer)\n setPeer(remotePeer)\n }\n\n log('Successfully upgraded inbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n } finally {\n timeoutController.clear()\n }\n }\n\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound (maConn: MultiaddrConnection): Promise {\n const idStr = maConn.remoteAddr.getPeerId()\n if (idStr == null) {\n throw errCode(new Error('outbound connection must have a peer id'), codes.ERR_INVALID_MULTIADDR)\n }\n\n const remotePeerId = peerIdFromString(idStr)\n\n if (await this.components.getConnectionGater().denyOutboundConnection(remotePeerId, maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n let encryptedConn\n let remotePeer\n let upgradedConn\n let cryptoProtocol\n let muxerFactory\n let setPeer\n let proxyPeer\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())\n const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n setPeer({ toB58String: () => idString })\n metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })\n }\n\n log('Starting the outbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n const protector = this.components.getConnectionProtector()\n\n if (protector != null) {\n protectedConn = await protector.protect(maConn)\n }\n\n try {\n // Encrypt the connection\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptOutbound(protectedConn, remotePeerId))\n\n if (await this.components.getConnectionGater().denyOutboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n // Multiplex the connection\n if (this.muxers.size > 0) {\n const multiplexed = await this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers)\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n } else {\n upgradedConn = encryptedConn\n }\n } catch (err: any) {\n log.error('Failed to upgrade outbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n if (await this.components.getConnectionGater().denyOutboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n metrics.updatePlaceholder(proxyPeer, remotePeer)\n setPeer(remotePeer)\n }\n\n log('Successfully upgraded outbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n }\n\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection (opts: CreateConectionOptions): Connection {\n const {\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n remotePeer,\n muxerFactory\n } = opts\n\n let muxer: StreamMuxer | undefined\n let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise) | undefined\n let connection: Connection // eslint-disable-line prefer-const\n\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return\n }\n\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.getRegistrar().getProtocols()\n const { stream, protocol } = await mss.handle(muxedStream, protocols)\n log('%s: incoming stream opened on %s', direction, protocol)\n\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n metrics.trackStream({ stream, remotePeer, protocol })\n }\n\n if (connection == null) {\n return\n }\n\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.getRegistrar())\n const streamCount = countStreams(protocol, 'inbound', connection)\n\n if (streamCount === incomingLimit) {\n muxedStream.abort(errCode(new Error(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`), codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS))\n\n return\n }\n\n muxedStream.stat.protocol = protocol\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n this.components.getPeerStore().protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))\n\n connection.addStream(muxedStream)\n this._onStream({ connection, stream: { ...muxedStream, ...stream }, protocol })\n })\n .catch(err => {\n log.error(err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n })\n },\n // Run anytime a stream closes\n onStreamEnd: muxedStream => {\n connection?.removeStream(muxedStream.id)\n }\n })\n\n if (isInitializable(muxer)) {\n muxer.init(this.components)\n }\n\n newStream = async (protocols: string[], options: AbortOptions = {}): Promise => {\n if (muxer == null) {\n throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE)\n }\n\n log('%s: starting new stream on %s', direction, protocols)\n const muxedStream = muxer.newStream()\n const metrics = this.components.getMetrics()\n let controller: TimeoutController | undefined\n\n try {\n if (options.signal == null) {\n log('No abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)\n\n controller = new TimeoutController(30000)\n options.signal = controller.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n }\n\n const { stream, protocol } = await mss.select(muxedStream, protocols, options)\n\n if (metrics != null) {\n metrics.trackStream({ stream, remotePeer, protocol })\n }\n\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.getRegistrar())\n const streamCount = countStreams(protocol, 'outbound', connection)\n\n if (streamCount === outgoingLimit) {\n const err = errCode(new Error(`Too many outbound protocol streams for protocol \"${protocol}\" - limit ${outgoingLimit}`), codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)\n muxedStream.abort(err)\n\n throw err\n }\n\n muxedStream.stat.protocol = protocol\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n this.components.getPeerStore().protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))\n\n return {\n ...muxedStream,\n ...stream,\n stat: {\n ...muxedStream.stat,\n protocol\n }\n }\n } catch (err: any) {\n log.error('could not create new stream', err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n\n if (err.code != null) {\n throw err\n }\n\n throw errCode(err, codes.ERR_UNSUPPORTED_PROTOCOL)\n } finally {\n if (controller != null) {\n controller.clear()\n }\n }\n }\n\n // Pipe all data through the muxer\n pipe(upgradedConn, muxer, upgradedConn).catch(log.error)\n }\n\n const _timeline = maConn.timeline\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.stat.status === 'OPEN') {\n await connection.close()\n }\n } catch (err: any) {\n log.error(err)\n } finally {\n this.dispatchEvent(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n }\n })().catch(err => {\n log.error(err)\n })\n }\n\n return Reflect.set(...args)\n }\n })\n maConn.timeline.upgraded = Date.now()\n\n const errConnectionNotMultiplexed = () => {\n throw errCode(new Error('connection is not multiplexed'), codes.ERR_CONNECTION_NOT_MULTIPLEXED)\n }\n\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer: remotePeer,\n stat: {\n status: 'OPEN',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol\n },\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => muxer != null ? muxer.streams : errConnectionNotMultiplexed(),\n close: async () => {\n await maConn.close()\n // Ensure remaining streams are closed\n if (muxer != null) {\n muxer.close()\n }\n }\n })\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: connection\n }))\n\n return connection\n }\n\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream (opts: OnStreamOptions): void {\n const { connection, stream, protocol } = opts\n const { handler } = this.components.getRegistrar().getHandler(protocol)\n\n handler({ connection, stream })\n }\n\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound (connection: Duplex): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('handling inbound crypto protocol selection', protocols)\n\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting inbound connection...')\n\n return {\n ...await encrypter.secureInbound(this.components.getPeerId(), stream),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\n }\n\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound (connection: MultiaddrConnection, remotePeerId: PeerId): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('selecting outbound crypto protocol', protocols)\n\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting outbound connection to %p', remotePeerId)\n\n return {\n ...await encrypter.secureOutbound(this.components.getPeerId(), stream, remotePeerId),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\n }\n\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map): Promise<{ stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('outbound selecting muxer %s', protocols)\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n log('%s selected as muxer protocol', protocol)\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing outbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound (connection: MultiaddrConnection, muxers: Map): Promise<{ stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('inbound handling muxers %s', protocols)\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing inbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Identify {\n protocolVersion?: string\n agentVersion?: string\n publicKey?: Uint8Array\n listenAddrs: Uint8Array[]\n observedAddr?: Uint8Array\n protocols: string[]\n signedPeerRecord?: Uint8Array\n}\n\nexport namespace Identify {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.protocolVersion != null) {\n writer.uint32(42)\n writer.string(obj.protocolVersion)\n }\n\n if (obj.agentVersion != null) {\n writer.uint32(50)\n writer.string(obj.agentVersion)\n }\n\n if (obj.publicKey != null) {\n writer.uint32(10)\n writer.bytes(obj.publicKey)\n }\n\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n writer.uint32(18)\n writer.bytes(value)\n }\n } else {\n throw new Error('Protocol error: required field \"listenAddrs\" was not found in object')\n }\n\n if (obj.observedAddr != null) {\n writer.uint32(34)\n writer.bytes(obj.observedAddr)\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n writer.uint32(26)\n writer.string(value)\n }\n } else {\n throw new Error('Protocol error: required field \"protocols\" was not found in object')\n }\n\n if (obj.signedPeerRecord != null) {\n writer.uint32(66)\n writer.bytes(obj.signedPeerRecord)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 5:\n obj.protocolVersion = reader.string()\n break\n case 6:\n obj.agentVersion = reader.string()\n break\n case 1:\n obj.publicKey = reader.bytes()\n break\n case 2:\n obj.listenAddrs = obj.listenAddrs ?? []\n obj.listenAddrs.push(reader.bytes())\n break\n case 4:\n obj.observedAddr = reader.bytes()\n break\n case 3:\n obj.protocols = obj.protocols ?? []\n obj.protocols.push(reader.string())\n break\n case 8:\n obj.signedPeerRecord = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n obj.listenAddrs = obj.listenAddrs ?? []\n obj.protocols = obj.protocols ?? []\n\n if (obj.listenAddrs == null) {\n throw new Error('Protocol error: value for required field \"listenAddrs\" was not found in protobuf')\n }\n\n if (obj.protocols == null) {\n throw new Error('Protocol error: value for required field \"protocols\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Identify): Uint8Array => {\n return encodeMessage(obj, Identify.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Identify => {\n return decodeMessage(buf, Identify.codec())\n }\n}\n","\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.publicKey != null) {\n writer.uint32(10)\n writer.bytes(obj.publicKey)\n } else {\n throw new Error('Protocol error: required field \"publicKey\" was not found in object')\n }\n\n if (obj.payloadType != null) {\n writer.uint32(18)\n writer.bytes(obj.payloadType)\n } else {\n throw new Error('Protocol error: required field \"payloadType\" was not found in object')\n }\n\n if (obj.payload != null) {\n writer.uint32(26)\n writer.bytes(obj.payload)\n } else {\n throw new Error('Protocol error: required field \"payload\" was not found in object')\n }\n\n if (obj.signature != null) {\n writer.uint32(42)\n writer.bytes(obj.signature)\n } else {\n throw new Error('Protocol error: required field \"signature\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes()\n break\n case 2:\n obj.payloadType = reader.bytes()\n break\n case 3:\n obj.payload = reader.bytes()\n break\n case 5:\n obj.signature = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.publicKey == null) {\n throw new Error('Protocol error: value for required field \"publicKey\" was not found in protobuf')\n }\n\n if (obj.payloadType == null) {\n throw new Error('Protocol error: value for required field \"payloadType\" was not found in protobuf')\n }\n\n if (obj.payload == null) {\n throw new Error('Protocol error: value for required field \"payload\" was not found in protobuf')\n }\n\n if (obj.signature == null) {\n throw new Error('Protocol error: value for required field \"signature\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Envelope): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\n","import errCode from 'err-code'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { codes } from '../errors.js'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\n\nexport interface EnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList) => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\n }\n\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record: Record, peerId: PeerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\n\n const domain = record.domain\n const payloadType = record.codec\n const payload = record.marshal()\n const signData = formatSignaturePayload(domain, payloadType, payload)\n const key = await unmarshalPrivateKey(peerId.privateKey)\n const signature = await key.sign(signData.subarray())\n\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\n }\n\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data: Uint8Array | Uint8ArrayList, domain: string) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw errCode(new Error('envelope signature is not valid for the given domain'), codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: EnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope) {\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return await key.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = unsigned.encode(domainUint8Array.byteLength)\n const payloadTypeLength = unsigned.encode(payloadType.length)\n const payloadLength = unsigned.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.multiaddr != null) {\n writer.uint32(10)\n writer.bytes(obj.multiaddr)\n } else {\n throw new Error('Protocol error: required field \"multiaddr\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.multiaddr == null) {\n throw new Error('Protocol error: value for required field \"multiaddr\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: AddressInfo): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.peerId != null) {\n writer.uint32(10)\n writer.bytes(obj.peerId)\n } else {\n throw new Error('Protocol error: required field \"peerId\" was not found in object')\n }\n\n if (obj.seq != null) {\n writer.uint32(16)\n writer.uint64(obj.seq)\n } else {\n throw new Error('Protocol error: required field \"seq\" was not found in object')\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n writer.uint32(26)\n PeerRecord.AddressInfo.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"addresses\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes()\n break\n case 2:\n obj.seq = reader.uint64()\n break\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.peerId == null) {\n throw new Error('Protocol error: value for required field \"peerId\" was not found in protobuf')\n }\n\n if (obj.seq == null) {\n throw new Error('Protocol error: value for required field \"seq\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerRecord): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n","\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1])\n","import { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\n}\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n const peerRecord = Protobuf.decode(buf)\n const peerId = peerIdFromBytes(peerRecord.peerId)\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => new Multiaddr(a.multiaddr))\n const seqNumber = peerRecord.seq\n\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\n\n /**\n * Marshal a record to be used in an envelope\n */\n marshal () {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown) {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n","/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals (a: any[], b: any[]) {\n const sort = (a: any, b: any) => a.toString().localeCompare(b.toString())\n return a.length === b.length && b.sort(sort) && a.sort(sort).every((item, index) => b[index].equals(item))\n}\n","export const version = '0.38.0-d281a60'\nexport const name = 'libp2p'\n","\nimport { version } from '../version.js'\n\nexport const PROTOCOL_VERSION = 'ipfs/0.1.0' // deprecated\nexport const AGENT_VERSION = `js-libp2p/${version}`\nexport const MULTICODEC_IDENTIFY = '/ipfs/id/1.0.0' // deprecated\nexport const MULTICODEC_IDENTIFY_PUSH = '/ipfs/id/push/1.0.0' // deprecated\n\nexport const IDENTIFY_PROTOCOL_VERSION = '0.1.0'\nexport const MULTICODEC_IDENTIFY_PROTOCOL_NAME = 'id'\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME = 'id/push'\nexport const MULTICODEC_IDENTIFY_PROTOCOL_VERSION = '1.0.0'\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION = '1.0.0'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport drain from 'it-drain'\nimport first from 'it-first'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Multiaddr, protocols } from '@multiformats/multiaddr'\nimport { Identify } from './pb/message.js'\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport {\n MULTICODEC_IDENTIFY,\n MULTICODEC_IDENTIFY_PUSH,\n IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION\n} from './consts.js'\nimport { codes } from '../errors.js'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { Components } from '@libp2p/components'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:identify')\n\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8\n\nexport interface HostProperties {\n agentVersion: string\n}\n\nexport interface IdentifyServiceInit {\n /**\n * The prefix to use for the protocol (default: 'ipfs')\n */\n protocolPrefix: string\n\n /**\n * What details we should send as part of an identify message\n */\n host: HostProperties\n\n /**\n * How long we should wait for a remote peer to send their identify response\n */\n timeout: number\n\n /**\n * Identify responses larger than this in bytes will be rejected (default: 8192)\n */\n maxIdentifyMessageSize?: number\n\n maxInboundStreams: number\n maxOutboundStreams: number\n\n maxPushIncomingStreams: number\n maxPushOutgoingStreams: number\n}\n\nexport class IdentifyService implements Startable {\n private readonly components: Components\n private readonly identifyProtocolStr: string\n private readonly identifyPushProtocolStr: string\n private readonly host: {\n protocolVersion: string\n agentVersion: string\n }\n\n private readonly init: IdentifyServiceInit\n private started: boolean\n\n constructor (components: Components, init: IdentifyServiceInit) {\n this.components = components\n this.started = false\n this.init = init\n\n this.identifyProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`\n this.identifyPushProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`\n\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n ...init.host\n }\n\n // When a new connection happens, trigger identify\n this.components.getConnectionManager().addEventListener('peer:connect', (evt) => {\n const connection = evt.detail\n this.identify(connection).catch(log.error)\n })\n\n // When self multiaddrs change, trigger identify-push\n this.components.getPeerStore().addEventListener('change:multiaddrs', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.getPeerId().equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n\n // When self protocols change, trigger identify-push\n this.components.getPeerStore().addEventListener('change:protocols', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.getPeerId().equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n if (this.started) {\n return\n }\n\n await this.components.getPeerStore().metadataBook.setValue(this.components.getPeerId(), 'AgentVersion', uint8ArrayFromString(this.host.agentVersion))\n await this.components.getPeerStore().metadataBook.setValue(this.components.getPeerId(), 'ProtocolVersion', uint8ArrayFromString(this.host.protocolVersion))\n\n await this.components.getRegistrar().handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n await this.components.getRegistrar().handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxPushIncomingStreams,\n maxOutboundStreams: this.init.maxPushOutgoingStreams\n })\n\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.identifyProtocolStr)\n await this.components.getRegistrar().unhandle(this.identifyPushProtocolStr)\n\n this.started = false\n }\n\n /**\n * Send an Identify Push update to the list of connections\n */\n async push (connections: Connection[]): Promise {\n const signedPeerRecord = await this.components.getPeerStore().addressBook.getRawEnvelope(this.components.getPeerId())\n const listenAddrs = this.components.getAddressManager().getAddresses().map((ma) => ma.bytes)\n const protocols = await this.components.getPeerStore().protoBook.get(this.components.getPeerId())\n\n const pushes = connections.map(async connection => {\n let stream: Stream | undefined\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n stream = await connection.newStream([this.identifyPushProtocolStr], {\n signal: timeoutController.signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n await pipe(\n [Identify.encode({\n listenAddrs,\n signedPeerRecord,\n protocols\n })],\n lp.encode(),\n source,\n drain\n )\n } catch (err: any) {\n // Just log errors\n log.error('could not push identify update to peer', err)\n } finally {\n if (stream != null) {\n stream.close()\n }\n\n timeoutController.clear()\n }\n })\n\n await Promise.all(pushes)\n }\n\n /**\n * Calls `push` on all peer connections\n */\n async pushToPeerStore () {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return\n }\n\n const connections: Connection[] = []\n\n for (const conn of this.components.getConnectionManager().getConnections()) {\n const peerId = conn.remotePeer\n const peer = await this.components.getPeerStore().get(peerId)\n\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n continue\n }\n\n connections.push(conn)\n }\n\n await this.push(connections)\n }\n\n async _identify (connection: Connection, options: AbortOptions = {}): Promise {\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.identifyProtocolStr], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data == null) {\n throw errCode(new Error('No data could be retrieved'), codes.ERR_CONNECTION_ENDED)\n }\n\n try {\n return Identify.decode(data)\n } catch (err: any) {\n throw errCode(err, codes.ERR_INVALID_MESSAGE)\n }\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Requests the `Identify` message from peer associated with the given `connection`.\n * If the identified peer does not match the `PeerId` associated with the connection,\n * an error will be thrown.\n */\n async identify (connection: Connection, options: AbortOptions = {}): Promise {\n const message = await this._identify(connection, options)\n\n const {\n publicKey,\n listenAddrs,\n protocols,\n observedAddr,\n signedPeerRecord,\n agentVersion,\n protocolVersion\n } = message\n\n if (publicKey == null) {\n throw errCode(new Error('public key was missing from identify message'), codes.ERR_MISSING_PUBLIC_KEY)\n }\n\n const id = await peerIdFromKeys(publicKey)\n\n if (!connection.remotePeer.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (this.components.getPeerId().equals(id)) {\n throw errCode(new Error('identified peer is our own peer id?'), codes.ERR_INVALID_PEER)\n }\n\n // Get the observedAddr if there is one\n const cleanObservedAddr = IdentifyService.getCleanMultiaddr(observedAddr)\n\n if (signedPeerRecord != null) {\n log('received signed peer record from %p', id)\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(signedPeerRecord, PeerRecord.DOMAIN)\n\n if (!envelope.peerId.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)) {\n await this.components.getPeerStore().protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n return\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('no signed peer record received from %p', id)\n }\n\n log('falling back to legacy addresses from %p', id)\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.getPeerStore().addressBook.set(id, listenAddrs.map((addr) => new Multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n await this.components.getPeerStore().protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n // TODO: Add and score our observed addr\n log('received observed address of %s', cleanObservedAddr?.toString())\n // this.components.getAddressManager().addObservedAddr(observedAddr)\n }\n\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async _handleIdentify (data: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const publicKey = this.components.getPeerId().publicKey ?? new Uint8Array(0)\n const peerData = await this.components.getPeerStore().get(this.components.getPeerId())\n const multiaddrs = this.components.getAddressManager().getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n let signedPeerRecord = peerData.peerRecordEnvelope\n\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.components.getPeerId(),\n multiaddrs\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.getPeerId())\n await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)\n signedPeerRecord = envelope.marshal().subarray()\n }\n\n const message = Identify.encode({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr: connection.remoteAddr.bytes,\n protocols: peerData.protocols\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n await pipe(\n [message],\n lp.encode(),\n source,\n drain\n )\n } catch (err: any) {\n log.error('could not respond to identify request', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n }\n\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush (data: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n let message: Identify | undefined\n try {\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data != null) {\n message = Identify.decode(data)\n }\n } catch (err: any) {\n return log.error('received invalid message', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n\n if (message == null) {\n return log.error('received invalid message')\n }\n\n const id = connection.remotePeer\n\n if (this.components.getPeerId().equals(id)) {\n log('received push from ourselves?')\n return\n }\n\n log('received push from %p', id)\n\n if (message.signedPeerRecord != null) {\n log('received signedPeerRecord in push')\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(message.signedPeerRecord, PeerRecord.DOMAIN)\n\n if (await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)) {\n log('consumed signedPeerRecord sent in push')\n\n await this.components.getPeerStore().protoBook.set(id, message.protocols)\n return\n } else {\n log('failed to consume signedPeerRecord sent in push')\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('did not receive signedPeerRecord in push')\n }\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.getPeerStore().addressBook.set(id,\n message.listenAddrs.map((addr) => new Multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n // Update the protocols\n try {\n await this.components.getPeerStore().protoBook.set(id, message.protocols)\n } catch (err: any) {\n log.error('received invalid protocols', err)\n }\n\n log('handled push from %p', id)\n }\n\n /**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\n static getCleanMultiaddr (addr: Uint8Array | string | null | undefined) {\n if (addr != null && addr.length > 0) {\n try {\n return new Multiaddr(addr)\n } catch {\n\n }\n }\n }\n}\n\n/**\n * The protocols the IdentifyService supports\n */\nexport const multicodecs = {\n IDENTIFY: MULTICODEC_IDENTIFY,\n IDENTIFY_PUSH: MULTICODEC_IDENTIFY_PUSH\n}\n\nexport const Message = { Identify }\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, enumeration } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface FetchRequest {\n identifier: string\n}\n\nexport namespace FetchRequest {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.identifier != null) {\n writer.uint32(10)\n writer.string(obj.identifier)\n } else {\n throw new Error('Protocol error: required field \"identifier\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.identifier = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.identifier == null) {\n throw new Error('Protocol error: value for required field \"identifier\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchRequest): Uint8Array => {\n return encodeMessage(obj, FetchRequest.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchRequest => {\n return decodeMessage(buf, FetchRequest.codec())\n }\n}\n\nexport interface FetchResponse {\n status: FetchResponse.StatusCode\n data: Uint8Array\n}\n\nexport namespace FetchResponse {\n export enum StatusCode {\n OK = 'OK',\n NOT_FOUND = 'NOT_FOUND',\n ERROR = 'ERROR'\n }\n\n enum __StatusCodeValues {\n OK = 0,\n NOT_FOUND = 1,\n ERROR = 2\n }\n\n export namespace StatusCode {\n export const codec = () => {\n return enumeration(__StatusCodeValues)\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.status != null) {\n writer.uint32(8)\n FetchResponse.StatusCode.codec().encode(obj.status, writer)\n } else {\n throw new Error('Protocol error: required field \"status\" was not found in object')\n }\n\n if (obj.data != null) {\n writer.uint32(18)\n writer.bytes(obj.data)\n } else {\n throw new Error('Protocol error: required field \"data\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.status = FetchResponse.StatusCode.codec().decode(reader)\n break\n case 2:\n obj.data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.status == null) {\n throw new Error('Protocol error: value for required field \"status\" was not found in protobuf')\n }\n\n if (obj.data == null) {\n throw new Error('Protocol error: value for required field \"data\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchResponse): Uint8Array => {\n return encodeMessage(obj, FetchResponse.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchResponse => {\n return decodeMessage(buf, FetchResponse.codec())\n }\n}\n","\n// https://github.com/libp2p/specs/tree/master/fetch#wire-protocol\nexport const PROTOCOL_VERSION = '0.0.1'\nexport const PROTOCOL_NAME = 'fetch'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport * as lp from 'it-length-prefixed'\nimport { FetchRequest, FetchResponse } from './pb/proto.js'\nimport { PROTOCOL_NAME, PROTOCOL_VERSION } from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Components } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:fetch')\n\nexport interface FetchServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a remote peer to send any data\n */\n timeout: number\n}\n\nexport interface HandleMessageOptions {\n stream: Stream\n protocol: string\n}\n\nexport interface LookupFunction {\n (key: string): Promise\n}\n\n/**\n * A simple libp2p protocol for requesting a value corresponding to a key from a peer.\n * Developers can register one or more lookup function for retrieving the value corresponding to\n * a given key. Each lookup function must act on a distinct part of the overall key space, defined\n * by a fixed prefix that all keys that should be routed to that lookup function will start with.\n */\nexport class FetchService implements Startable {\n public readonly protocol: string\n private readonly components: Components\n private readonly lookupFunctions: Map\n private started: boolean\n private readonly init: FetchServiceInit\n\n constructor (components: Components, init: FetchServiceInit) {\n this.started = false\n this.components = components\n this.protocol = `/${init.protocolPrefix ?? 'libp2p'}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.lookupFunctions = new Map() // Maps key prefix to value lookup function\n this.handleMessage = this.handleMessage.bind(this)\n this.init = init\n }\n\n async start () {\n await this.components.getRegistrar().handle(this.protocol, (data) => {\n void this.handleMessage(data)\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n data.stream.close()\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Sends a request to fetch the value associated with the given key from the given peer\n */\n async fetch (peer: PeerId, key: string, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const connection = await this.components.getConnectionManager().openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.protocol], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const result = await pipe(\n [FetchRequest.encode({ identifier: key })],\n lp.encode(),\n source,\n lp.decode(),\n async function (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n const response = FetchResponse.decode(buf)\n\n switch (response.status) {\n case (FetchResponse.StatusCode.OK): {\n return response.data\n }\n case (FetchResponse.StatusCode.NOT_FOUND): {\n return null\n }\n case (FetchResponse.StatusCode.ERROR): {\n const errmsg = (new TextDecoder()).decode(response.data)\n throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)\n }\n default: {\n throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)\n }\n }\n }\n )\n\n return result ?? null\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Invoked when a fetch request is received. Reads the request message off the given stream and\n * responds based on looking up the key in the request via the lookup callback that corresponds\n * to the key's prefix.\n */\n async handleMessage (data: IncomingStreamData) {\n const { stream } = data\n const self = this\n\n await pipe(\n stream,\n lp.decode(),\n async function * (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n // for await (const buf of source) {\n const request = FetchRequest.decode(buf)\n\n let response: FetchResponse\n const lookup = self._getLookupFunction(request.identifier)\n if (lookup != null) {\n const data = await lookup(request.identifier)\n if (data != null) {\n response = { status: FetchResponse.StatusCode.OK, data }\n } else {\n response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }\n }\n } else {\n const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier)\n response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }\n }\n\n yield FetchResponse.encode(response)\n },\n lp.encode(),\n stream\n )\n }\n\n /**\n * Given a key, finds the appropriate function for looking up its corresponding value, based on\n * the key's prefix.\n */\n _getLookupFunction (key: string) {\n for (const prefix of this.lookupFunctions.keys()) {\n if (key.startsWith(prefix)) {\n return this.lookupFunctions.get(prefix)\n }\n }\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix\n */\n registerLookupFunction (prefix: string, lookup: LookupFunction) {\n if (this.lookupFunctions.has(prefix)) {\n throw errCode(new Error(\"Fetch protocol handler for key prefix '\" + prefix + \"' already registered\"), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n this.lookupFunctions.set(prefix, lookup)\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix.\n */\n unregisterLookupFunction (prefix: string, lookup?: LookupFunction) {\n if (lookup != null) {\n const existingLookup = this.lookupFunctions.get(prefix)\n\n if (existingLookup !== lookup) {\n return\n }\n }\n\n this.lookupFunctions.delete(prefix)\n }\n}\n","\nexport const PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { randomBytes } from '@libp2p/crypto'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION } from './constants.js'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { Stream } from '@libp2p/interface-connection'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:ping')\n\nexport interface PingServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a ping response\n */\n timeout: number\n}\n\nexport class PingService implements Startable {\n public readonly protocol: string\n private readonly components: Components\n private started: boolean\n private readonly init: PingServiceInit\n\n constructor (components: Components, init: PingServiceInit) {\n this.components = components\n this.started = false\n this.protocol = `/${init.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.init = init\n }\n\n async start () {\n await this.components.getRegistrar().handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage (data: IncomingStreamData) {\n const { stream } = data\n\n void pipe(stream, stream)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n *\n * @param {PeerId|Multiaddr} peer\n * @returns {Promise}\n */\n async ping (peer: PeerId, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const start = Date.now()\n const data = randomBytes(PING_LENGTH)\n const connection = await this.components.getConnectionManager().openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.protocol], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const result = await pipe(\n [data],\n source,\n async (source) => await first(source)\n )\n const end = Date.now()\n\n if (result == null || !uint8ArrayEquals(data, result.subarray())) {\n throw errCode(new Error('Received wrong ping ack'), codes.ERR_WRONG_PING_ACK)\n }\n\n return end - start\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n}\n","import { isLoopbackAddr } from 'is-loopback-addr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Check if a given multiaddr is a loopback address.\n */\nexport function isLoopback (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return isLoopbackAddr(address)\n}\n","/**\n * Check if a given ip address is a loopback address\n */\nexport function isLoopbackAddr (ip: string) {\n return /^127\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n /^::1$/.test(ip)\n}\n","import { upnpNat, NatAPI } from '@achingbrain/nat-port-mapper'\nimport { logger } from '@libp2p/logger'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { isBrowser } from 'wherearewe'\nimport isPrivateIp from 'private-ip'\nimport * as pkg from './version.js'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:nat')\nconst DEFAULT_TTL = 7200\n\nfunction highPort (min = 1024, max = 65535) {\n return Math.floor(Math.random() * (max - min + 1) + min)\n}\n\nexport interface PMPOptions {\n /**\n * Whether to enable PMP as well as UPnP\n */\n enabled?: boolean\n}\n\nexport interface NatManagerInit {\n /**\n * Whether to enable the NAT manager\n */\n enabled: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n externalAddress?: string\n\n /**\n * Pass a value to use instead of auto-detection\n */\n localAddress?: string\n\n /**\n * A string value to use for the port mapping description on the gateway\n */\n description?: string\n\n /**\n * How long UPnP port mappings should last for in seconds (minimum 1200)\n */\n ttl?: number\n\n /**\n * Whether to automatically refresh UPnP port mappings when their TTL is reached\n */\n keepAlive: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n gateway?: string\n}\n\nexport class NatManager implements Startable {\n private readonly components: Components\n private readonly enabled: boolean\n private readonly externalAddress?: string\n private readonly localAddress?: string\n private readonly description: string\n private readonly ttl: number\n private readonly keepAlive: boolean\n private readonly gateway?: string\n private started: boolean\n private client?: NatAPI\n\n constructor (components: Components, init: NatManagerInit) {\n this.components = components\n\n this.started = false\n this.enabled = init.enabled\n this.externalAddress = init.externalAddress\n this.localAddress = init.localAddress\n this.description = init.description ?? `${pkg.name}@${pkg.version} ${this.components.getPeerId().toString()}`\n this.ttl = init.ttl ?? DEFAULT_TTL\n this.keepAlive = init.keepAlive ?? true\n this.gateway = init.gateway\n\n if (this.ttl < DEFAULT_TTL) {\n throw errCode(new Error(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`), codes.ERR_INVALID_PARAMETERS)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n start () {}\n\n /**\n * Attempt to use uPnP to configure port mapping using the current gateway.\n *\n * Run after start to ensure the transport manager has all addresses configured.\n */\n afterStart () {\n if (isBrowser || !this.enabled || this.started) {\n return\n }\n\n this.started = true\n\n // done async to not slow down startup\n void this._start().catch((err) => {\n // hole punching errors are non-fatal\n log.error(err)\n })\n }\n\n async _start () {\n const addrs = this.components.getTransportManager().getAddrs()\n\n for (const addr of addrs) {\n // try to open uPnP ports for each thin waist address\n const { family, host, port, transport } = addr.toOptions()\n\n if (!addr.isThinWaistAddress() || transport !== 'tcp') {\n // only bare tcp addresses\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (isLoopback(addr)) {\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (family !== 4) {\n // ignore ipv6\n // eslint-disable-next-line no-continue\n continue\n }\n\n const client = await this._getClient()\n const publicIp = this.externalAddress ?? await client.externalIp()\n\n if (isPrivateIp(publicIp)) {\n throw new Error(`${publicIp} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`)\n }\n\n const publicPort = highPort()\n\n log(`opening uPnP connection from ${publicIp}:${publicPort} to ${host}:${port}`)\n\n await client.map({\n publicPort,\n localPort: port,\n localAddress: this.localAddress,\n protocol: transport.toUpperCase() === 'TCP' ? 'TCP' : 'UDP'\n })\n\n this.components.getAddressManager().addObservedAddr(Multiaddr.fromNodeAddress({\n family: 4,\n address: publicIp,\n port: publicPort\n }, transport))\n }\n }\n\n async _getClient () {\n if (this.client != null) {\n return this.client\n }\n\n this.client = await upnpNat({\n description: this.description,\n ttl: this.ttl,\n keepAlive: this.keepAlive,\n gateway: this.gateway\n })\n\n return this.client\n }\n\n /**\n * Stops the NAT manager\n */\n async stop () {\n if (isBrowser || this.client == null) {\n return\n }\n\n try {\n await this.client.close()\n this.client = undefined\n } catch (err: any) {\n log.error(err)\n }\n }\n}\n","\nexport async function upnpNat () {\n throw new Error('Not supported in browsers')\n}\n\nexport async function pmpNat () {\n throw new Error('Not supported in browsers')\n}\n","import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport type { Components } from '@libp2p/components'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { logger } from '@libp2p/logger'\nimport { protocols } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:peer-record-updater')\n\nexport class PeerRecordUpdater implements Startable {\n private readonly components: Components\n private started: boolean\n\n constructor (components: Components) {\n this.components = components\n this.started = false\n this.update = this.update.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n this.components.getTransportManager().addEventListener('listener:listening', this.update)\n this.components.getTransportManager().addEventListener('listener:close', this.update)\n this.components.getAddressManager().addEventListener('change:addresses', this.update)\n }\n\n async stop () {\n this.started = false\n this.components.getTransportManager().removeEventListener('listener:listening', this.update)\n this.components.getTransportManager().removeEventListener('listener:close', this.update)\n this.components.getAddressManager().removeEventListener('change:addresses', this.update)\n }\n\n /**\n * Create (or update if existing) self peer record and store it in the AddressBook.\n */\n update () {\n Promise.resolve()\n .then(async () => {\n const peerRecord = new PeerRecord({\n peerId: this.components.getPeerId(),\n multiaddrs: this.components.getAddressManager().getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.getPeerId())\n await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)\n })\n .catch(err => {\n log.error('Could not update self peer record: %o', err)\n })\n }\n}\n","import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTPeerRouting implements PeerRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async findPeer (peerId: PeerId, options: AbortOptions = {}) {\n for await (const event of this.dht.findPeer(peerId, options)) {\n if (event.name === 'FINAL_PEER') {\n return event.peer\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n async * getClosestPeers (key: Uint8Array, options: AbortOptions = {}) {\n for await (const event of this.dht.getClosestPeers(key, options)) {\n if (event.name === 'PEER_RESPONSE') {\n yield * event.closer\n }\n }\n }\n}\n","\nexport const codes = {\n ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS',\n ERR_NOT_FOUND: 'ERR_NOT_FOUND'\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { codes } from './errors.js'\nimport { PeerRecord, RecordEnvelope } from '@libp2p/peer-record'\nimport { pipe } from 'it-pipe'\nimport all from 'it-all'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport each from 'it-foreach'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { AddressFilter, Peer, PeerMultiaddrsChangeData, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Store } from './store.js'\nimport type { Envelope } from '@libp2p/interface-record'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\n\nconst log = logger('libp2p:peer-store:address-book')\nconst EVENT_NAME = 'change:multiaddrs'\n\nasync function allowAll () {\n return true\n}\n\nexport class PeerStoreAddressBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n private readonly addressFilter: AddressFilter\n\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store, addressFilter?: AddressFilter) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n this.addressFilter = addressFilter ?? allowAll\n }\n\n /**\n * ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope.\n * This will return a boolean that indicates if the record was successfully processed and added\n * into the AddressBook.\n */\n async consumePeerRecord (envelope: Envelope) {\n log.trace('consumePeerRecord await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('consumePeerRecord got write lock')\n\n let peerId\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n let peerRecord\n try {\n peerRecord = PeerRecord.createFromProtobuf(envelope.payload)\n } catch (err: any) {\n log.error('invalid peer record received')\n return false\n }\n\n peerId = peerRecord.peerId\n const multiaddrs = peerRecord.multiaddrs\n\n // Verify peerId\n if (!peerId.equals(envelope.peerId)) {\n log('signing key does not match PeerId in the PeerRecord')\n return false\n }\n\n // ensure the record has multiaddrs\n if (multiaddrs == null || multiaddrs.length === 0) {\n return false\n }\n\n if (await this.store.has(peerId)) {\n peer = await this.store.load(peerId)\n\n if (peer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope)\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)\n\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber)\n return false\n }\n }\n }\n\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter, true)\n\n // Replace unsigned addresses by the new ones from the record\n // TODO: Once we have ttls for the addresses, we should merge these in\n updatedPeer = await this.store.patchOrCreate(peerId, {\n addresses,\n peerRecordEnvelope: envelope.marshal().subarray()\n })\n\n log('stored provided peer record for %p', peerRecord.peerId)\n } finally {\n log.trace('consumePeerRecord release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(({ multiaddr }) => multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n return true\n }\n\n async getRawEnvelope (peerId: PeerId) {\n log.trace('getRawEnvelope await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getRawEnvelope got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.peerRecordEnvelope\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getRawEnvelope release read lock')\n release()\n }\n }\n\n /**\n * Get an Envelope containing a PeerRecord for the given peer.\n * Returns undefined if no record exists.\n */\n async getPeerRecord (peerId: PeerId) {\n const raw = await this.getRawEnvelope(peerId)\n\n if (raw == null) {\n return undefined\n }\n\n return await RecordEnvelope.createFromProtobuf(raw)\n }\n\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.addresses\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let hasPeer = false\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length && addresses.length === peer.addresses.length) {\n // not changing anything, no need to update\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, { addresses })\n\n log('set multiaddrs for %p', peerId)\n } finally {\n log.trace('set multiaddrs for %p', peerId)\n log('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (!hasPeer) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async add (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let hasPeer\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, { addresses })\n\n log('added multiaddrs for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (hasPeer === true) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n addresses: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: [],\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n }\n }\n}\n\nasync function filterMultiaddrs (peerId: PeerId, multiaddrs: Multiaddr[], addressFilter: AddressFilter, isCertified: boolean = false) {\n return await pipe(\n multiaddrs,\n (source) => each(source, (multiaddr) => {\n if (!Multiaddr.isMultiaddr(multiaddr)) {\n log.error('multiaddr must be an instance of Multiaddr')\n throw errcode(new Error('multiaddr must be an instance of Multiaddr'), codes.ERR_INVALID_PARAMETERS)\n }\n }),\n (source) => filter(source, async (multiaddr) => await addressFilter(peerId, multiaddr)),\n (source) => map(source, (multiaddr) => {\n return {\n multiaddr: new Multiaddr(multiaddr.toString()),\n isCertified\n }\n }),\n async (source) => await all(source)\n )\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, KeyBook, PeerPublicKeyChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:key-book')\n\nconst EVENT_NAME = 'change:pubkey'\n\nexport class PeerStoreKeyBook implements KeyBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The KeyBook is responsible for keeping the known public keys of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Set the Peer public key\n */\n async set (peerId: PeerId, publicKey: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(publicKey instanceof Uint8Array)) {\n log.error('publicKey must be an instance of Uint8Array to store data')\n throw errcode(new Error('publicKey must be an instance of PublicKey'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let updatedKey = false\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if ((peer.pubKey != null) && uint8arrayEquals(peer.pubKey, publicKey)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: publicKey\n })\n updatedKey = true\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n if (updatedKey) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: publicKey,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n }\n\n /**\n * Get Public key of the given PeerId, if stored\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await write lock')\n const release = await this.store.lock.readLock()\n log.trace('get got write lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.pubKey\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log('get release write lock')\n release()\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: undefined\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: undefined,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, MetadataBook, PeerMetadataChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:metadata-book')\n\nconst EVENT_NAME = 'change:metadata'\n\nexport class PeerStoreMetadataBook implements MetadataBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The MetadataBook is responsible for keeping metadata\n * about known peers\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Get the known data of a provided peer\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return new Map()\n }\n\n /**\n * Get specific metadata value, if it exists\n */\n async getValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('getValue await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getValue got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata.get(key)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getValue release write lock')\n release()\n }\n }\n\n async set (peerId: PeerId, metadata: Map) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(metadata instanceof Map)) {\n log.error('valid metadata must be provided to store data')\n throw errcode(new Error('valid metadata must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.mergeOrCreate(peerId, {\n metadata\n })\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n /**\n * Set metadata key and value of a provided peer\n */\n async setValue (peerId: PeerId, key: string, value: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (typeof key !== 'string' || !(value instanceof Uint8Array)) {\n log.error('valid key and value must be provided to store data')\n throw errcode(new Error('valid key and value must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('setValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('setValue got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const existingValue = peer.metadata.get(key)\n\n if (existingValue != null && uint8ArrayEquals(value, existingValue)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n metadata: new Map([[key, value]])\n })\n } finally {\n log.trace('setValue release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: updatedPeer.metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n if (peer != null) {\n await this.store.patch(peerId, {\n metadata: new Map()\n })\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: new Map(),\n oldMetadata: peer.metadata\n }\n }))\n }\n }\n\n async deleteValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('deleteValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('deleteValue got write lock')\n\n let metadata\n let peer: Peer | undefined\n\n try {\n peer = await this.store.load(peerId)\n metadata = peer.metadata\n\n metadata.delete(key)\n\n await this.store.patch(peerId, {\n metadata\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('deleteValue release write lock')\n release()\n }\n\n if (metadata != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { Peer, PeerProtocolsChangeData, PeerStore, ProtoBook } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:proto-book')\n\nconst EVENT_NAME = 'change:protocols'\n\nexport class PeerStoreProtoBook implements ProtoBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The ProtoBook is responsible for keeping the known supported\n * protocols of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n async get (peerId: PeerId) {\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.protocols\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n\n log('stored provided protocols for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async add (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...peer.protocols,\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n protocols\n })\n\n log('added provided protocols for %p', peerId)\n } finally {\n log.trace('add release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async remove (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('remove await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('remove got write lock')\n\n let peer: Peer | undefined\n let updatedPeer: Peer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const protocolSet = new Set(peer.protocols)\n\n for (const protocol of protocols) {\n protocolSet.delete(protocol)\n }\n\n if (peer.protocols.length === protocolSet.size) {\n return\n }\n\n protocols = Array.from(protocolSet)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n } finally {\n log.trace('remove release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n protocols: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: [],\n oldProtocols: peer.protocols\n }\n }))\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Peer {\n addresses: Address[]\n protocols: string[]\n metadata: Metadata[]\n pubKey?: Uint8Array\n peerRecordEnvelope?: Uint8Array\n}\n\nexport namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n writer.uint32(10)\n Address.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"addresses\" was not found in object')\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n writer.uint32(18)\n writer.string(value)\n }\n } else {\n throw new Error('Protocol error: required field \"protocols\" was not found in object')\n }\n\n if (obj.metadata != null) {\n for (const value of obj.metadata) {\n writer.uint32(26)\n Metadata.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"metadata\" was not found in object')\n }\n\n if (obj.pubKey != null) {\n writer.uint32(34)\n writer.bytes(obj.pubKey)\n }\n\n if (obj.peerRecordEnvelope != null) {\n writer.uint32(42)\n writer.bytes(obj.peerRecordEnvelope)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n addresses: [],\n protocols: [],\n metadata: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.addresses.push(Address.codec().decode(reader, reader.uint32()))\n break\n case 2:\n obj.protocols.push(reader.string())\n break\n case 3:\n obj.metadata.push(Metadata.codec().decode(reader, reader.uint32()))\n break\n case 4:\n obj.pubKey = reader.bytes()\n break\n case 5:\n obj.peerRecordEnvelope = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n}\n\nexport interface Address {\n multiaddr: Uint8Array\n isCertified?: boolean\n}\n\nexport namespace Address {\n let _codec: Codec
\n\n export const codec = (): Codec
=> {\n if (_codec == null) {\n _codec = message
((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.multiaddr != null) {\n writer.uint32(10)\n writer.bytes(obj.multiaddr)\n } else {\n throw new Error('Protocol error: required field \"multiaddr\" was not found in object')\n }\n\n if (obj.isCertified != null) {\n writer.uint32(16)\n writer.bool(obj.isCertified)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes()\n break\n case 2:\n obj.isCertified = reader.bool()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.multiaddr == null) {\n throw new Error('Protocol error: value for required field \"multiaddr\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Address): Uint8Array => {\n return encodeMessage(obj, Address.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Address => {\n return decodeMessage(buf, Address.codec())\n }\n}\n\nexport interface Metadata {\n key: string\n value: Uint8Array\n}\n\nexport namespace Metadata {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.key != null) {\n writer.uint32(10)\n writer.string(obj.key)\n } else {\n throw new Error('Protocol error: required field \"key\" was not found in object')\n }\n\n if (obj.value != null) {\n writer.uint32(18)\n writer.bytes(obj.value)\n } else {\n throw new Error('Protocol error: required field \"value\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: '',\n value: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string()\n break\n case 2:\n obj.value = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.key == null) {\n throw new Error('Protocol error: value for required field \"key\" was not found in protobuf')\n }\n\n if (obj.value == null) {\n throw new Error('Protocol error: value for required field \"value\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Metadata): Uint8Array => {\n return encodeMessage(obj, Metadata.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Metadata => {\n return decodeMessage(buf, Metadata.codec())\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PriorityQueue_queue;\nimport lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n constructor() {\n _PriorityQueue_queue.set(this, []);\n }\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n run,\n };\n if (this.size && __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\")[this.size - 1].priority >= options.priority) {\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").push(element);\n return;\n }\n const index = lowerBound(__classPrivateFieldGet(this, _PriorityQueue_queue, \"f\"), element, (a, b) => b.priority - a.priority);\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").splice(index, 0, element);\n }\n dequeue() {\n const item = __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").length;\n }\n}\n_PriorityQueue_queue = new WeakMap();\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pendingCount, _PQueue_concurrency, _PQueue_isPaused, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_emitEvents, _PQueue_onResumeInterval, _PQueue_isIntervalPaused_get, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, _PQueue_onEvent;\nimport EventEmitter from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\nconst timeoutError = new TimeoutError();\n/**\nThe error thrown by `queue.add()` when a job is aborted before it is run. See `signal`.\n*/\nexport class AbortError extends Error {\n}\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n _PQueue_instances.add(this);\n _PQueue_carryoverConcurrencyCount.set(this, void 0);\n _PQueue_isIntervalIgnored.set(this, void 0);\n _PQueue_intervalCount.set(this, 0);\n _PQueue_intervalCap.set(this, void 0);\n _PQueue_interval.set(this, void 0);\n _PQueue_intervalEnd.set(this, 0);\n _PQueue_intervalId.set(this, void 0);\n _PQueue_timeoutId.set(this, void 0);\n _PQueue_queue.set(this, void 0);\n _PQueue_queueClass.set(this, void 0);\n _PQueue_pendingCount.set(this, 0);\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n _PQueue_concurrency.set(this, void 0);\n _PQueue_isPaused.set(this, void 0);\n _PQueue_throwOnTimeout.set(this, void 0);\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n \n Applies to each future operation.\n */\n Object.defineProperty(this, \"timeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\\` (${typeof options.interval})`);\n }\n __classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, \"f\");\n __classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, \"f\");\n __classPrivateFieldSet(this, _PQueue_interval, options.interval, \"f\");\n __classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), \"f\");\n __classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, \"f\");\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n __classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, \"f\");\n __classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, \"f\");\n }\n get concurrency() {\n return __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n __classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n }\n /**\n Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options = {}) {\n return new Promise((resolve, reject) => {\n const run = async () => {\n var _a;\n var _b, _c;\n __classPrivateFieldSet(this, _PQueue_pendingCount, (_b = __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\"), _b++, _b), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\"), _c++, _c), \"f\");\n try {\n if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n reject(new AbortError('The task was aborted.'));\n return;\n }\n const operation = (this.timeout === undefined && options.timeout === undefined) ? fn({ signal: options.signal }) : pTimeout(Promise.resolve(fn({ signal: options.signal })), (options.timeout === undefined ? this.timeout : options.timeout), () => {\n if (options.throwOnTimeout === undefined ? __classPrivateFieldGet(this, _PQueue_throwOnTimeout, \"f\") : options.throwOnTimeout) {\n reject(timeoutError);\n }\n return undefined;\n });\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n reject(error);\n this.emit('error', error);\n }\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_next).call(this);\n };\n __classPrivateFieldGet(this, _PQueue_queue, \"f\").enqueue(run, options);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('add');\n });\n }\n /**\n Same as `.add()`, but accepts an array of sync or async functions.\n\n @returns A promise that resolves when all functions are resolved.\n */\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n return this;\n }\n __classPrivateFieldSet(this, _PQueue_isPaused, false, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n __classPrivateFieldSet(this, _PQueue_isPaused, true, \"f\");\n }\n /**\n Clear the queue.\n */\n clear() {\n __classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet(this, _PQueue_queueClass, \"f\"))(), \"f\");\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'next', () => __classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (__classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'idle');\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\");\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return __classPrivateFieldGet(this, _PQueue_isPaused, \"f\");\n }\n}\n_PQueue_carryoverConcurrencyCount = new WeakMap(), _PQueue_isIntervalIgnored = new WeakMap(), _PQueue_intervalCount = new WeakMap(), _PQueue_intervalCap = new WeakMap(), _PQueue_interval = new WeakMap(), _PQueue_intervalEnd = new WeakMap(), _PQueue_intervalId = new WeakMap(), _PQueue_timeoutId = new WeakMap(), _PQueue_queue = new WeakMap(), _PQueue_queueClass = new WeakMap(), _PQueue_pendingCount = new WeakMap(), _PQueue_concurrency = new WeakMap(), _PQueue_isPaused = new WeakMap(), _PQueue_throwOnTimeout = new WeakMap(), _PQueue_instances = new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") < __classPrivateFieldGet(this, _PQueue_intervalCap, \"f\");\n}, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") < __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n}, _PQueue_next = function _PQueue_next() {\n var _a;\n __classPrivateFieldSet(this, _PQueue_pendingCount, (_a = __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\"), _a--, _a), \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('next');\n}, _PQueue_emitEvents = function _PQueue_emitEvents() {\n this.emit('empty');\n if (__classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0) {\n this.emit('idle');\n }\n}, _PQueue_onResumeInterval = function _PQueue_onResumeInterval() {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n __classPrivateFieldSet(this, _PQueue_timeoutId, undefined, \"f\");\n}, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get() {\n const now = Date.now();\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\") === undefined) {\n const delay = __classPrivateFieldGet(this, _PQueue_intervalEnd, \"f\") - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n __classPrivateFieldSet(this, _PQueue_intervalCount, (__classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\")) ? __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") : 0, \"f\");\n }\n else {\n // Act as the interval is pending\n if (__classPrivateFieldGet(this, _PQueue_timeoutId, \"f\") === undefined) {\n __classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onResumeInterval).call(this);\n }, delay), \"f\");\n }\n return true;\n }\n }\n return false;\n}, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother() {\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_emitEvents).call(this);\n return false;\n }\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n const canInitializeInterval = !__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_isIntervalPaused_get);\n if (__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesConcurrentAllowAnother_get)) {\n const job = __classPrivateFieldGet(this, _PQueue_queue, \"f\").dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n }\n return true;\n }\n }\n return false;\n}, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded() {\n if (__classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalId, \"f\") !== undefined) {\n return;\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n }, __classPrivateFieldGet(this, _PQueue_interval, \"f\")), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet(this, _PQueue_interval, \"f\"), \"f\");\n}, _PQueue_onInterval = function _PQueue_onInterval() {\n if (__classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n }\n __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\") ? __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") : 0, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n}, _PQueue_processQueue = function _PQueue_processQueue() {\n // eslint-disable-next-line no-empty\n while (__classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this)) { }\n}, _PQueue_onEvent = async function _PQueue_onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n};\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst cancelablePromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst errorMessage = typeof message === 'string' ? message : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = message instanceof Error ? message : new TimeoutError(errorMessage);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t} finally {\n\t\t\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","\nexport const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read'\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read'\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read'\n\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write'\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write'\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write'\n","export interface WebworkerEventListener {\n (worker: Worker, event: MessageEvent): void\n}\n\nconst events: Record = {}\n\nconst observable = (worker: Worker & { port?: any }) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event)\n })\n\n if (worker.port != null) {\n worker.port.addEventListener('message', (event: any) => {\n observable.dispatchEvent('message', worker, event)\n })\n }\n}\n\nobservable.addEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n events[type] = []\n }\n\n events[type].push(fn)\n}\n\nobservable.removeEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n return\n }\n\n events[type] = events[type]\n .filter(listener => listener === fn)\n}\n\nobservable.dispatchEvent = function (type: string, worker: Worker, event: MessageEvent) {\n if (events[type] == null) {\n return\n }\n\n events[type].forEach(fn => fn(worker, event))\n}\n\nexport default observable\n","import { nanoid } from 'nanoid'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport observer from 'observable-webworkers'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n return await new Promise((resolve) => {\n const releaseEventListener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return await new Promise((resolve) => {\n const listener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK))\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK))\n\n return emitter\n }\n\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK)\n }\n}\n","export { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nexport let nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\n","import PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock: () => Promise\n writeLock: () => Promise\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock: (name: string, options: MorticeOptions) => Mortice['readLock']\n writeLock: (name: string, options: MorticeOptions) => Mortice['writeLock']\n}\n\nconst mutexes: Record = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required): Promise {\n let res: (release: Release) => void\n\n const p = new Promise((resolve) => {\n res = resolve\n })\n\n void queue.add(async () => await pTimeout((async () => {\n return await new Promise((resolve) => {\n res(() => {\n resolve()\n })\n })\n })(), {\n milliseconds: options.timeout\n }))\n\n return await p\n}\n\nconst createMutex = (name: string, options: Required): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\n return {\n async readLock () {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return await createReleaseable(readQueue, options)\n }\n\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start()\n\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n return await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return await readPromise\n },\n async writeLock () {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null\n\n return await createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler: () => Promise\n}\n\nexport default function createMortice (options?: MorticeOptions) {\n const opts: Required = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n","import { logger } from '@libp2p/logger'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { Metadata, Peer as PeerPB } from './pb/peer.js'\nimport mortice from 'mortice'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport type { Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:peer-store:store')\n\nconst NAMESPACE_COMMON = '/peers/'\n\nexport interface Store {\n has: (peerId: PeerId) => Promise\n save: (peer: Peer) => Promise\n load: (peerId: PeerId) => Promise\n delete: (peerId: PeerId) => Promise\n merge: (peerId: PeerId, data: Partial) => Promise\n mergeOrCreate: (peerId: PeerId, data: Partial) => Promise\n patch: (peerId: PeerId, data: Partial) => Promise\n patchOrCreate: (peerId: PeerId, data: Partial) => Promise\n all: () => AsyncIterable\n\n lock: {\n readLock: () => Promise<() => void>\n writeLock: () => Promise<() => void>\n }\n}\n\nexport class PersistentStore {\n private components: Components = new Components()\n public lock: any\n\n constructor () {\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n })\n }\n\n init (components: Components) {\n this.components = components\n }\n\n _peerIdToDatastoreKey (peerId: PeerId) {\n if (peerId.type == null) {\n log.error('peerId must be an instance of peer-id to store data')\n throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const b32key = peerId.toCID().toString()\n return new Key(`${NAMESPACE_COMMON}${b32key}`)\n }\n\n async has (peerId: PeerId) {\n return await this.components.getDatastore().has(this._peerIdToDatastoreKey(peerId))\n }\n\n async delete (peerId: PeerId) {\n await this.components.getDatastore().delete(this._peerIdToDatastoreKey(peerId))\n }\n\n async load (peerId: PeerId): Promise {\n const buf = await this.components.getDatastore().get(this._peerIdToDatastoreKey(peerId))\n const peer = PeerPB.decode(buf)\n const metadata = new Map()\n\n for (const meta of peer.metadata) {\n metadata.set(meta.key, meta.value)\n }\n\n return {\n ...peer,\n id: peerId,\n addresses: peer.addresses.map(({ multiaddr, isCertified }) => {\n return {\n multiaddr: new Multiaddr(multiaddr),\n isCertified: isCertified ?? false\n }\n }),\n metadata,\n pubKey: peer.pubKey ?? undefined,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined\n }\n }\n\n async save (peer: Peer) {\n if (peer.pubKey != null && peer.id.publicKey != null && !uint8arrayEquals(peer.pubKey, peer.id.publicKey)) {\n log.error('peer publicKey bytes do not match peer id publicKey bytes')\n throw errcode(new Error('publicKey bytes do not match peer id publicKey bytes'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // dedupe addresses\n const addressSet = new Set()\n const addresses = peer.addresses\n .filter(address => {\n if (addressSet.has(address.multiaddr.toString())) {\n return false\n }\n\n addressSet.add(address.multiaddr.toString())\n return true\n })\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString())\n })\n .map(({ multiaddr, isCertified }) => ({\n multiaddr: multiaddr.bytes,\n isCertified\n }))\n\n const metadata: Metadata[] = []\n\n ;[...peer.metadata.keys()].sort().forEach(key => {\n const value = peer.metadata.get(key)\n\n if (value != null) {\n metadata.push({ key, value })\n }\n })\n\n const buf = PeerPB.encode({\n addresses,\n protocols: peer.protocols.sort(),\n pubKey: peer.pubKey,\n metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope\n })\n\n await this.components.getDatastore().put(this._peerIdToDatastoreKey(peer.id), buf.subarray())\n\n return await this.load(peer.id)\n }\n\n async patch (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._patch(peerId, data, peer)\n }\n\n async patchOrCreate (peerId: PeerId, data: Partial) {\n let peer: Peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._patch(peerId, data, peer)\n }\n\n async _patch (peerId: PeerId, data: Partial, peer: Peer) {\n return await this.save({\n ...peer,\n ...data,\n id: peerId\n })\n }\n\n async merge (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._merge(peerId, data, peer)\n }\n\n async mergeOrCreate (peerId: PeerId, data: Partial) {\n /** @type {Peer} */\n let peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._merge(peerId, data, peer)\n }\n\n async _merge (peerId: PeerId, data: Partial, peer: Peer) {\n // if the peer has certified addresses, use those in\n // favour of the supplied versions\n const addresses = new Map()\n\n peer.addresses.forEach((addr) => {\n addresses.set(addr.multiaddr.toString(), addr.isCertified)\n })\n\n ;(data.addresses ?? []).forEach(addr => {\n const addrString = addr.multiaddr.toString()\n const isAlreadyCertified = Boolean(addresses.get(addrString))\n\n const isCertified = isAlreadyCertified || addr.isCertified\n\n addresses.set(addrString, isCertified)\n })\n\n return await this.save({\n id: peerId,\n addresses: Array.from(addresses.entries()).map(([addrStr, isCertified]) => {\n return {\n multiaddr: new Multiaddr(addrStr),\n isCertified\n }\n }),\n protocols: Array.from(new Set([\n ...(peer.protocols ?? []),\n ...(data.protocols ?? [])\n ])),\n metadata: new Map([\n ...(peer.metadata?.entries() ?? []),\n ...(data.metadata?.entries() ?? [])\n ]),\n pubKey: data.pubKey ?? (peer != null ? peer.pubKey : undefined),\n peerRecordEnvelope: data.peerRecordEnvelope ?? (peer != null ? peer.peerRecordEnvelope : undefined)\n })\n }\n\n async * all () {\n for await (const key of this.components.getDatastore().queryKeys({\n prefix: NAMESPACE_COMMON\n })) {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2]\n const buf = base32.decode(base32Str)\n\n yield this.load(peerIdFromBytes(buf))\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Tags {\n tags: Tag[]\n}\n\nexport namespace Tags {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.tags != null) {\n for (const value of obj.tags) {\n writer.uint32(10)\n Tag.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"tags\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n tags: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.tags.push(Tag.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tags): Uint8Array => {\n return encodeMessage(obj, Tags.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tags => {\n return decodeMessage(buf, Tags.codec())\n }\n}\n\nexport interface Tag {\n name: string\n value?: number\n expiry?: bigint\n}\n\nexport namespace Tag {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.name != null) {\n writer.uint32(10)\n writer.string(obj.name)\n } else {\n throw new Error('Protocol error: required field \"name\" was not found in object')\n }\n\n if (obj.value != null) {\n writer.uint32(16)\n writer.uint32(obj.value)\n }\n\n if (obj.expiry != null) {\n writer.uint32(24)\n writer.uint64(obj.expiry)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n name: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.name = reader.string()\n break\n case 2:\n obj.value = reader.uint32()\n break\n case 3:\n obj.expiry = reader.uint64()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.name == null) {\n throw new Error('Protocol error: value for required field \"name\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tag): Uint8Array => {\n return encodeMessage(obj, Tag.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tag => {\n return decodeMessage(buf, Tag.codec())\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { PeerStoreAddressBook } from './address-book.js'\nimport { PeerStoreKeyBook } from './key-book.js'\nimport { PeerStoreMetadataBook } from './metadata-book.js'\nimport { PeerStoreProtoBook } from './proto-book.js'\nimport { PersistentStore, Store } from './store.js'\nimport type { PeerStore, AddressBook, KeyBook, MetadataBook, ProtoBook, PeerStoreEvents, PeerStoreInit, Peer, TagOptions } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { Components, Initializable } from '@libp2p/components'\nimport errCode from 'err-code'\nimport { Tag, Tags } from './pb/tags.js'\n\nconst log = logger('libp2p:peer-store')\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nexport class PersistentPeerStore extends EventEmitter implements PeerStore, Initializable {\n public addressBook: AddressBook\n public keyBook: KeyBook\n public metadataBook: MetadataBook\n public protoBook: ProtoBook\n\n private components: Components = new Components()\n private readonly store: Store\n\n constructor (init: PeerStoreInit = {}) {\n super()\n\n this.store = new PersistentStore()\n this.addressBook = new PeerStoreAddressBook(this.dispatchEvent.bind(this), this.store, init.addressFilter)\n this.keyBook = new PeerStoreKeyBook(this.dispatchEvent.bind(this), this.store)\n this.metadataBook = new PeerStoreMetadataBook(this.dispatchEvent.bind(this), this.store)\n this.protoBook = new PeerStoreProtoBook(this.dispatchEvent.bind(this), this.store)\n }\n\n init (components: Components) {\n this.components = components\n ;(this.store as PersistentStore).init(components)\n }\n\n async forEach (fn: (peer: Peer) => void) {\n log.trace('getPeers await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getPeers got read lock')\n\n try {\n for await (const peer of this.store.all()) {\n if (peer.id.equals(this.components.getPeerId())) {\n // Skip self peer if present\n continue\n }\n\n fn(peer)\n }\n } finally {\n log.trace('getPeers release read lock')\n release()\n }\n }\n\n async all (): Promise {\n const output: Peer[] = []\n\n await this.forEach(peer => {\n output.push(peer)\n })\n\n return output\n }\n\n /**\n * Delete the information of the given peer in every book\n */\n async delete (peerId: PeerId) {\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n try {\n await this.store.delete(peerId)\n } finally {\n log.trace('delete release write lock')\n release()\n }\n }\n\n /**\n * Get the stored information of a given peer\n */\n async get (peerId: PeerId) {\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n return await this.store.load(peerId)\n } finally {\n log.trace('get release read lock')\n release()\n }\n }\n\n /**\n * Returns true if we have a record of the peer\n */\n async has (peerId: PeerId) {\n log.trace('has await read lock')\n const release = await this.store.lock.readLock()\n log.trace('has got read lock')\n\n try {\n return await this.store.has(peerId)\n } finally {\n log.trace('has release read lock')\n release()\n }\n }\n\n async tagPeer (peerId: PeerId, tag: string, options: TagOptions = {}) {\n const providedValue = options.value ?? 0\n const value = Math.round(providedValue)\n const ttl = options.ttl ?? undefined\n\n if (value !== providedValue || value < 0 || value > 100) {\n throw errCode(new Error('Tag value must be between 0-100'), 'ERR_TAG_VALUE_OUT_OF_BOUNDS')\n }\n\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n for (const t of tags) {\n if (t.name === tag) {\n throw errCode(new Error('Peer already tagged'), 'ERR_DUPLICATE_TAG')\n }\n }\n\n tags.push({\n name: tag,\n value,\n expiry: ttl == null ? undefined : BigInt(Date.now() + ttl)\n })\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async unTagPeer (peerId: PeerId, tag: string) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n tags = tags.filter(t => t.name !== tag)\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async getTags (peerId: PeerId) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n const now = BigInt(Date.now())\n const unexpiredTags = tags.filter(tag => tag.expiry == null || tag.expiry > now)\n\n if (unexpiredTags.length !== tags.length) {\n // remove any expired tags\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags: unexpiredTags }).subarray())\n }\n\n return unexpiredTags.map(t => ({\n name: t.name,\n value: t.value ?? 0\n }))\n }\n}\n","import drain from 'it-drain'\nimport errCode from 'err-code'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { CID } from 'multiformats/cid'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTContentRouting implements ContentRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async provide (cid: CID) {\n await drain(this.dht.provide(cid))\n }\n\n async * findProviders (cid: CID, options: AbortOptions = {}) {\n for await (const event of this.dht.findProviders(cid, options)) {\n if (event.name === 'PROVIDER') {\n yield * event.providers\n }\n }\n }\n\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise {\n await drain(this.dht.put(key, value, options))\n }\n\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n for await (const event of this.dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n}\n","import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { logger } from '@libp2p/logger'\nimport type { Components } from '@libp2p/components'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:dialer:auto-dialer')\n\nexport interface AutoDialerInit {\n enabled: boolean\n minConnections: number\n dialTimeout: number\n}\n\nexport class AutoDialer {\n private readonly components: Components\n private readonly enabled: boolean\n private readonly minConnections: number\n private readonly dialTimeout: number\n\n constructor (components: Components, init: AutoDialerInit) {\n this.components = components\n this.enabled = init.enabled\n this.minConnections = init.minConnections\n this.dialTimeout = init.dialTimeout\n }\n\n public handle (evt: CustomEvent) {\n const { detail: peer } = evt\n\n if (!this.enabled) {\n return\n }\n\n const connections = this.components.getConnectionManager().getConnections(peer.id)\n\n // If auto dialing is on and we have no connection to the peer, check if we should dial\n if (connections.length === 0) {\n const minConnections = this.minConnections ?? 0\n\n const allConnections = this.components.getConnectionManager().getConnections()\n\n if (minConnections > allConnections.length) {\n log('auto-dialing discovered peer %p with timeout %d', peer.id, this.dialTimeout)\n\n const controller = new TimeoutController(this.dialTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n void this.components.getConnectionManager().openConnection(peer.id, {\n signal: controller.signal\n })\n .catch(err => {\n log.error('could not connect to discovered peer %p with %o', peer.id, err)\n })\n .finally(() => {\n controller.clear()\n })\n }\n }\n }\n}\n","const globalFetch = globalThis.fetch;\nconst globalHeaders = globalThis.Headers;\nconst globalRequest = globalThis.Request;\nconst globalResponse = globalThis.Response;\nexport {\n globalFetch as fetch\n};\nexport {\n globalHeaders as Headers\n};\nexport {\n globalRequest as Request\n};\nexport {\n globalResponse as Response\n};","import { fetch as nativeFetch, Headers } from 'native-fetch'\n\n/**\n * Build fetch resource for request\n */\nexport function buildResource (serverResolver: string, hostname: string, recordType: string) {\n return `${serverResolver}?name=${hostname}&type=${recordType}`\n}\n\nexport interface DNSJSON {\n Question: Question[]\n Answer: Answer[]\n}\n\ninterface Question {\n name: string\n type: number\n}\n\ninterface Answer {\n name: string\n type: number\n data: string\n TTL: number\n}\n\n/**\n * Use fetch to find the record\n */\nexport async function request (resource: string, signal: AbortSignal) {\n const req = await nativeFetch(resource, {\n headers: new Headers({\n accept: 'application/dns-json'\n }),\n signal\n })\n const res = await req.json()\n\n return res as DNSJSON\n}\n\n/**\n * Creates cache key composed by recordType and hostname\n *\n * @param {string} hostname\n * @param {string} recordType\n */\nexport function getCacheKey (hostname: string, recordType: string) {\n return `${recordType}_${hostname}`\n}\n","import debug from 'debug'\nimport Receptacle from 'receptacle'\nimport * as utils from './utils.js'\nimport type { DNSJSON } from './utils'\n\nconst log = Object.assign(debug('dns-over-http-resolver'), {\n error: debug('dns-over-http-resolver:error')\n})\n\nexport interface Request { (resource: string, signal: AbortSignal): Promise }\n\ninterface ResolverOptions {\n maxCache?: number\n request?: Request\n}\n\n/**\n * DNS over HTTP resolver.\n * Uses a list of servers to resolve DNS records with HTTP requests.\n */\nclass Resolver {\n private readonly _cache: Receptacle\n private readonly _TXTcache: Receptacle\n private _servers: string[]\n private readonly _request: Request\n private _abortControllers: AbortController[]\n\n /**\n * @class\n * @param {object} [options]\n * @param {number} [options.maxCache = 100] - maximum number of cached dns records\n * @param {Request} [options.request] - function to return DNSJSON\n */\n constructor (options: ResolverOptions = {}) {\n this._cache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._TXTcache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._servers = [\n 'https://cloudflare-dns.com/dns-query',\n 'https://dns.google/resolve'\n ]\n this._request = options.request ?? utils.request\n this._abortControllers = []\n }\n\n /**\n * Cancel all outstanding DNS queries made by this resolver. Any outstanding\n * requests will be aborted and promises rejected.\n */\n cancel () {\n this._abortControllers.forEach(controller => controller.abort())\n }\n\n /**\n * Get an array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n getServers () {\n return this._servers\n }\n\n /**\n * Get a shuffled array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n _getShuffledServers () {\n const newServers = [...this._servers]\n\n for (let i = newServers.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i)\n const temp = newServers[i]\n newServers[i] = newServers[j]\n newServers[j] = temp\n }\n\n return newServers\n }\n\n /**\n * Sets the IP address and port of servers to be used when performing DNS resolution.\n *\n * @param {string[]} servers - array of RFC 5952 formatted addresses.\n */\n setServers (servers: string[]) {\n this._servers = servers\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into the appropriate DNS record\n *\n * @param {string} hostname - host name to resolve\n * @param {string} [rrType = 'A'] - resource record type\n */\n async resolve (hostname: string, rrType = 'A') {\n switch (rrType) {\n case 'A':\n return await this.resolve4(hostname)\n case 'AAAA':\n return await this.resolve6(hostname)\n case 'TXT':\n return await this.resolveTxt(hostname)\n default:\n throw new Error(`${rrType} is not supported`)\n }\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv4 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve4 (hostname: string) {\n const recordType = 'A'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryA ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv6 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve6 (hostname: string) {\n const recordType = 'AAAA'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryAaaa ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into a Text record\n *\n * @param {string} hostname - host name to resolve\n */\n async resolveTxt (hostname: string) {\n const recordType = 'TXT'\n const cached = this._TXTcache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => [a.data.replace(/['\"]+/g, '')])\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._TXTcache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryTxt ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n clearCache () {\n this._cache.clear()\n this._TXTcache.clear()\n }\n}\n\nexport default Resolver\n","import dns from 'dns-over-http-resolver'\n\nexport default dns\n","import { getProtocol } from '../protocols-table.js'\nimport Resolver from './dns.js'\nimport type { AbortOptions, Multiaddr } from '../index.js'\n\nconst { code: dnsaddrCode } = getProtocol('dnsaddr')\n\n/**\n * Resolver for dnsaddr addresses.\n */\nexport async function dnsaddrResolver (addr: Multiaddr, options: AbortOptions = {}) {\n const resolver = new Resolver()\n\n if (options.signal != null) {\n options.signal.addEventListener('abort', () => {\n resolver.cancel()\n })\n }\n\n const peerId = addr.getPeerId()\n const [, hostname] = addr.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? []\n\n if (hostname == null) {\n throw new Error('No hostname found in multiaddr')\n }\n\n const records = await resolver.resolveTxt(`_dnsaddr.${hostname}`)\n\n let addresses = records.flat().map((a) => a.split('=')[1])\n\n if (peerId != null) {\n addresses = addresses.filter((entry) => entry.includes(peerId))\n }\n\n return addresses\n}\n","import mergeOptions from 'merge-options'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport * as Constants from './constants.js'\nimport { AGENT_VERSION } from './identify/consts.js'\nimport * as RelayConstants from './circuit/constants.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { FaultTolerance } from './transport-manager.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Libp2pInit } from './index.js'\nimport { codes, messages } from './errors.js'\nimport errCode from 'err-code'\nimport type { RecursivePartial } from '@libp2p/interfaces'\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'\n\nconst DefaultConfig: Partial = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs: Multiaddr[]) => multiaddrs\n },\n connectionManager: {\n maxConnections: 300,\n minConnections: 50,\n autoDial: true,\n autoDialInterval: 10000,\n maxParallelDials: Constants.MAX_PARALLEL_DIALS,\n maxDialsPerPeer: Constants.MAX_PER_PEER_DIALS,\n dialTimeout: Constants.DIAL_TIMEOUT,\n inboundUpgradeTimeout: Constants.INBOUND_UPGRADE_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n },\n addressSorter: publicAddressesFirst\n },\n connectionGater: {},\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n },\n metrics: {\n enabled: false,\n computeThrottleMaxQueueSize: 1000,\n computeThrottleTimeout: 2000,\n movingAverageIntervals: [\n 60 * 1000, // 1 minute\n 5 * 60 * 1000, // 5 minutes\n 15 * 60 * 1000 // 15 minutes\n ],\n maxOldPeersRetention: 50\n },\n peerRouting: {\n refreshManager: {\n enabled: true,\n interval: 6e5,\n bootDelay: 10e3\n }\n },\n nat: {\n enabled: true,\n ttl: 7200,\n keepAlive: true\n },\n relay: {\n enabled: true,\n advertise: {\n bootDelay: RelayConstants.ADVERTISE_BOOT_DELAY,\n enabled: false,\n ttl: RelayConstants.ADVERTISE_TTL\n },\n hop: {\n enabled: false,\n active: false,\n timeout: 30000\n },\n autoRelay: {\n enabled: false,\n maxListeners: 2\n }\n },\n identify: {\n protocolPrefix: 'ipfs',\n host: {\n agentVersion: AGENT_VERSION\n },\n // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48\n timeout: 60000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxPushIncomingStreams: 1,\n maxPushOutgoingStreams: 1\n },\n ping: {\n protocolPrefix: 'ipfs',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n },\n fetch: {\n protocolPrefix: 'libp2p',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n }\n}\n\nexport function validateConfig (opts: RecursivePartial): Libp2pInit {\n const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts)\n\n if (resultingOptions.transports == null || resultingOptions.transports.length < 1) {\n throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED)\n }\n\n if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) {\n throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED)\n }\n\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED)\n }\n\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (resultingOptions.identify.host.agentVersion === AGENT_VERSION) {\n if (isNode || isElectronMain) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.process.version}`\n } else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`\n }\n }\n\n return resultingOptions\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerIdProto {\n id: Uint8Array\n pubKey?: Uint8Array\n privKey?: Uint8Array\n}\n\nexport namespace PeerIdProto {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.id != null) {\n writer.uint32(10)\n writer.bytes(obj.id)\n } else {\n throw new Error('Protocol error: required field \"id\" was not found in object')\n }\n\n if (obj.pubKey != null) {\n writer.uint32(18)\n writer.bytes(obj.pubKey)\n }\n\n if (obj.privKey != null) {\n writer.uint32(26)\n writer.bytes(obj.privKey)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n id: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.pubKey = reader.bytes()\n break\n case 3:\n obj.privKey = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.id == null) {\n throw new Error('Protocol error: value for required field \"id\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerIdProto): Uint8Array => {\n return encodeMessage(obj, PeerIdProto.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerIdProto => {\n return decodeMessage(buf, PeerIdProto.codec())\n }\n}\n","import { generateKeyPair, marshalPrivateKey, unmarshalPrivateKey, marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { peerIdFromKeys, peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerIdProto } from './proto.js'\nimport type { PublicKey, PrivateKey } from '@libp2p/interface-keys'\nimport type { RSAPeerId, Ed25519PeerId, Secp256k1PeerId, PeerId } from '@libp2p/interface-peer-id'\n\nexport const createEd25519PeerId = async (): Promise => {\n const key = await generateKeyPair('Ed25519')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'Ed25519') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createSecp256k1PeerId = async (): Promise => {\n const key = await generateKeyPair('secp256k1')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'secp256k1') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createRSAPeerId = async (opts?: { bits: number }): Promise => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048)\n const id = await createFromPrivKey(key)\n\n if (id.type === 'RSA') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport async function createFromPubKey (publicKey: PublicKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(publicKey))\n}\n\nexport async function createFromPrivKey (privateKey: PrivateKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey))\n}\n\nexport function exportToProtobuf (peerId: RSAPeerId | Ed25519PeerId | Secp256k1PeerId, excludePrivateKey?: boolean): Uint8Array {\n return PeerIdProto.encode({\n id: peerId.multihash.bytes,\n pubKey: peerId.publicKey,\n privKey: excludePrivateKey === true || peerId.privateKey == null ? undefined : peerId.privateKey\n })\n}\n\nexport async function createFromProtobuf (buf: Uint8Array) {\n const {\n id,\n privKey,\n pubKey\n } = PeerIdProto.decode(buf)\n\n return await createFromParts(\n id,\n privKey,\n pubKey\n )\n}\n\nexport async function createFromJSON (obj: { id: string, privKey?: string, pubKey?: string }) {\n return await createFromParts(\n uint8ArrayFromString(obj.id, 'base58btc'),\n obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined,\n obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined\n )\n}\n\nasync function createFromParts (multihash: Uint8Array, privKey?: Uint8Array, pubKey?: Uint8Array) {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey)\n\n return await createFromPrivKey(key)\n } else if (pubKey != null) {\n const key = await unmarshalPublicKey(pubKey)\n\n return await createFromPubKey(key)\n }\n\n return peerIdFromBytes(multihash)\n}\n","import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\n\nexport const symbol = Symbol.for('@libp2p/peer-discovery')\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent\n}\n\nexport interface PeerDiscovery extends EventEmitter {\n /**\n * Used to identify the peer discovery mechanism\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isPeerDiscovery function\n */\n [symbol]: true\n}\n\nexport function isPeerDiscovery (other: any): other is PeerDiscovery {\n return other != null && Boolean(other[symbol])\n}\n","import type { DualDHT, QueryEvent, SingleDHT } from '@libp2p/interface-dht'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { symbol } from '@libp2p/interface-peer-discovery'\n\nexport class DummyDHT extends EventEmitter implements DualDHT {\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/dummy-dht'\n }\n\n get wan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get lan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findProviders (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findPeer (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n getClosestPeers (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n provide (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n put (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async getMode (): Promise<'client' | 'server'> {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async setMode (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async refreshRoutingTable (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n}\n","import { EventEmitter } from '@libp2p/interfaces/events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign } from '@libp2p/interface-pubsub'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\n\nexport class DummyPubSub extends EventEmitter implements PubSub {\n isStarted (): boolean {\n return false\n }\n\n start (): void | Promise {\n\n }\n\n stop (): void | Promise {\n\n }\n\n get globalSignaturePolicy (): typeof StrictSign | typeof StrictNoSign {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n get multicodecs (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getPeers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getTopics (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n subscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n unsubscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getSubscribers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n async publish (): Promise {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n}\n","import { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport { Startable, isStartable } from '@libp2p/interfaces/startable'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { MemoryDatastore } from 'datastore-core/memory'\nimport { DefaultPeerRouting } from './peer-routing.js'\nimport { CompoundContentRouting } from './content-routing/index.js'\nimport { getPeer } from './get-peer.js'\nimport { codes } from './errors.js'\nimport { DefaultAddressManager } from './address-manager/index.js'\nimport { DefaultConnectionManager } from './connection-manager/index.js'\nimport { AutoDialler } from './connection-manager/auto-dialler.js'\nimport { Circuit } from './circuit/transport.js'\nimport { Relay } from './circuit/index.js'\nimport { KeyChain } from './keychain/index.js'\nimport { DefaultMetrics } from './metrics/index.js'\nimport { DefaultTransportManager } from './transport-manager.js'\nimport { DefaultUpgrader } from './upgrader.js'\nimport { DefaultRegistrar } from './registrar.js'\nimport { IdentifyService } from './identify/index.js'\nimport { FetchService } from './fetch/index.js'\nimport { PingService } from './ping/index.js'\nimport { NatManager } from './nat-manager.js'\nimport { PeerRecordUpdater } from './peer-record-updater.js'\nimport { DHTPeerRouting } from './dht/dht-peer-routing.js'\nimport { PersistentPeerStore } from '@libp2p/peer-store'\nimport { DHTContentRouting } from './dht/dht-content-routing.js'\nimport { AutoDialer } from './connection-manager/dialer/auto-dialer.js'\nimport { Initializable, Components, isInitializable } from '@libp2p/components'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Libp2p, Libp2pEvents, Libp2pInit, Libp2pOptions } from './index.js'\nimport { validateConfig } from './config.js'\nimport { createEd25519PeerId } from '@libp2p/peer-id-factory'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport errCode from 'err-code'\nimport { unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport { DummyDHT } from './dht/dummy-dht.js'\nimport { DummyPubSub } from './pubsub/dummy-pubsub.js'\nimport { PeerSet } from '@libp2p/peer-collections'\n\nconst log = logger('libp2p')\n\nexport class Libp2pNode extends EventEmitter implements Libp2p {\n public peerId: PeerId\n public dht: DualDHT\n public pubsub: PubSub\n public identifyService?: IdentifyService\n public fetchService: FetchService\n public pingService: PingService\n public components: Components\n public peerStore: PeerStore\n public contentRouting: ContentRouting\n public peerRouting: PeerRouting\n public keychain: KeyChain\n public connectionManager: ConnectionManager\n public registrar: Registrar\n public metrics?: Metrics\n\n private started: boolean\n private readonly services: Startable[]\n private readonly initializables: Initializable[]\n\n constructor (init: Libp2pInit) {\n super()\n\n this.initializables = []\n this.started = false\n this.peerId = init.peerId\n this.components = new Components({\n peerId: init.peerId,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: {\n denyDialPeer: async () => await Promise.resolve(false),\n denyDialMultiaddr: async () => await Promise.resolve(false),\n denyInboundConnection: async () => await Promise.resolve(false),\n denyOutboundConnection: async () => await Promise.resolve(false),\n denyInboundEncryptedConnection: async () => await Promise.resolve(false),\n denyOutboundEncryptedConnection: async () => await Promise.resolve(false),\n denyInboundUpgradedConnection: async () => await Promise.resolve(false),\n denyOutboundUpgradedConnection: async () => await Promise.resolve(false),\n filterMultiaddrForPeer: async () => await Promise.resolve(true),\n ...init.connectionGater\n }\n })\n this.components.setPeerStore(new PersistentPeerStore({\n addressFilter: this.components.getConnectionGater().filterMultiaddrForPeer,\n ...init.peerStore\n }))\n\n this.services = [\n this.components\n ]\n\n // Create Metrics\n if (init.metrics.enabled) {\n this.metrics = this.components.setMetrics(new DefaultMetrics(init.metrics))\n }\n\n this.peerStore = this.components.getPeerStore()\n\n this.peerStore.addEventListener('peer', evt => {\n const { detail: peerData } = evt\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peerData }))\n })\n\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.components.setConnectionProtector(init.connectionProtector)\n }\n\n // Set up the Upgrader\n this.components.setUpgrader(new DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map(component => this.configureComponent(component)),\n muxers: (init.streamMuxers ?? []).map(component => this.configureComponent(component)),\n inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout\n }))\n\n // Create the Connection Manager\n this.connectionManager = this.components.setConnectionManager(new DefaultConnectionManager(init.connectionManager))\n\n // Create the Registrar\n this.registrar = this.components.setRegistrar(new DefaultRegistrar(this.components))\n\n // Setup the transport manager\n this.components.setTransportManager(new DefaultTransportManager(this.components, init.transportManager))\n\n // Addresses {listen, announce, noAnnounce}\n this.components.setAddressManager(new DefaultAddressManager(this.components, init.addresses))\n\n // update our peer record when addresses change\n this.configureComponent(new PeerRecordUpdater(this.components))\n\n this.configureComponent(new AutoDialler(this.components, {\n enabled: init.connectionManager.autoDial,\n minConnections: init.connectionManager.minConnections,\n autoDialInterval: init.connectionManager.autoDialInterval\n }))\n\n // Create keychain\n const keychainOpts = KeyChain.generateOptions()\n this.keychain = this.configureComponent(new KeyChain(this.components, {\n ...keychainOpts,\n ...init.keychain\n }))\n\n // Create the Nat Manager\n this.services.push(new NatManager(this.components, init.nat))\n\n init.transports.forEach((transport) => {\n this.components.getTransportManager().add(this.configureComponent(transport))\n })\n\n // Attach stream multiplexers\n if (init.streamMuxers != null && init.streamMuxers.length > 0) {\n // Add the identify service since we can multiplex\n this.identifyService = new IdentifyService(this.components, {\n ...init.identify\n })\n this.configureComponent(this.identifyService)\n }\n\n // dht provided components (peerRouting, contentRouting, dht)\n if (init.dht != null) {\n this.dht = this.components.setDHT(init.dht)\n } else {\n this.dht = new DummyDHT()\n }\n\n // Create pubsub if provided\n if (init.pubsub != null) {\n this.pubsub = this.components.setPubSub(init.pubsub)\n } else {\n this.pubsub = new DummyPubSub()\n }\n\n // Attach remaining APIs\n // peer and content routing will automatically get modules from _modules and _dht\n\n const peerRouters: PeerRouting[] = (init.peerRouters ?? []).map(component => this.configureComponent(component))\n\n if (init.dht != null) {\n // add dht to routers\n peerRouters.push(this.configureComponent(new DHTPeerRouting(this.dht)))\n\n // use dht for peer discovery\n this.dht.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n\n this.peerRouting = this.components.setPeerRouting(this.configureComponent(new DefaultPeerRouting(this.components, {\n ...init.peerRouting,\n routers: peerRouters\n })))\n\n const contentRouters: ContentRouting[] = (init.contentRouters ?? []).map(component => this.configureComponent(component))\n\n if (init.dht != null) {\n // add dht to routers\n contentRouters.push(this.configureComponent(new DHTContentRouting(this.dht)))\n }\n\n this.contentRouting = this.components.setContentRouting(this.configureComponent(new CompoundContentRouting(this.components, {\n routers: contentRouters\n })))\n\n if (init.relay.enabled) {\n this.components.getTransportManager().add(this.configureComponent(new Circuit(init.relay)))\n\n this.configureComponent(new Relay(this.components, {\n addressSorter: init.connectionManager.addressSorter,\n ...init.relay\n }))\n }\n\n this.fetchService = this.configureComponent(new FetchService(this.components, {\n ...init.fetch\n }))\n\n this.pingService = this.configureComponent(new PingService(this.components, {\n ...init.ping\n }))\n\n const autoDialer = this.configureComponent(new AutoDialer(this.components, {\n enabled: init.connectionManager.autoDial !== false,\n minConnections: init.connectionManager.minConnections,\n dialTimeout: init.connectionManager.dialTimeout ?? 30000\n }))\n\n this.addEventListener('peer:discovery', evt => {\n if (!this.isStarted()) {\n return\n }\n\n autoDialer.handle(evt)\n })\n\n // Discovery modules\n for (const service of init.peerDiscovery ?? []) {\n this.configureComponent(service)\n\n service.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n }\n\n private configureComponent (component: T): T {\n if (isStartable(component)) {\n this.services.push(component)\n }\n\n if (isInitializable(component)) {\n this.initializables.push(component)\n }\n\n return component\n }\n\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start () {\n if (this.started) {\n return\n }\n\n this.started = true\n\n log('libp2p is starting')\n\n try {\n // Set available components on all modules interested in components\n this.initializables.forEach(obj => {\n obj.init(this.components)\n })\n\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStart != null) {\n await service.beforeStart()\n }\n })\n )\n\n // start any startables\n await Promise.all(\n this.services.map(service => service.start())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStart != null) {\n await service.afterStart()\n }\n })\n )\n\n log('libp2p has started')\n } catch (err: any) {\n log.error('An error occurred starting libp2p', err)\n await this.stop()\n throw err\n }\n }\n\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop () {\n if (!this.started) {\n return\n }\n\n log('libp2p is stopping')\n\n this.started = false\n\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStop != null) {\n await service.beforeStop()\n }\n })\n )\n\n await Promise.all(\n this.services.map(servce => servce.stop())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStop != null) {\n await service.afterStop()\n }\n })\n )\n\n log('libp2p has stopped')\n }\n\n isStarted () {\n return this.started\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n return this.components.getConnectionManager().getConnections(peerId)\n }\n\n getPeers (): PeerId[] {\n const peerSet = new PeerSet()\n\n for (const conn of this.components.getConnectionManager().getConnections()) {\n peerSet.add(conn.remotePeer)\n }\n\n return Array.from(peerSet)\n }\n\n async dial (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n\n return await this.components.getConnectionManager().openConnection(id, options)\n }\n\n async dialProtocol (peer: PeerId | Multiaddr, protocols: string | string[], options: AbortOptions = {}) {\n if (protocols == null) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n\n if (protocols.length === 0) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n const connection = await this.dial(peer, options)\n\n return await connection.newStream(protocols, options)\n }\n\n getMultiaddrs (): Multiaddr[] {\n return this.components.getAddressManager().getAddresses()\n }\n\n async hangUp (peer: PeerId | Multiaddr | string): Promise {\n const { id } = getPeer(peer)\n\n await this.components.getConnectionManager().closeConnections(id)\n }\n\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise {\n log('getPublicKey %p', peer)\n\n if (peer.publicKey != null) {\n return peer.publicKey\n }\n\n const peerInfo = await this.peerStore.get(peer)\n\n if (peerInfo.pubKey != null) {\n return peerInfo.pubKey\n }\n\n if (this.dht == null) {\n throw errCode(new Error('Public key was not in the peer store and the DHT is not enabled'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.multihash.digest\n ])\n\n // search the dht\n for await (const event of this.dht.get(peerKey, options)) {\n if (event.name === 'VALUE') {\n const key = unmarshalPublicKey(event.value)\n\n await this.peerStore.keyBook.set(peer, event.value)\n\n return key.bytes\n }\n }\n\n throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD)\n }\n\n async fetch (peer: PeerId | Multiaddr | string, key: string, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (multiaddrs != null) {\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n return await this.fetchService.fetch(id, key, options)\n }\n\n async ping (peer: PeerId | Multiaddr | string, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (multiaddrs.length > 0) {\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n return await this.pingService.ping(id, options)\n }\n\n async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.getRegistrar().handle(protocol, handler, options)\n })\n )\n }\n\n async unhandle (protocols: string[] | string): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.getRegistrar().unhandle(protocol)\n })\n )\n }\n\n /**\n * Called whenever peer discovery services emit `peer` events.\n * Known peers may be emitted.\n */\n onDiscoveryPeer (evt: CustomEvent) {\n const { detail: peer } = evt\n\n if (peer.id.toString() === this.peerId.toString()) {\n log.error(new Error(codes.ERR_DISCOVERED_SELF))\n return\n }\n\n if (peer.multiaddrs.length > 0) {\n void this.components.getPeerStore().addressBook.add(peer.id, peer.multiaddrs).catch(err => log.error(err))\n }\n\n if (peer.protocols.length > 0) {\n void this.components.getPeerStore().protoBook.set(peer.id, peer.protocols).catch(err => log.error(err))\n }\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peer }))\n }\n}\n\n/**\n * Returns a new Libp2pNode instance - this exposes more of the internals than the\n * libp2p interface and is useful for testing and debugging.\n */\nexport async function createLibp2pNode (options: Libp2pOptions): Promise {\n if (options.peerId == null) {\n options.peerId = await createEd25519PeerId()\n }\n\n return new Libp2pNode(validateConfig(options))\n}\n","/**\n * Return pseudo random subset of the input.\n */\nexport function getPseudoRandomSubset(\n values: T[],\n wantedNumber: number\n): T[] {\n if (values.length <= wantedNumber || values.length <= 1) {\n return values;\n }\n\n return shuffle(values).slice(0, wantedNumber);\n}\n\nfunction shuffle(arr: T[]): T[] {\n if (arr.length <= 1) {\n return arr;\n }\n const randInt = (): number => {\n return Math.floor(Math.random() * Math.floor(arr.length));\n };\n\n for (let i = 0; i < arr.length; i++) {\n const j = randInt();\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n return arr;\n}\n","import type {\n PeerDiscovery,\n PeerDiscoveryEvents,\n} from \"@libp2p/interface-peer-discovery\";\nimport { symbol } from \"@libp2p/interface-peer-discovery\";\nimport type { PeerInfo } from \"@libp2p/interface-peer-info\";\nimport { CustomEvent, EventEmitter } from \"@libp2p/interfaces/events\";\nimport { Multiaddr } from \"@multiformats/multiaddr\";\nimport debug from \"debug\";\n\nimport { multiaddrsToPeerInfo } from \"./multiaddr_to_peer_info\";\nimport { getPseudoRandomSubset } from \"./random_subset\";\n\nconst log = debug(\"waku:peer-discovery-static-list\");\n\nexport interface Options {\n /**\n * The maximum of peers to connect to as part of the bootstrap process.\n *\n * @default The length of the passed `peers` array.\n */\n maxPeers?: number;\n /**\n * The interval between emitting addresses in milliseconds.\n *\n * @default {@link PeerDiscoveryEvents.DefaultInterval}\n */\n interval?: number;\n}\n\n/**\n * Parse options and expose function to return bootstrap peer addresses.\n *\n * @throws if an invalid combination of options is passed, see [[BootstrapOptions]] for details.\n */\nexport class PeerDiscoveryStaticPeers\n extends EventEmitter\n implements PeerDiscovery\n{\n static DefaultInterval = 200;\n private readonly peers: PeerInfo[];\n private timer?: ReturnType;\n private readonly interval: number;\n\n /**\n * @param peers Multiaddrs of peers to connect to.\n * @param opts\n */\n constructor(peers: string[] | Multiaddr[], opts?: Options) {\n super();\n\n this.interval = opts?.interval ?? PeerDiscoveryStaticPeers.DefaultInterval;\n const maxPeers = opts?.maxPeers ?? peers?.length;\n\n const peerMas = peers.map((peer: string | Multiaddr) => {\n if (typeof peer === \"string\") {\n return new Multiaddr(peer);\n } else {\n return peer;\n }\n });\n this.peers = multiaddrsToPeerInfo(getPseudoRandomSubset(peerMas, maxPeers));\n log(\n \"Use provided list of peers (reduced to maxPeers)\",\n this.peers.map((ma) => ma.toString())\n );\n }\n\n /**\n * Start emitting static peers.\n */\n start(): void {\n this._startTimer();\n }\n\n private _startTimer(): void {\n if (this.peers) {\n log(\"Starting to emit static peers.\");\n if (this.timer != null) {\n return;\n }\n\n this.timer = setInterval(() => this._returnPeers(), this.interval);\n\n this._returnPeers();\n }\n }\n\n _returnPeers(): void {\n if (this.timer == null) {\n return;\n }\n\n this.peers.forEach((peerData) => {\n this.dispatchEvent(\n new CustomEvent(\"peer\", { detail: peerData })\n );\n });\n }\n\n /**\n * Stop emitting peers.\n */\n stop(): void {\n if (this.timer != null) {\n clearInterval(this.timer);\n }\n\n this.timer = undefined;\n }\n\n get [symbol](): true {\n return true;\n }\n\n get [Symbol.toStringTag](): string {\n return \"@waku/peer-discovery-static-list\";\n }\n}\n","import { PeerInfo } from \"@libp2p/interface-peer-info\";\nimport { peerIdFromString } from \"@libp2p/peer-id\";\nimport { Multiaddr } from \"@multiformats/multiaddr\";\n\nexport function multiaddrsToPeerInfo(mas: Multiaddr[]): PeerInfo[] {\n return mas\n .map((ma) => {\n const peerIdStr = ma.getPeerId();\n const protocols: string[] = [];\n return {\n id: peerIdStr ? peerIdFromString(peerIdStr) : null,\n multiaddrs: [ma.decapsulateCode(421)],\n protocols,\n };\n })\n .filter((peerInfo): peerInfo is PeerInfo => peerInfo.id !== null);\n}\n","import { Multiaddr } from \"@multiformats/multiaddr\";\n\nimport { getPseudoRandomSubset } from \"./random_subset\";\n\nexport const DefaultWantedNumber = 1;\n\nexport enum Fleet {\n Prod = \"prod\",\n Test = \"test\",\n}\n\n/**\n * Return list of pre-defined (hardcoded) bootstrap nodes.\n *\n * Default behavior is to return nodes of the nwaku Status Prod fleet.\n *\n * @param fleet The fleet to be returned. Defaults to production fleet.\n * @param wantedNumber The number of connections desired. Defaults to [[DefaultWantedNumber]].\n *\n * @returns An array of multiaddresses.\n */\nexport function getPredefinedBootstrapNodes(\n fleet: Fleet = Fleet.Prod,\n wantedNumber: number = DefaultWantedNumber\n): Multiaddr[] {\n if (wantedNumber <= 0) {\n return [];\n }\n\n let nodes;\n switch (fleet) {\n case Fleet.Prod:\n nodes = fleets.fleets[\"wakuv2.prod\"][\"waku-websocket\"];\n break;\n case Fleet.Test:\n nodes = fleets.fleets[\"wakuv2.test\"][\"waku-websocket\"];\n break;\n default:\n nodes = fleets.fleets[\"wakuv2.prod\"][\"waku-websocket\"];\n }\n\n nodes = Object.values(nodes) as string[];\n\n nodes = nodes.map((node: string) => new Multiaddr(node));\n return getPseudoRandomSubset(nodes, wantedNumber);\n}\n\nexport const fleets = {\n fleets: {\n \"wakuv2.prod\": {\n \"waku-websocket\": {\n \"node-01.ac-cn-hongkong-c.wakuv2.prod\":\n \"/dns4/node-01.ac-cn-hongkong-c.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAm4v86W3bmT1BiH6oSPzcsSr24iDQpSN5Qa992BCjjwgrD\",\n \"node-01.do-ams3.wakuv2.prod\":\n \"/dns4/node-01.do-ams3.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAmL5okWopX7NqZWBUKVqW8iUxCEmd5GMHLVPwCgzYzQv3e\",\n \"node-01.gc-us-central1-a.wakuv2.prod\":\n \"/dns4/node-01.gc-us-central1-a.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAmVkKntsECaYfefR1V2yCR79CegLATuTPE6B9TxgxBiiiA\",\n },\n },\n \"wakuv2.test\": {\n \"waku-websocket\": {\n \"node-01.ac-cn-hongkong-c.wakuv2.test\":\n \"/dns4/node-01.ac-cn-hongkong-c.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAkvWiyFsgRhuJEb9JfjYxEkoHLgnUQmr1N5mKWnYjxYRVm\",\n \"node-01.do-ams3.wakuv2.test\":\n \"/dns4/node-01.do-ams3.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAmPLe7Mzm8TsYUubgCAW1aJoeFScxrLj8ppHFivPo97bUZ\",\n \"node-01.gc-us-central1-a.wakuv2.test\":\n \"/dns4/node-01.gc-us-central1-a.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAmJb2e28qLXxT5kZxVUUoJt72EMzNGXB47Rxx5hw3q4YjS\",\n },\n },\n },\n};\n","import { Noise } from \"@chainsafe/libp2p-noise\";\nimport type { PeerDiscovery } from \"@libp2p/interface-peer-discovery\";\nimport { Mplex } from \"@libp2p/mplex\";\nimport { WebSockets } from \"@libp2p/websockets\";\nimport { all as filterAll } from \"@libp2p/websockets/filters\";\nimport { createLibp2p, Libp2pOptions } from \"libp2p\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { PeerDiscoveryStaticPeers } from \"./peer_discovery_static_list\";\nimport { getPredefinedBootstrapNodes } from \"./predefined_bootstrap_nodes\";\nimport { Waku, WakuOptions } from \"./waku\";\nimport { WakuFilter } from \"./waku_filter\";\nimport { WakuLightPush } from \"./waku_light_push\";\nimport { WakuRelay } from \"./waku_relay\";\nimport { WakuStore } from \"./waku_store\";\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * One and only one pubsub topic is used by Waku. This is used by:\n * - WakuRelay to receive, route and send messages,\n * - WakuLightPush to send messages,\n * - WakuStore to retrieve messages.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n /**\n * You can pass options to the `Libp2p` instance used by {@link Waku} using the {@link CreateOptions.libp2p} property.\n * This property is the same type than the one passed to [`Libp2p.create`](https://github.com/libp2p/js-libp2p/blob/master/doc/API.md#create)\n * apart that we made the `modules` property optional and partial,\n * allowing its omission and letting Waku set good defaults.\n * Notes that some values are overridden by {@link Waku} to ensure it implements the Waku protocol.\n */\n libp2p?: Partial;\n /**\n * Byte array used as key for the noise protocol used for connection encryption\n * by [`Libp2p.create`](https://github.com/libp2p/js-libp2p/blob/master/doc/API.md#create)\n * This is only used for test purposes to not run out of entropy during CI runs.\n */\n staticNoiseKey?: Uint8Array;\n /**\n * Use recommended bootstrap method to discovery and connect to new nodes.\n */\n defaultBootstrap?: boolean;\n}\n\nexport async function createWaku(\n options?: CreateOptions & WakuOptions\n): Promise {\n const libp2pOptions = options?.libp2p ?? {};\n const peerDiscovery = libp2pOptions.peerDiscovery ?? [];\n if (options?.defaultBootstrap) {\n peerDiscovery.push(defaultPeerDiscovery());\n Object.assign(libp2pOptions, { peerDiscovery });\n }\n\n const libp2p = await defaultLibp2p(new WakuRelay(options), libp2pOptions);\n\n const wakuStore = new WakuStore(libp2p, options);\n const wakuLightPush = new WakuLightPush(libp2p, options);\n const wakuFilter = new WakuFilter(libp2p, options);\n\n return new Waku(options ?? {}, libp2p, wakuStore, wakuLightPush, wakuFilter);\n}\n\nexport function defaultPeerDiscovery(): PeerDiscovery {\n return new PeerDiscoveryStaticPeers(getPredefinedBootstrapNodes());\n}\n\nexport async function defaultLibp2p(\n wakuRelay: WakuRelay,\n options?: Partial\n): Promise {\n const libp2pOpts = Object.assign(\n {\n transports: [new WebSockets({ filter: filterAll })],\n streamMuxers: [new Mplex()],\n connectionEncryption: [new Noise()],\n },\n { pubsub: wakuRelay },\n options ?? {}\n );\n\n return createLibp2p(libp2pOpts);\n}\n","import { createLibp2pNode } from './libp2p.js'\nimport type { AbortOptions, RecursivePartial } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { FaultTolerance } from './transport-manager.js'\nimport type { IdentifyServiceInit } from './identify/index.js'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { Datastore } from 'interface-datastore'\nimport type { PeerStore, PeerStoreInit } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AutoRelayConfig, RelayAdvertiseConfig } from './circuit/index.js'\nimport type { PeerDiscovery } from '@libp2p/interface-peer-discovery'\nimport type { Connection, ConnectionGater, ConnectionProtector, Stream } from '@libp2p/interface-connection'\nimport type { Transport } from '@libp2p/interface-transport'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { Metrics, MetricsInit } from '@libp2p/interface-metrics'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { KeyChain } from './keychain/index.js'\nimport type { ConnectionManagerInit } from './connection-manager/index.js'\nimport type { PingServiceInit } from './ping/index.js'\nimport type { FetchServiceInit } from './fetch/index.js'\n\nexport interface PersistentPeerStoreOptions {\n threshold?: number\n}\n\nexport interface DEKConfig {\n keyLength: number\n iterationCount: number\n salt: string\n hash: string\n}\n\nexport interface KeychainConfig {\n pass?: string\n dek?: DEKConfig\n}\n\nexport interface MetricsConfig {\n enabled?: boolean\n}\n\nexport interface HopConfig {\n enabled?: boolean\n active?: boolean\n timeout: number\n}\n\nexport interface RelayConfig {\n enabled: boolean\n advertise: RelayAdvertiseConfig\n hop: HopConfig\n autoRelay: AutoRelayConfig\n}\n\nexport interface NatManagerConfig {\n enabled: boolean\n externalAddress?: string\n localAddress?: string\n description?: string\n ttl?: number\n keepAlive: boolean\n gateway?: string\n}\n\nexport interface AddressesConfig {\n listen: string[]\n announce: string[]\n noAnnounce: string[]\n announceFilter: (multiaddrs: Multiaddr[]) => Multiaddr[]\n}\n\nexport interface TransportManagerConfig {\n faultTolerance?: FaultTolerance\n}\n\nexport interface PeerStoreConfig {\n persistence?: boolean\n threshold?: number\n}\n\nexport interface PeerRoutingConfig {\n refreshManager: RefreshManagerConfig\n}\n\nexport interface RefreshManagerConfig {\n enabled?: boolean\n interval: number\n bootDelay: number\n}\n\nexport interface Libp2pInit {\n peerId: PeerId\n addresses: AddressesConfig\n connectionManager: ConnectionManagerInit\n connectionGater: Partial\n transportManager: TransportManagerConfig\n datastore: Datastore\n metrics: MetricsInit\n peerStore: PeerStoreInit\n peerRouting: PeerRoutingConfig\n keychain: KeychainConfig\n nat: NatManagerConfig\n relay: RelayConfig\n identify: IdentifyServiceInit\n ping: PingServiceInit\n fetch: FetchServiceInit\n\n transports: Transport[]\n streamMuxers?: StreamMuxerFactory[]\n connectionEncryption?: ConnectionEncrypter[]\n peerDiscovery?: PeerDiscovery[]\n peerRouters?: PeerRouting[]\n contentRouters?: ContentRouting[]\n dht?: DualDHT\n pubsub?: PubSub\n connectionProtector?: ConnectionProtector\n}\n\nexport interface Libp2pEvents {\n 'peer:discovery': CustomEvent\n}\n\nexport interface Libp2p extends Startable, EventEmitter {\n peerId: PeerId\n peerStore: PeerStore\n peerRouting: PeerRouting\n contentRouting: ContentRouting\n keychain: KeyChain\n connectionManager: ConnectionManager\n registrar: Registrar\n metrics?: Metrics\n pubsub: PubSub\n dht: DualDHT\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n */\n getMultiaddrs: () => Multiaddr[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n */\n getConnections: (peerId?: PeerId) => Connection[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers: () => PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`\n */\n dial: (peer: PeerId | Multiaddr, options?: AbortOptions) => Promise\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n */\n dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise\n\n /**\n * Disconnects all connections to the given `peer`\n */\n hangUp: (peer: PeerId | Multiaddr | string) => Promise\n\n /**\n * Registers the `handler` for each protocol\n */\n handle: (protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n unhandle: (protocols: string[] | string) => Promise\n\n /**\n * Pings the given peer in order to obtain the operation latency\n */\n ping: (peer: Multiaddr | PeerId, options?: AbortOptions) => Promise\n\n /**\n * Sends a request to fetch the value associated with the given key from the given peer.\n */\n fetch: (peer: PeerId | Multiaddr | string, key: string, options?: AbortOptions) => Promise\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA' type\n * this may mean searching the DHT if the key is not present in the KeyStore.\n */\n getPublicKey: (peer: PeerId, options?: AbortOptions) => Promise\n}\n\nexport type Libp2pOptions = RecursivePartial\n\n/**\n * Returns a new instance of the Libp2p interface, generating a new PeerId\n * if one is not passed as part of the options.\n */\nexport async function createLibp2p (options: Libp2pOptions): Promise {\n return await createLibp2pNode(options)\n}\n","import {WakuMessage, waitForRemotePeer} from \"js-waku\";\nimport * as React from \"react\";\nimport protobuf from \"protobufjs\";\nimport {createWaku} from \"js-waku/lib/create_waku\";\n\nconst ContentTopic = `/relay-reactjs-chat/1/chat/proto`;\n\nconst SimpleChatMessage = new protobuf.Type(\"SimpleChatMessage\")\n .add(new protobuf.Field(\"timestamp\", 1, \"uint32\"))\n .add(new protobuf.Field(\"text\", 2, \"string\"));\n\nfunction App() {\n const [waku, setWaku] = React.useState(undefined);\n const [wakuStatus, setWakuStatus] = React.useState(\"None\");\n // Using a counter just for the messages to be different\n const [sendCounter, setSendCounter] = React.useState(0);\n const [messages, setMessages] = React.useState([]);\n\n React.useEffect(() => {\n if (!!waku) return;\n if (wakuStatus !== \"None\") return;\n\n setWakuStatus(\"Starting\");\n (async () => {\n\n const waku = await createWaku({defaultBootstrap: true})\n\n setWaku(waku);\n await waku.start();\n setWakuStatus(\"Connecting\");\n await waitForRemotePeer(waku, [\"relay\"]);\n setWakuStatus(\"Ready\");\n })();\n }, [waku, wakuStatus]);\n\n const processIncomingMessage = React.useCallback((wakuMessage) => {\n if (!wakuMessage.payload) return;\n\n const {text, timestamp} = SimpleChatMessage.decode(wakuMessage.payload);\n\n const time = new Date();\n\n time.setTime(timestamp);\n const message = {text, timestamp: time};\n\n setMessages((messages) => {\n return [message].concat(messages);\n });\n }, []);\n\n React.useEffect(() => {\n if (!waku) return;\n\n // Pass the content topic to only process messages related to your dApp\n waku.relay.addObserver(processIncomingMessage, [ContentTopic]);\n\n // `cleanUp` is called when the component is unmounted, see ReactJS doc.\n return function cleanUp() {\n waku.relay.deleteObserver(processIncomingMessage, [ContentTopic]);\n };\n }, [waku, wakuStatus, processIncomingMessage]);\n\n const sendMessageOnClick = () => {\n // Check Waku is started and connected first.\n if (wakuStatus !== \"Ready\") return;\n\n sendMessage(`Here is message #${sendCounter}`, waku, new Date()).then(() =>\n console.log(\"Message sent\")\n );\n\n // For demonstration purposes.\n setSendCounter(sendCounter + 1);\n };\n\n return (\n
\n
\n

{wakuStatus}

\n \n
    \n {messages.map((msg) => {\n return (\n
  • \n

    \n {msg.timestamp.toString()}: {msg.text}\n

    \n
  • \n );\n })}\n
\n
\n
\n );\n}\n\nfunction sendMessage(message, waku, timestamp) {\n const time = timestamp.getTime();\n\n // Encode to protobuf\n const protoMsg = SimpleChatMessage.create({\n timestamp: time,\n text: message,\n });\n const payload = SimpleChatMessage.encode(protoMsg).finish();\n\n // Wrap in a Waku Message\n return WakuMessage.fromBytes(payload, ContentTopic).then((wakuMessage) =>\n // Send over Waku Relay\n waku.relay.send(wakuMessage)\n );\n}\n\nexport default App;\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './index.css';\nimport App from './App';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n \n \n \n);\n"],"names":["module","exports","protobuf","configure","util","_configure","Writer","BufferWriter","Reader","BufferReader","build","require","rpc","roots","LongBits","utf8","indexOutOfRange","reader","writeLength","RangeError","pos","len","buffer","this","buf","length","create_array","Uint8Array","Array","isArray","Error","create","Buffer","isBuffer","readLongVarint","bits","i","lo","hi","readFixed32_end","end","readFixed64","prototype","_slice","subarray","slice","uint32","value","int32","sint32","bool","fixed32","sfixed32","float","readFloatLE","double","readDoubleLE","bytes","start","constructor","call","string","read","skip","skipType","wireType","BufferReader_","fn","Long","merge","int64","uint64","sint64","zzDecode","fixed64","sfixed64","Object","utf8Slice","Math","min","toString","Service","rpcImpl","requestDelimited","responseDelimited","TypeError","EventEmitter","Boolean","rpcCall","method","requestCtor","responseCtor","request","callback","self","asPromise","finish","err","response","emit","setTimeout","endedByRPC","off","zero","toNumber","zzEncode","zeroHash","fromNumber","sign","from","isString","parseInt","fromString","low","high","unsigned","toLong","charCodeAt","String","fromHash","hash","toHash","fromCharCode","mask","part0","part1","part2","dst","src","ifNotSet","keys","undefined","newError","name","CustomError","message","properties","defineProperty","get","captureStackTrace","stack","base64","inquire","pool","isNode","global","process","versions","node","window","emptyArray","freeze","emptyObject","isInteger","Number","isFinite","floor","isObject","isset","isSet","obj","prop","hasOwnProperty","utf8Write","e","_Buffer_from","_Buffer_allocUnsafe","newBuffer","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","lcFirst","str","charAt","toLowerCase","substring","ProtocolError","oneOfGetter","fieldNames","fieldMap","oneOfSetter","toJSONOptions","longs","enums","json","encoding","allocUnsafe","size","Op","val","next","noop","State","writer","head","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","alloc","_push","writeFloatLE","writeDoubleLE","writeBytes","set","decode","write","fork","reset","ldelim","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength","ctx","params","arguments","offset","index","pending","Promise","resolve","reject","apply","p","n","ceil","b64","s64","encode","t","parts","chunk","j","b","push","join","invalidEncoding","c","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","verbose","console","log","scopeKeys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","JSON","stringify","functionNameOverride","_listeners","on","evt","listeners","splice","args","fetch","fs","filename","options","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","responseText","overrideMimeType","responseType","open","send","factory","Float32Array","f32","f8b","le","writeFloat_f32_cpy","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatBE","readFloatBE","writeFloat_ieee754","writeUint","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleBE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","moduleName","mod","eval","path","isAbsolute","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","SIZE","MAX","slab","c1","c2","writeUint16BE","out","writeUint16LE","readInt32BE","array","readUint32BE","readInt32LE","readUint32LE","writeUint32BE","writeUint32LE","writeUint64BE","writeUint64LE","bitLength","result","mul","int_1","div","DataView","byteOffset","getFloat32","getFloat64","setFloat32","setFloat64","core","input","key","j0","j1","j2","j3","j4","j5","j6","j7","j8","j9","j10","j11","j12","j13","j14","j15","x0","x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13","x14","x15","binary_1","streamXOR","nonce","nonceInplaceCounterLength","nc","counterLength","block","incrementCounter","wipe_1","counter","carry","ZEROS","nonceLength","tagLength","_key","ChaCha20Poly1305","plaintext","associatedData","authKey","chacha_1","resultLength","_authenticate","sealed","calculatedTag","constant_time_1","tagOut","ciphertext","h","poly1305_1","update","tag","digest","clean","compare","a","subject","resultIfOne","resultIfZero","saveState","restoreState","cleanSavedState","salt","info","_counter","_hash","_info","okm","hmac_1","_hmac","_buffer","digestLength","_bufpos","HKDF","ctr","_fillBuffer","_finished","_inner","_outer","blockSize","pad","hash_1","_innerKeyedState","_outerKeyedState","HMAC","data","savedState","imul","al","bl","x","_r","Uint16Array","_h","_pad","_leftover","_fin","t0","t1","t2","t3","t4","t5","t6","t7","Poly1305","m","mpos","hibit","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","mac","macpos","f","g","_blocks","want","randomBytes","prng","system_1","wipe","ALPHANUMERIC","randomString","charset","charsLen","maxByte","randomByte","isAvailable","isInstantiated","browserCrypto","crypto","msCrypto","getRandomValues","_crypto","nodeCrypto","_source","browser_1","node_1","_state","Int32Array","_temp","_bufferLength","_bytesHashed","SHA256","_initState","dataLength","dataPos","hashBlocks","bytesHashed","left","bitLenHi","bitLenLo","padLength","state","bufferLength","K","w","v","d","u","gf","init","r","_9","_121665","car25519","o","sel25519","q","add","sub","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","square","scalarMult","z","unpack25519","x32","x16","inp","inv25519","pack25519","scalarMultBase","generateKeyPairFromSeed","seed","secretKey","publicKey","mySecretKey","theirPublicKey","rejectZero","zeros","anySignal","signals","controller","globalThis","AbortController","onAbort","abort","signal","removeEventListener","addEventListener","aborted","s","y","plural","ms","msAbs","isPlural","type","match","exec","parseFloat","parse","long","abs","fmtLong","fmtShort","formatArgs","useColors","namespace","humanize","diff","color","lastC","save","namespaces","storage","setItem","removeItem","error","load","getItem","DEBUG","__nwjs","navigator","userAgent","document","documentElement","style","WebkitAppearance","firebug","exception","table","RegExp","localStorage","localstorage","destroy","warned","warn","colors","debug","formatters","env","createDebug","prevTime","namespacesCache","enabledCache","enableOverride","enabled","curr","Date","prev","coerce","unshift","format","formatter","logFn","selectColor","extend","enumerable","configurable","delimiter","newDebug","toNamespace","regexp","default","disable","names","map","skips","enable","forEach","Denque","_head","_tail","_capacity","capacity","_capacityMask","_list","_fromArray","peekAt","peek","peekFront","peekBack","item","_growArray","pop","_shrinkArray","removeOne","k","remove","count","removed","del_count","toArray","clear","temp","arg_len","arguments_index","leng","isEmpty","_copyArray","fullCopy","newArray","list","assign","props","code","_","ErrClass","getPrototypeOf","event_iterator_1","EventIterator","EventQueue","pullQueue","pushQueue","eventHandlers","isPaused","isStopped","resolution","done","placeholder","highWaterMark","highWater","stop","fail","rejection","catch","then","removeCallback","Symbol","asyncIterator","lowWaterMark","lowWater","return","listen","queue","event","has","Events","EE","context","once","addListener","emitter","listener","_events","_eventsCount","clearEvent","__proto__","eventNames","events","getOwnPropertySymbols","concat","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","removeAllListeners","prefixed","ReflectOwnKeys","R","Reflect","ReflectApply","target","receiver","ownKeys","getOwnPropertyNames","NumberIsNaN","errorListener","resolver","eventTargetAgnosticAddListener","handler","flags","addErrorHandlerIfEventEmitter","_maxListeners","defaultMaxListeners","checkListener","_getMaxListeners","that","_addListener","prepend","existing","warning","newListener","onceWrapper","fired","wrapFn","_onceWrap","wrapped","unwrap","evlistener","arr","ret","unwrapListeners","arrayClone","wrapListener","arg","setMaxListeners","getMaxListeners","doError","er","prependListener","prependOnceListener","position","originalListener","spliceOne","rawListeners","hwm","top","btm","last","FixedFIFO","max","cache","_cache","word","includeBoundaries","v4","v6seg","v6","trim","v46Exact","v4exact","v6exact","ip","exact","root","ipv4Part","ipv4Regexes","fourOctet","threeOctet","twoOctet","longValue","octalRegex","hexRegex","zoneIndex","ipv6Part","ipv6Regexes","deprecatedTransitional","transitional","expandIPv6","indexOf","lastIndexOf","replacement","replacementCount","colonCount","lastColon","zoneId","substr","ref","results","matchCIDR","first","second","partSize","cidrBits","part","parseIntAuto","padPart","ipaddr","IPv4","octets","octet","SpecialRanges","unspecified","broadcast","multicast","linkLocal","loopback","carrierGradeNat","reserved","kind","other","cidrRange","prefixLengthFromSubnetMask","cidr","zerotable","range","subnetMatch","toByteArray","toIPv4MappedAddress","IPv6","toNormalizedString","broadcastAddressFromCIDR","parseCIDR","ipInterfaceOctets","subnetMaskOctets","subnetMaskFromPrefixLength","isIPv4","parser","isValid","isValidFourPartDecimal","networkAddressFromCIDR","maskLength","parsed","reverse","filledOctetCount","uniqueLocal","ipv4Mapped","rfc6145","rfc6052","teredo","isIPv4MappedAddress","toFixedLengthString","addr","suffix","toIPv4Address","toRFC5952String","regex","bestMatchIndex","bestMatchLength","isIPv6","native","fromByteArray","e2","address","rangeList","defaultName","rangeName","rangeSubnets","subnet","electron","ipRegex","isIp","version","URLWithLegacySupport","URLSearchParams","defaultBase","relative","URL","url","urlParsed","location","protocolMap","defaultProtocol","protocol","base","host","isReactNative","product","super","pathname","search","auth","username","password","query","startsWith","hostname","href","origin","port","searchParams","createObjectURL","revokeObjectURL","toJSON","userPass","async","entry","thing","func","pushable","sources","output","all","FIFO","onEnd","onNext","ended","bufferNext","bufferError","writev","values","throw","_pushable","sorter","sort","limit","items","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","COMMON_JS","JS_SHA3_NO_COMMON_JS","AMD","define","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","ArrayBuffer","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","BITS","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","isView","createOutputMethod","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","methods","createKmacOutputMethod","createOutputMethods","createMethod","algorithms","bytepad","Kmac","methodNames","algorithm","methodName","newMethodName","blocks","finalized","blockCount","byteCount","outputBlocks","extraBytes","notString","lastByteIndex","right","encodeString","strs","paddingBytes","finalize","hex","arrayBuffer","Uint32Array","c0","c3","c4","c5","c6","c7","c8","c9","b16","b17","b18","b19","b20","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b40","b41","b42","b43","b44","b45","b46","b47","b48","b49","isOptionObject","propertyIsEnumerable","object","writable","defaultMergeOptions","concatArrays","ignoreUndefined","getEnumerableOwnPropertyKeys","symbols","symbol","clone","cloneArray","cloneOptionObject","mergeKeys","merged","config","resultIndex","indices","filter","includes","option","_toConsumableArray","arr2","defaultTarget","mutableHandler","mutableTarget","setTarget","setHandler","Proxy","property","_len","getTarget","getHandler","proxy","Netmask","atob","chr","chr0","chrA","chra","ip2long","long2ip","dmax","net","maskLong","error1","bitmask","netLong","hostmask","contains","lastLong","forge","registerAlgorithm","mode","cipher","aes","Algorithm","startEncrypting","iv","_createCipher","decrypt","createEncryptionCipher","startDecrypting","createDecryptionCipher","initialize","encrypt","inBlock","outBlock","_updateBlock","_w","_init","tmp","createBuffer","putByte","getInt32","encryptOp","_expandKey","modes","ecb","cbc","cfb","ofb","gcm","sbox","isbox","rcon","mix","imix","xtime","e4","e8","sx","sx2","me","ime","ei","iNk","Nk","m0","m1","m2","m3","wnew","wi","Nr","toUpperCase","createDecipher","createCipher","ByteBuffer","asn1","_checkBufferLength","remaining","available","requested","Class","UNIVERSAL","APPLICATION","CONTEXT_SPECIFIC","PRIVATE","Type","NONE","BOOLEAN","INTEGER","BITSTRING","OCTETSTRING","NULL","OID","ODESC","EXTERNAL","REAL","ENUMERATED","EMBEDDED","UTF8","ROID","SEQUENCE","SET","PRINTABLESTRING","IA5STRING","UTCTIME","GENERALIZEDTIME","BMPSTRING","tagClass","constructed","composed","bitStringContents","original","excludeBitStringContents","equals","obj1","obj2","equal","includeBitStringContents","getBerValueLength","getByte","getInt","_fromDer","depth","longFormBytes","_getValueLength","strict","getBytes","decodeBitStrings","savedRead","savedRemaining","unused","used","tc","ex","getInt16","asn1Options","fromDer","parseAllBytes","toDer","useBitStringContents","putBytes","putBuffer","putInt16","lenBytes","oidToDer","oid","valueBytes","derToOid","utcTimeToDate","utc","date","year","MM","DD","hh","mm","ss","setUTCFullYear","setUTCHours","setTime","generalizedTimeToDate","gentime","YYYY","fff","isUTC","setFullYear","setHours","dateToUtcTime","rval","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","dateToGeneralizedTime","integerToDer","putSignedInt","integer","derToInteger","getSignedInt","validate","capture","errors","optional","captureAsn1","captureBitStringContents","captureBitStringValue","_nonLatinRegex","prettyPrint","level","indentation","indent","IA5String","subvalues","pki","oids","bytesToHex","decodeUtf8","api","_reverseAlphabets","alphabet","maxline","digits","at","_encodeWithByteBuffer","getAlgorithm","BlockCipher","_finish","_input","_op","_decrypt","opts","compact","unpad","overflow","afterFinish","transformIV","ints","inc32","from64To32","num","_ints","_inBlock","_outBlock","putInt32","fillWithByte","truncate","_prev","_iv","_partialBlock","_partialOutput","_partialBytes","inputLength","partialBytes","_R","additionalData","_cipherLength","_tagLength","_tag","_hashBlock","_hashSubkey","componentBits","_m","generateHashTable","ivLength","_j0","ghash","_aDataLength","_s","lengths","multiply","z_i","v_i","lsb","tableMultiply","x_i","ah","multiplier","perInt","shft","generateSubHashTable","mid","half","m_i","m_j","des","_keys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","iterations","shifts","lefttmp","righttmp","_createKeys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","looping","endloop","loopinc","right1","right2","usePureJavaScript","hmac","_md","_ipadding","_opadding","md","keylen","blockLength","inner","getMac","dbits","jsbn","BigInteger","nbi","am3","xl","xh","am","appName","DB","DM","DV","FV","F1","F2","rr","vv","BI_RC","int2char","intAt","nbv","fromInt","nbits","Classic","Montgomery","mp","invDigit","mpl","mph","um","mt2","op_and","op_or","op_xor","op_andnot","lbit","cbit","NullExp","nNop","Barrett","q3","ONE","dlShiftTo","mu","divide","convert","compareTo","revert","reduce","divRemTo","mulTo","multiplyTo","sqrTo","squareTo","ZERO","subTo","copyTo","u0","clamp","drShiftTo","fromRadix","mi","sh","lShiftTo","bs","cbs","bm","ds","rShiftTo","pm","pt","ts","nsh","ys","y0","yt","qd","isEven","exp","negate","toRadix","km","modPowInt","multiplyUpperTo","multiplyLowerTo","dAddOffset","lowprimes","lplim","chunkSize","signum","cs","intValue","dMultiply","testBit","bitwiseTo","shiftLeft","isProbablePrime","nextBytes","op","changeBit","addTo","modInt","millerRabin","n1","subtract","getLowestSetBit","shiftRight","random","modPow","byteValue","shortValue","and","or","xor","andNot","not","bitCount","setBit","clearBit","flipBit","remainder","divideAndRemainder","k1","g2","is1","modInverse","ac","gcd","mgf","mgf1","generate","maskLen","_IN","id","_I_","pbe","encryptedPrivateKeyValidator","PBES2AlgorithmsValidator","pkcs12PbeParamsValidator","prfOidToMessageDigest","prfOid","prfAlgorithm","supported","prfAlgorithmToMessageDigest","sha512","encryptPrivateKeyInfo","saltSize","dkLen","encryptionAlgorithm","encryptedData","getBytesSync","countBytes","ivLen","encOid","cipherFn","dk","pkcs5","pbkdf2","hexToBytes","createPbkdf2Params","saltBytes","generatePkcs12Key","decryptPrivateKeyInfo","encryptionOid","getCipher","encryptionParams","encrypted","encryptedPrivateKeyToPem","epki","msg","pem","encryptedPrivateKeyFromPem","headerType","procType","encryptRsaPrivateKey","rsaKey","legacy","wrapRsaPrivateKey","privateKeyToAsn1","opensslDeriveBytes","dekInfo","parameters","decryptRsaPrivateKey","rc2","privateKeyFromAsn1","iter","sha1","passBuf","D","Slen","S","Plen","P","I","B","Inew","setAt","getCipherForPBES2","getCipherForPKCS12PBE","supportedOids","kdfOid","kdfSalt","kdfIterationCount","encIv","dIvLen","md5","digests","isNodejs","pbkdf2Sync","hLen","prf","u_c","u_c1","int32ToBytes","xorBytes","outer","setImmediate","foldHeader","header","insertSpace","candidate","insert","ltrim","contentDomain","headers","encode64","rMessage","rHeader","rCRLF","decode64","lines","li","line","nl","vi","pkcs1","rsa_mgf1","encode_rsa_oaep","label","mgf1Md","keyLength","maxLength","lHash","PS","PS_length","seedLength","dbMask","maskedDB","seedMask","maskedSeed","decode_rsa_oaep","em","expectedLength","db","lHashPrime","in_ps","is_0","error_mask","p7","pkcs7","_recipientFromAsn1","recipientInfoValidator","issuer","RDNAttributesAsArray","serialNumber","serial","toHex","encryptedContent","encAlgorithm","parameter","encParameter","content","encKey","_recipientsToAsn1","recipients","distinguishedNameToAsn1","attributes","_signerToAsn1","digestAlgorithm","authenticatedAttributesAsn1","signatureAlgorithm","signature","unauthenticatedAttributes","attrsAsn1","attr","_attributeToAsn1","contentType","messageDigest","signingTime","jan_1_1950","jan_1_2050","timestamp","_fromAsn1","validator","rawCapture","_decryptContent","ciph","messageFromPem","messageFromAsn1","messageToPem","pemObj","toAsn1","contentInfoValidator","envelopedData","createEnvelopedData","createEncryptedData","signedData","createSignedData","fromAsn1","certificates","crls","signers","digestAlgorithmIdentifiers","contentInfo","signerInfos","signedDataValidator","certs","certificateFromAsn1","certificateToAsn1","addSigner","signer","certificate","cert","certificateFromPem","privateKeyFromPem","sha256","sha384","authenticatedAttributes","rsaEncryption","encodeUtf8","detached","detachedContent","mds","ai","_signersToAsn1","addSignerInfos","addDigestAlgorithmIds","verify","addCertificate","addCertificateRevokationList","crl","encryptedDataValidator","envelopedDataValidator","infos","_recipientsFromAsn1","recipientInfos","ec","findRecipient","sAttr","rAttr","recipient","privKey","desCBC","addRecipient","keyLen","ciphFn","p7v","pkcs7asn1","encryptedContentInfoValidator","signerValidator","prime","GCD_30_DELTA","THIRTY","generateProbablePrime","rng","Worker","primeincFindPrimeWithoutWorkers","generateRandom","numWorkers","workers","workLoad","workerScript","estimateCores","cores","workerMessage","found","terminate","postMessage","primeincFindPrimeWithWorkers","primeincFindPrime","mrTests","getMillerRabinTests","millerRabinTests","maxBlockTime","_primeinc","deltaIdx","bits1","plugin","time","reseeds","generated","keyBytes","pools","_reseedSync","messageLength","_seed","needed","collect","seedFileSync","_2powK","seedBytes","formatKey","formatSeed","defaultSeedFile","globalScope","entropy","QuotaExceededError","generateSync","increment","nextTick","seedFile","_reseed","collectInt","registerWorker","worker","pss","saltLength","sLen","salt_","pssobj","modBits","emBits","emLen","mHash","m_","ps","checkLen","jQuery","prng_aes","_prng_aes_output","_prng_aes_buffer","spawnPrng","_ctx","_navBytes","mousemove","clientX","clientY","keypress","charCode","createInstance","piTable","rol","ror","expandKey","effKeyBits","L","T","T1","T8","TM","mixRound","mashRound","_output","getInt16Le","runPlan","plan","putInt16Le","ptr","rsa","privateKeyValidator","rsaPrivateKeyValidator","rsaPublicKeyValidator","publicKeyValidator","digestInfoValidator","emsaPkcs1v15encode","oidBytes","digestInfo","_modPow","pub","dP","dQ","qInv","xp","xq","_encodePkcs1_v1_5","bt","eb","padByte","padNum","numZeros","padBytes","_decodePkcs1_v1_5","ml","_generateKeyPair","getPrime","pBits","qBits","p1","q1","phi","privateKey","setPrivateKey","setPublicKey","_bnToBytes","_getMillerRabinTests","_detectNodeCrypto","_detectSubtleCrypto","subtle","_detectSubtleMsCrypto","_intToUint8Array","yhex","ed","expected","xhex","createKeyPairGenerationState","eInt","pqState","stepKeyPairGenerationState","total","generateKeyPair","modulusLength","publicExponent","publicKeyEncoding","privateKeyEncoding","priv","publicKeyFromPem","generateKey","pair","exportKey","pkcs8","setRsaPublicKey","genOp","oncomplete","exportOp","onerror","keypair","generateKeyPairSync","scheme","schemeOptions","_parseAllDigestBytes","algorithmIdentifier","md2","sha224","setRsaPrivateKey","privateKeyModulus","privateKeyPublicExponent","privateKeyPrivateExponent","privateKeyPrime1","privateKeyPrime2","privateKeyExponent1","privateKeyExponent2","privateKeyCoefficient","privateKeyToRSAPrivateKey","publicKeyFromAsn1","publicKeyOid","rsaPublicKey","publicKeyModulus","publicKeyExponent","publicKeyToAsn1","publicKeyToSubjectPublicKeyInfo","publicKeyToRSAPublicKey","_initialized","_padding","fillString","fullMessageLength","messageLengthSize","messageLength64","int32s","_update","finalBlock","s2","_k","s0","maj","_states","messageLength128","hlen","t1_hi","t1_lo","t2_hi","t2_lo","s0_hi","s0_lo","s1_hi","ch_hi","maj_hi","maj_lo","a_hi","a_lo","b_hi","b_lo","c_hi","c_lo","d_hi","d_lo","e_hi","e_lo","f_hi","f_lo","g_hi","g_lo","h_hi","h_lo","w2","w7","w15","w16","baseN","_checkBitsParam","ByteStringBuffer","isArrayBuffer","isArrayBufferView","_constructedStringLength","browser","callbacks","stopPropagation","MutationObserver","now","createElement","observe","oldSetImmediate","setAttribute","_optimizeConstructedString","putString","putInt24","putInt24Le","putInt32Le","putInt","getInt24","getInt24Le","getInt32Le","DataBuffer","readOffset","growSize","writeOffset","accommodate","amount","setUint8","view","raw","text","utf16","setInt16","setInt8","setInt32","getInt8","getUint8","s1","s3","_base64","_base64Idx","_base58","chr1","chr2","chr3","enc1","enc2","enc3","enc4","unescape","encodeURIComponent","decodeURIComponent","escape","base58","deflate","inflate","_setStorageObject","_getStorageObject","_setItem","_getItem","_removeItem","empty","_clearItems","_callStorageFunction","idx","clearItems","re","argi","lastIndex","formatNumber","number","decimals","dec_point","thousands_sep","toFixed","formatSize","bytesFromIP","bytesFromIPv4","bytesFromIPv6","blanks","bytesToIP","bytesToIPv4","bytesToIPv6","zeroGroups","zeroMaxGroup","group","hardwareConcurrency","Blob","blobUrl","st","et","sample","samples","avg","overlaps","overlap","_shortNames","x509CertificateValidator","rsassaPssParameterValidator","certificationRequestInfoValidator","certificationRequestValidator","_getAttribute","shortName","rdn","si","valueTagClass","CRIAttributesAsArray","seq","extensionRequest","extensions","certificateExtensionFromAsn1","_readSignatureParameters","fillDefaults","algorithmOid","hashOid","maskGenOid","maskGenHashOid","_createSignatureDigest","signatureOid","_verifySignature","sha1WithRSAEncryption","sha1WithRSASignature","signatureParameters","_dnToAsn1","attrs","_fillMissingFields","attribute","valueConstructed","certificateExtensionToAsn1","_fillMissingExtensionFields","extension","digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly","cA","pathLenConstraint","client","server","email","objsign","sslCA","emailCA","objCA","altNames","altName","comment","ski","generateSubjectKeyIdentifier","subjectKeyIdentifier","keyIdentifier","authorityCertIssuer","subSeq","fullNameGeneralNames","_signatureParametersToAsn1","_CRIAttributesToAsn1","csr","computeHash","certificateToPem","publicKeyToPem","publicKeyToRSAPublicKeyPem","getPublicKeyFingerprint","certificationRequestFromPem","certificationRequestFromAsn1","certificationRequestToPem","certificationRequestToAsn1","createCertificate","siginfo","validity","notBefore","notAfter","getField","sn","addField","setSubject","uniqueId","setIssuer","setExtensions","exts","getExtension","ext","tbsCertificate","getTBSCertificate","child","issued","expectedIssuer","actualIssuer","isIssuer","parent","iattr","sattr","verifySubjectKeyIdentifier","certVersion","certSerialNumber","certSignatureOid","certSignatureParams","certinfoSignatureOid","certinfoSignatureParams","certSignature","certValidity1UTCTime","certValidity2GeneralizedTime","certValidity3UTCTime","certValidity4GeneralizedTime","imd","ibytes","certIssuer","certIssuerUniqueId","smd","sbytes","certSubject","certSubjectUniqueId","certExtensions","certificateExtensionsFromAsn1","subjectPublicKeyInfo","extseq","critical","ev","gn","createCertificationRequest","csrVersion","csrSignatureOid","csrSignatureParams","csrSignature","certificationRequestInfo","certificationRequestInfoSubject","getAttribute","addAttribute","certificationRequestInfoAttributes","setAttributes","getCertificationRequestInfo","cri","_dateToAsn1","tbs","certificateExtensionsToAsn1","dn","createCaStore","caStore","getBySubject","ensureSubjectHasHash","getIssuer","hasCertificate","der1","listAllCertificates","certList","removeCertificate","certificateError","bad_certificate","unsupported_certificate","certificate_revoked","certificate_expired","certificate_unknown","unknown_ca","verifyCertificateChain","chain","validityCheckDate","selfSigned","parents","verified","se","keyUsage","basicConstraints","bcExt","keyUsageExt","vfd","Fifo","defer","_waitingConsumers","promise","_consume","nextConsumer","nextChunk","deferred","__importDefault","__esModule","netmask_1","ip_regex_1","is_ip_1","ipaddr_js_1","NETMASK_RANGES","ip_range","ipv6_check","ip_addr","ipv4_check","common","timeType","commonRe","nested","google","Any","fields","type_url","Duration","seconds","nanos","Timestamp","Empty","Struct","keyType","Value","oneofs","oneof","nullValue","numberValue","stringValue","boolValue","structValue","listValue","NullValue","NULL_VALUE","ListValue","rule","DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue","FieldMask","paths","file","converter","Enum","genValuePartial_fromObject","gen","field","fieldIndex","resolvedType","typeDefault","repeated","fullName","isUnsigned","genValuePartial_toObject","fromObject","mtype","fieldsArray","safeProp","toObject","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","valuesById","arrayDefault","hasKs2","_fieldsArray","types","defaults","basic","packed","rfield","required","missing","mapKey","genTypePartial","ReflectionObject","className","Namespace","comments","valuesOptions","fromJSON","enm","keepComments","isReservedId","isReservedName","allow_alias","Field","ruleRe","defaultValue","extensionField","declaringField","_packed","getOption","setOption","resolved","lookupTypeOrEnum","proto3_optional","ctor","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","Type_","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Method","Message","wrappers","tokenize","resolvedKeyType","fieldKeyType","fieldValueType","$type","encodeDelimited","decodeDelimited","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","_nestedArray","clearCache","addJSON","nestedArray","nestedJson","getEnum","setOptions","onAdd","onRemove","resolveAll","lookup","filterTypes","parentAlreadyChecked","lookupEnum","lookupService","Service_","Enum_","defineProperties","_handleAdd","_handleRemove","setParsedOption","propName","opt","find","newValue","setProperty","newOpt","Root_","addFieldsToParent","oneofName","keepCase","base10Re","base10NegRe","base16Re","base16NegRe","base8Re","base8NegRe","numberRe","nameRe","typeRefRe","fqTypeRefRe","pkg","imports","weakImports","syntax","token","preferTrailingComment","tn","alternateCommentMode","cmnt","isProto3","applyCase","camelCase","illegal","insideTryCatch","readString","readValue","acceptTypeRef","parseNumber","readRanges","acceptStrings","parseId","acceptNegative","parsePackage","parseImport","whichImports","parseSyntax","parseCommon","parseOption","parseType","parseEnum","service","ifBlock","commentText","parseMethod","parseService","reference","parseField","parseExtension","fnIf","fnElse","trailingLine","valueType","parseInlineOptions","parseMapField","parseOneOf","ucFirst","parseGroup","dummy","parseEnumValue","isCustom","parseOptionValue","objectResult","lastValue","prevValue","simpleValue","files","SYNC","resolvePath","sync","cb","getBundledFileName","altname","queued","weak","readFileSync","exposeRe","tryHandleExtension","extendedType","sisterField","parse_","common_","_methodsArray","inherited","methodsArray","rpcService","isReserved","delimRe","stringDoubleRe","stringSingleRe","setCommentRe","setCommentAltRe","setCommentSplitRe","whitespaceRe","unescapeRe","unescapeMap","lastCommentLine","stringDelim","setComment","isLeading","lineEmpty","leading","commentOffset","isDoubleSlashCommentLine","startOffset","endOffset","findEndOfLine","lineText","cursor","repeat","isDoc","isLeadingComment","actual","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","wrapper","originalThis","typeName","bake","safePropBackslashRe","safePropQuoteRe","camelCaseRe","decorateRoot","decorateEnumIndex","setProp","seenFirstField","invalid","genVerifyKey","genVerifyValue","oneofProp","aa","ca","da","Set","ea","fa","ha","ia","ja","ka","la","ma","acceptsBooleans","attributeName","attributeNamespace","mustUseProperty","propertyName","sanitizeURL","removeEmptyString","ra","sa","ta","pa","qa","oa","removeAttribute","setAttributeNS","xlinkHref","ua","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","va","for","wa","ya","za","Aa","Ba","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","iterator","Ka","La","A","Ma","Na","Oa","prepareStackTrace","construct","displayName","Pa","render","Qa","$$typeof","_context","_payload","Ra","Sa","Ta","nodeName","Va","_valueTracker","getOwnPropertyDescriptor","getValue","setValue","stopTracking","Ua","Wa","checked","Xa","activeElement","Ya","defaultChecked","_wrapperState","initialChecked","Za","initialValue","controlled","ab","bb","ownerDocument","fb","selected","defaultSelected","disabled","gb","dangerouslySetInnerHTML","children","hb","ib","jb","textContent","kb","lb","mb","nb","namespaceURI","innerHTML","valueOf","firstChild","removeChild","appendChild","MSApp","execUnsafeLocalFunction","ob","lastChild","nodeType","nodeValue","pb","animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","qb","rb","sb","tb","menuitem","area","br","col","embed","hr","img","keygen","link","meta","param","track","wbr","ub","vb","is","wb","xb","srcElement","correspondingUseElement","parentNode","yb","zb","Ab","Bb","Cb","stateNode","Db","Eb","Fb","Gb","Hb","Ib","Jb","Kb","Lb","Mb","Nb","onError","Ob","Pb","Qb","Rb","Sb","Tb","Vb","alternate","Wb","memoizedState","dehydrated","Xb","Zb","sibling","current","Yb","$b","unstable_scheduleCallback","bc","unstable_cancelCallback","cc","unstable_shouldYield","dc","unstable_requestPaint","unstable_now","unstable_getCurrentPriorityLevel","fc","unstable_ImmediatePriority","gc","unstable_UserBlockingPriority","hc","unstable_NormalPriority","ic","unstable_LowPriority","jc","unstable_IdlePriority","kc","lc","oc","clz32","pc","qc","rc","sc","uc","pendingLanes","suspendedLanes","pingedLanes","entangledLanes","entanglements","vc","xc","yc","zc","Ac","eventTimes","Cc","C","Dc","Ec","Fc","Gc","Hc","Ic","Jc","Kc","Lc","Mc","Nc","Oc","Map","Pc","Qc","Rc","Sc","delete","pointerId","Tc","nativeEvent","blockedOn","domEventName","eventSystemFlags","targetContainers","Vc","Wc","priority","isDehydrated","containerInfo","Xc","Yc","dispatchEvent","Zc","$c","ad","bd","cd","ReactCurrentBatchConfig","dd","transition","fd","gd","hd","Uc","jd","kd","ld","nd","od","keyCode","pd","rd","_reactName","_targetInst","currentTarget","isDefaultPrevented","defaultPrevented","returnValue","isPropagationStopped","preventDefault","cancelBubble","persist","isPersistent","wd","xd","yd","sd","eventPhase","bubbles","cancelable","timeStamp","isTrusted","td","ud","detail","vd","Ad","screenX","screenY","pageX","pageY","ctrlKey","shiftKey","altKey","metaKey","getModifierState","zd","button","buttons","relatedTarget","fromElement","toElement","movementX","movementY","Bd","Dd","dataTransfer","Fd","Hd","animationName","elapsedTime","pseudoElement","Id","clipboardData","Jd","Ld","Md","Esc","Spacebar","Left","Up","Right","Down","Del","Win","Menu","Apps","Scroll","MozPrintableKey","Nd","Od","Alt","Control","Meta","Shift","Pd","Qd","locale","which","Rd","Td","width","height","pressure","tangentialPressure","tiltX","tiltY","twist","pointerType","isPrimary","Vd","touches","targetTouches","changedTouches","Xd","Yd","deltaX","wheelDeltaX","deltaY","wheelDeltaY","wheelDelta","deltaZ","deltaMode","Zd","$d","ae","be","documentMode","ce","de","fe","ge","he","ie","datetime","month","tel","week","ne","oe","pe","qe","te","ue","ve","we","xe","ye","ze","oninput","Ae","detachEvent","Be","Ce","attachEvent","De","Ee","Fe","He","Ie","Je","Ke","nextSibling","Le","compareDocumentPosition","Me","HTMLIFrameElement","contentWindow","Ne","contentEditable","Oe","focusedElem","selectionRange","selectionStart","selectionEnd","defaultView","getSelection","rangeCount","anchorNode","anchorOffset","focusNode","focusOffset","createRange","setStart","removeAllRanges","addRange","setEnd","element","scrollLeft","scrollTop","focus","Pe","Qe","Re","Se","Te","Ue","Ve","We","animationend","animationiteration","animationstart","transitionend","Xe","Ye","Ze","animation","$e","af","bf","cf","df","ef","ff","hf","lf","mf","nf","Ub","instance","of","pf","qf","rf","sf","passive","J","F","tf","uf","parentWindow","vf","wf","na","xa","$a","ba","je","char","ke","xf","yf","zf","Af","Bf","Cf","Df","Ef","__html","Ff","Gf","clearTimeout","Hf","Jf","queueMicrotask","If","Kf","Lf","Mf","previousSibling","Nf","Of","Pf","Qf","Rf","Sf","Tf","Uf","E","G","Vf","H","Wf","Xf","Yf","contextTypes","__reactInternalMemoizedUnmaskedChildContext","__reactInternalMemoizedMaskedChildContext","Zf","childContextTypes","$f","ag","bg","getChildContext","cg","__reactInternalMemoizedMergedChildContext","dg","eg","fg","gg","hg","jg","kg","lg","mg","ng","og","pg","qg","rg","sg","tg","ug","vg","wg","xg","yg","zg","Ag","Bg","elementType","deletions","Cg","pendingProps","treeContext","retryLane","Dg","Eg","Fg","Gg","memoizedProps","Hg","Ig","Jg","Kg","Lg","defaultProps","Mg","Ng","Og","Pg","Qg","Rg","_currentValue","Sg","childLanes","Tg","dependencies","firstContext","lanes","Ug","Vg","memoizedValue","Wg","Xg","Yg","interleaved","Zg","$g","updateQueue","baseState","firstBaseUpdate","lastBaseUpdate","shared","effects","bh","ch","eventTime","lane","payload","dh","eh","fh","gh","ih","jh","Component","refs","kh","nh","isMounted","_reactInternals","enqueueSetState","lh","mh","enqueueReplaceState","enqueueForceUpdate","oh","shouldComponentUpdate","isPureReactComponent","ph","contextType","updater","qh","componentWillReceiveProps","UNSAFE_componentWillReceiveProps","rh","getDerivedStateFromProps","getSnapshotBeforeUpdate","UNSAFE_componentWillMount","componentWillMount","componentDidMount","_owner","_stringRef","th","uh","vh","wh","yh","implementation","zh","Ah","Bh","Ch","Dh","Eh","Fh","Gh","Hh","Ih","tagName","Jh","Kh","Lh","M","Mh","revealOrder","Nh","Oh","_workInProgressVersionPrimary","Ph","ReactCurrentDispatcher","Qh","Rh","N","O","Sh","Th","Uh","Vh","Q","Wh","Xh","Yh","Zh","$h","bi","ci","baseQueue","di","fi","lastRenderedReducer","action","hasEagerState","eagerState","lastRenderedState","dispatch","gi","ii","ji","ki","getSnapshot","ni","lastEffect","stores","oi","pi","qi","ri","deps","ti","ui","xi","yi","zi","Ai","Bi","Ci","Di","Ei","Fi","Gi","Hi","Ii","Ji","readContext","useCallback","useContext","useEffect","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useReducer","useRef","useState","useDebugValue","useDeferredValue","useTransition","useMutableSource","useSyncExternalStore","useId","unstable_isNewReconciler","identifierPrefix","Ki","Li","Mi","Ni","WeakMap","Oi","Pi","Qi","Ri","getDerivedStateFromError","componentDidCatch","Si","componentStack","Ti","pingCache","Ui","Vi","Wi","Xi","ReactCurrentOwner","Yi","Zi","$i","aj","bj","cj","dj","ej","baseLanes","cachePool","transitions","fj","gj","hj","ij","jj","UNSAFE_componentWillUpdate","componentWillUpdate","componentDidUpdate","kj","lj","pendingContext","mj","Aj","Cj","Dj","nj","oj","pj","fallback","qj","rj","tj","dataset","dgst","uj","vj","_reactRetry","sj","subtreeFlags","wj","xj","isBackwards","rendering","renderingStartTime","tailMode","yj","Ej","Fj","Gj","wasMultiple","multiple","suppressHydrationWarning","onClick","onclick","createElementNS","autoFocus","createTextNode","Hj","Ij","Jj","Kj","U","Lj","WeakSet","V","Mj","W","Nj","Oj","Qj","Rj","Sj","Tj","Uj","Vj","Wj","insertBefore","_reactRootContainer","Xj","X","Yj","Zj","ak","onCommitFiberUnmount","componentWillUnmount","bk","ck","ek","fk","isHidden","gk","hk","display","ik","jk","kk","lk","__reactInternalSnapshotBeforeUpdate","Wk","mk","nk","ok","pk","Y","Z","qk","rk","sk","tk","uk","vk","wk","xk","yk","zk","Ak","Bk","Ck","Dk","Ek","callbackNode","expirationTimes","expiredLanes","wc","callbackPriority","ig","Fk","Gk","Hk","Ik","Jk","Kk","Lk","Mk","Ok","Pk","finishedWork","finishedLanes","Qk","timeoutHandle","Rk","Sk","Tk","Uk","Vk","mutableReadLanes","Bc","Pj","onCommitFiberRoot","mc","onRecoverableError","Xk","onPostCommitFiberRoot","Yk","Zk","isReactComponent","pendingChildren","mutableSourceEagerHydrationData","cl","pendingSuspenseBoundaries","dl","el","fl","gl","hl","il","jl","zj","$k","ll","reportError","_internalRoot","ol","pl","ql","sl","rl","unmount","unstable_scheduleHydration","querySelectorAll","form","tl","usingClientEntryPoint","ul","findFiberByHostInstance","bundleType","rendererPackageName","vl","rendererConfig","overrideHookState","overrideHookStateDeletePath","overrideHookStateRenamePath","overrideProps","overridePropsDeletePath","overridePropsRenamePath","setErrorHandler","setSuspenseHandler","scheduleUpdate","currentDispatcherRef","findHostInstanceByFiber","findHostInstancesForRefresh","scheduleRefresh","scheduleRoot","setRefreshHandler","getCurrentFiber","reconcilerVersion","__REACT_DEVTOOLS_GLOBAL_HOOK__","wl","isDisabled","supportsFiber","inject","createPortal","createRoot","unstable_strictMode","findDOMNode","flushSync","hydrate","hydrateRoot","hydratedSources","_getVersion","unmountComponentAtNode","unstable_batchedUpdates","unstable_renderSubtreeIntoContainer","checkDCE","__self","__source","jsx","jsxs","setState","forceUpdate","_status","_result","Children","only","Fragment","Profiler","PureComponent","StrictMode","Suspense","cloneElement","createContext","_currentValue2","_threadCount","Provider","Consumer","_defaultValue","_globalName","createFactory","createRef","forwardRef","isValidElement","lazy","memo","startTransition","unstable_act","Receptacle","toMS","_lookup","lastModified","ttl","expires","expire","record","refresh","oldRecord","timeout","getTime","Retimer","_started","_rescheduled","_scheduled","_args","_triggered","_timerWrapper","_schedule","_timer","reschedule","illegalRe","controlRe","reservedRe","windowsReservedRe","windowsTrailingRe","sanitize","sanitized","sortIndex","performance","startTime","expirationTime","priorityLevel","scheduling","isInputPending","MessageChannel","port2","port1","onmessage","unstable_Profiling","unstable_continueExecution","unstable_forceFrameRate","unstable_getFirstCallbackNode","unstable_next","unstable_pauseExecution","unstable_runWithPriority","delay","unstable_wrapCallback","intervals","setDelayedInterval","task","interval","_timeout","_runPeriodically","clearDelayedInterval","retimer","TimeoutController","_ms","setPrototypeOf","getLength","isHighSurrogate","codePoint","isLowSurrogate","segment","charLength","curByteLength","prevCodePoint","res","MAX_SAFE_INTEGER","oldOffset","INT","encodingLength","N1","N2","N3","N4","N5","N6","N7","N8","N9","$protobuf","$Reader","$Writer","$util","$root","RPC","subscriptions","messages","ks","$oneOfFields","control","SubOpts","ControlMessage","arrays","_control","subscribe","topic","_subscribe","_topic","seqno","_from","_data","_seqno","_signature","ihave","iwant","graft","prune","ControlIHave","ControlIWant","ControlGraft","ControlPrune","messageIDs","topicID","_topicID","peers","backoff","PeerInfo","fromValue","_backoff","peerID","signedPeerRecord","_peerID","_signedPeerRecord","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","getter","leafPrototypes","getProto","ns","def","definition","toStringTag","DefaultPubSubTopic","StoreCodecs","_0n","BigInt","_1n","_2n","_3n","_8n","POW_2_256","CURVE","Gx","Gy","beta","weistrass","USE_ENDOMORPHISM","JacobianPoint","Point","points","toInv","nums","scratch","lastMultiplied","acc","inverted","invert","reduceRight","invertBatch","toAffine","toAffineBatch","fromAffine","X1","Y1","Z1","X2","Y2","Z2","Z1Z1","Z2Z2","U1","U2","S1","S2","X3","Y3","Z3","HH","HHH","multiplyUnsafe","scalar","P0","normalizeScalar","k1neg","k2neg","k2","splitScalarEndo","k1p","k2p","precomputeWindow","windows","wNAF","affinePoint","BASE","_WINDOW_SIZE","precomputes","pointPrecomputes","normalizeZ","windowSize","maxNumber","shiftBy","wbits","pr","cached","point","fake","f1p","f2p","invZ","iz1","iz2","iz3","ax","ay","_setWindowSize","isShort","bytesToNumber","isValidFieldElement","_6n","_11n","_22n","_23n","_44n","_88n","pow2","b88","b176","b220","b223","sqrtMod","isYOdd","assertValidity","ensureBytes","fromCompressedHex","fromUncompressedHex","normalizePrivateKey","msgHash","recovery","truncateHash","normalizeSignature","fromHex","numTo32bStr","rinv","u1","u2","multiplyAndAddUnsafe","toRawBytes","isCompressed","toHexX","toRawX","aP","bQ","sum","sliceDER","parseDERInt","Signature","isUint8a","hexToNumber","sBytes","rBytesLeft","parseDERSignature","fromDER","isWithinCurveOrder","hasHighS","HALF","normalizeS","toDERRawBytes","toDERHex","sHex","numberToHexUnpadded","rHex","rLen","toCompactRawBytes","toCompactHex","concatBytes","every","hexes","padStart","uint8a","numTo32b","hexByte","byte","isSafeInteger","power","modulo","divNearest","POW_2_128","delta","HmacDrbg","fill","utils","hmacSha256","hmacSync","hmacSha256Sync","incr","reseedSync","kmdToSig","kBytes","sig","normalizePublicKey","fromCompact","getPublicKey","fromPrivateKey","isPub","bits2int","bits2octets","z1","z2","int2octets","initSigArgs","extraEntropy","seedArgs","finalizeSig","recSig","canonical","der","recovered","hashed","drbg","reseed","vopts","sinv","web","TAGGED_HASH_PREFIXES","isValidPrivateKey","privateAdd","tweak","privateNegate","pointAddScalar","pointMultiply","hashToPrivateKey","bytesLength","randomPrivateKey","createHash","ckey","importKey","createHmac","sha256Sync","taggedHash","tagP","tagH","taggedHashSync","precompute","Symmetric","getSubtle","webcrypto","secp","keccak256","sha3","compressPublicKey","ALPHABET","BASE_MAP","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","it3","it4","vch","pbegin","pend","b58","it1","it2","Encoder","baseEncode","Decoder","baseDecode","codePointAt","prefixCodePoint","ComposedDecoder","decoders","Codec","baseX","basex","rfc4648","bitsPerChar","codes","written","SyntaxError","identity","TextDecoder","TextEncoder","base2","base8","base10","base16","base16upper","base32","base32upper","base32pad","base32padupper","base32hex","base32hexupper","base32hexpad","base32hexpadupper","base32z","base36","base36upper","base58btc","base58flickr","base64pad","base64url","base64urlpad","alphabetBytesToChars","alphabetCharsToBytes","base256emoji","byts","byt","encode_1","varint","encodeTo","int","sizeOffset","digestOffset","Digest","multihash","Hasher","sha","textEncoder","textDecoder","CID","asCID","_baseCache","hidden","readonly","toV0","DAG_PB_CODE","SHA_256_CODE","createV0","toV1","createV1","equalBytes","toStringV0","toStringV1","deprecate","IS_CID_DEPRECATION","cidSymbol","toBaseEncodedString","codec","multibaseName","encodeCID","cid","decodeFirst","specs","inspectBytes","prefixSize","multihashSize","multihashBytes","digestBytes","digestSize","multihashCode","initialBytes","parseCIDtoBytes","codeOffset","hashOffset","bases","identityBase","createCodec","ascii","latin1","bytesToUtf8","utf8ToBytes","_permanentCensorErrors","_censorErrors","LogLevels","_logLevel","_globalLogger","_normalizeError","_checkNormalize","LogLevel","ErrorCode","HEX","Logger","_log","logLevel","throwArgumentError","levels","INFO","WARNING","makeError","UNKNOWN_ERROR","messageDetails","reason","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","condition","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","operation","checkSafeUint53","checkArgumentCount","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","checkAbstract","censorship","permanent","globalLogger","logger","isHexable","toHexString","addSlice","isBytesLike","isHexString","isBytes","arrayify","allowMissingPrefix","hexPad","HexCharacters","hexlify","arrayifyInteger","unarrayifyInteger","_encode","_decodeChildren","childOffset","decoded","_decode","consumed","BUFFER_OVERRUN","lengthLength","boundry","v6segment","functionTimeout","function_","wrappedFunction","isRegexp","flagMap","ignoreCase","multiline","dotAll","sticky","unicode","clonedRegexp","flag","isMatch","cloneRegexp","isIP","isV4","isV6","toBytes","sections","v4Buffer","uint8ArrayToString","argv","getProtocol","proto","row","resolvable","createProtocol","convertToString","ipBuff","ipString","getUint16","bytes2ip","bytes2port","bytes2str","bytes2mh","bytes2onion","bytes2mb","convertToBytes","ip2bytes","port2bytes","uint8ArrayFromString","uint8ArrayConcat","str2bytes","mh2bytes","portBuf","onion2bytes","onion32bytes","mbstr","anybaseDecoder","mb2bytes","setUint16","addrBytes","portBytes","ERR_INVALID_ID","decodeMessage","encodeMessage","lengthDelimited","CODEC_TYPES","KeyType","__KeyTypeValues","PublicKey","PrivateKey","enumeration","findValue","enumValue","_codec","Data","RSA","nativeCrypto","bigIntegerToUintBase64url","base64urlToBigInteger","base64urlToBuffer","aesGcm","deriveParams","rawKey","cryptoKey","deriveKey","errcode","unmarshalPrivateKey","derivePublicFromPrivate","jwKey","kty","convertKey","handle","fkey","jwk2pub","jwk2priv","exporter","ciphers","encryptedKey","RsaPublicKey","marshal","jwk","pbm","uint8ArrayEquals","RsaPrivateKey","_publicKey","genSecret","public","dp","dq","unmarshalRsaPrivateKey","alg","unmarshalRsaPublicKey","fromJwk","_255n","CURVE_ORDER","MAX_256B","SQRT_M1","SQRT_AD_MINUS_ONE","INVSQRT_A_MINUS_D","ONE_MINUS_D_SQ","D_MINUS_ONE_SQ","ExtendedPoint","assertExtPoint","X1Z2","X2Z1","Y1Z2","Y2Z1","T3","T2","isSmallOrder","isTorsionFree","fromRistrettoBytes","legacyRist","toRistrettoBytes","fromRistrettoHash","assertRstPoint","RistrettoPoint","ep","Ns","Ns_D_is_sq","uvRatio","s_","edIsNegative","Nt","W0","W1","W2","W3","bytes255ToNumberLE","R1","calcElligatorRistrettoMap","R2","emsg","numberTo32BytesLE","u1_2","u2_2","invertSqrt","Dx","Dy","invsqrt","D1","D2","zInv","_x","_y","one","two","normed","bytesToNumberLE","y2","isXOdd","getExtendedPublicKey","toX25519","u8","numberTo32BytesBE","pow_2_252_3","_5n","_10n","_20n","_40n","_80n","b80","b160","b240","b250","pow_p_5_8","v3","v7","vx2","root1","root2","useRoot1","useRoot2","noRoot","modlLE","adjustBytes25519","checkPrivateKey","getKeyFromHash","pointBytes","_sha512Sync","prepareVerification","SB","finishVerification","kA","TORSION_SUBGROUP","hashToPrivateScalar","sha512Sync","PRIVATE_KEY_BYTE_LENGTH","hashAndSign","privateKeyRaw","hashAndVerify","concatKeys","Ed25519PublicKey","ensureKey","Ed25519PrivateKey","unmarshalEd25519PrivateKey","privateKeyBytes","publicKeyBytes","unmarshalEd25519PublicKey","validatePublicKey","Secp256k1PublicKey","keysProtobuf","Secp256k1PrivateKey","unmarshalSecp256k1PrivateKey","unmarshalSecp256k1PublicKey","supportedKeys","ed25519","Ed25519","secp256k1","Secp256k1","unsupportedKey","typeToKey","unmarshalPublicKey","keysPBM","importer","isPeerId","baseDecoder","PeerIdImpl","toCID","peerIdFromString","RSAPeerIdImpl","Ed25519PeerIdImpl","Secp256k1PeerIdImpl","peerIdFromPeerId","peerIdFromBytes","peerIdFromCID","peerIdFromKeys","KeypairType","Secp256k1Keypair","_privateKey","privateKeyVerify","publicKeyVerify","hasPrivateKey","ERR_TYPE_NOT_IMPLEMENTED","createKeypair","tuplesToStringTuples","tuples","tup","protoFromTuple","tuplesToBytes","fromBytes","sizeForAddr","bytesToTuples","ParseError","bytesToString","cleanPath","stringTuplesToString","stringToBytes","stringToStringTuples","validateBytes","inspect","DNS_CODES","P2P_CODES","resolvers","Multiaddr","isMultiaddr","toOptions","protoCodes","transport","family","protos","protoNames","stringTuples","encapsulate","decapsulate","addrString","decapsulateCode","getPeerId","tuple","ipfs","peerIdStr","getPath","resolvableProto","errCode","nodeAddress","isThinWaistAddress","some","dbg","ENR","kvs","entries","enr","keypairType","peerId","createPeerIdFromKeypair","createKeypairFromPeerId","createV4","hexSeq","rlpEncodedBytes","RLP","encoded","decodeFromValues","RECORD_PREFIX","nodeId","pubKey","uncompressedPubkey","tcp","udp","ip6","tcp6","udp6","multiaddrs","multiaddrBytes","multiaddr","decodeMultiaddrs","multiaddrsBuf","totalLength","dataView","encodeMultiaddrs","getLocationMultiaddr","isIpv6","endsWith","ipVal","isUdp","isTcp","protoName","protoVal","ipFamily","ipBytes","protocolBytes","multiaddrFromFields","setLocationMultiaddr","getFullMultiaddr","locationMultiaddr","getFullMultiaddrs","waku2","relay","store","lightPush","decodeWaku2","protocols","encodeWaku2","verifySignature","localeCompare","flat","encodeToValues","TimeoutError","AbortError","getDOMException","errorMessage","DOMException","getAbortedReason","pTimeout","milliseconds","timer","cancelablePromise","POSITIVE_INFINITY","customTimers","timeoutError","cancel","normalizeEmitter","pEvent","arrayPromise","rejectionEvents","multiArgs","resolveImmediately","onItem","arguments_","rejectHandler","rejectionEvent","pEventMultiple","findBufAndOffset","bufs","bufEnd","isUint8ArrayList","Uint8ArrayList","appendAll","append","consume","trunc","beginInclusive","endExclusive","_subList","bufStart","sliceEndsInBuf","bufInSlice","startIndex","endIndex","littleEndian","getBigInt64","setBigInt64","getUint32","setUint32","getBigUint64","setBigUint64","varintEncode","poolSize","minPoolSize","encodeLength","lengthEncoder","poolOffset","encodedLength","single","varintDecode","ReadModes","ReadHandlers","lengthDecoder","maxLengthLength","maxDataLength","onLength","onData","fromReader","varByteSource","splitLimit","calculateSize","getNext","objectMode","readableLength","rawPipe","fns","isIterable","isDuplex","sink","duplexPipelineFn","duplex","stream","sourceWrap","pipe","rest","selectRandomPeer","getPeersForProtocol","libp2p","peerStore","peer","accessor","TWO_32","toBigInt","access","negative","signed","zigzag","strValue","LIMIT","fromBigInt","fieldDefs","encodeValue","fieldNumber","fieldDef","fieldNumberStr","repeats","fieldLength","valueLength","asBuf","strLen","WakuMessage","kdf","secret","outputLength","willBeResult","counters","countersSecret","willBeHashResult","hashResult","_hashResult","derive","privateKeyA","publicKeyB","px","privateA","publicB","publicKeyTo","ephemPrivateKey","sharedPx","encryptionKey","cipherText","ivCipherText","macKey","hmacSha256Sign","ephemPublicKey","cipherTextLength","cipherAndIv","msgMac","hmacSha256Verify","clearEncode","messagePayload","sigPrivKey","envelope","fieldSize","computeSizeOfPayloadSizeField","addPayloadSizeField","rawSize","paddingSize","expectedSize","findIndex","validateDataIntegrity","bytesSignature","recoveryId","clearDecode","sizeOfPayloadSizeField","getSizeOfPayloadSizeField","payloadSize","payloadSizeBytes","getPayloadSize","payloadStart","isSigned","isMessageSigned","getSignature","getHash","messageHash","fromSignature","ecRecoverPubKey","decryptAsymmetric","ecies","encryptSymmetric","clearText","symmetric","decryptSymmetric","ivStart","OneMillion","DecryptionMethod","_signaturePublicKey","contentTopic","encPublicKey","symKey","enc","version_1","timestampDeprecated","decryptionKeys","protoBuf","decodeProto","signaturePublicKey","isDefined","dec","decodedResults","contentTopics","Asymmetric","payloadAsUtf8","rnds8","uuid","REGEX","byteToHex","rnds","FilterRequest","MessagePush","FilterRPC","ContentFilter","contentFilters","requestId","FilterCodec","WakuFilter","pubSubTopic","onRequest","pubsubTopic","createRequest","getPeer","newStream","lp","addCallback","unsubscribe","streamData","pushMessages","unsubscribeRequest","connections","connectionManager","getConnections","randomPeer","addDecryptionKey","deleteDecryptionKey","PushRequest","PushResponse","PushRPC","LightPushCodec","WakuLightPush","RelayCodecs","Index","PagingInfo","HistoryQuery","HistoryResponse","HistoryRPC","Direction","__DirectionValues","__ErrorValues","PageDirection","storeCodec","historyRpc","protoV2Beta3","protoV2Beta4","direction","pageDirection","BACKWARD","FORWARD","directionToProto","pagingInfo","pageSize","endTime","WakuStore","timeFilter","queryOpts","historyRpcQuery","createQuery","remoteAddr","reply","ERROR_NONE_UNSPECIFIED","pageMessages","protoMsg","responsePageSize","queryPageSize","codecs","Protocols","Waku","pubsub","pingKeepAliveTimers","relayKeepAliveTimers","pingKeepAlive","relayKeepAlive","startKeepAlive","remotePeer","stopKeepAlive","_protocols","Relay","Store","LightPush","Filter","dialProtocol","addPeerToAddressBook","addresses","addressBook","stopAllKeepAlives","isStarted","getLocalMultiaddrWithID","localMultiaddr","getMultiaddrs","pingPeriodSecs","relayPeriodSecs","setInterval","ping","wakuMsg","clearInterval","waitForRemotePeer","waku","timeoutMs","promises","getMeshPeers","waitForGossipSubPeerInMesh","waitForConnectedPeer","rejectReason","race","awaitTimeout","rejectOnTimeout","_resolve","Envelope","RecordEnvelope","payloadType","marshaled","Protobuf","uint8arraysEquals","domain","signData","formatSignaturePayload","envelopeData","createFromProtobuf","domainUint8Array","uint8arraysFromString","domainLength","payloadTypeLength","payloadLength","uint8arraysConcat","PeerRecord","AddressInfo","ENVELOPE_PAYLOAD_TYPE_PEER_RECORD","DOMAIN","CODEC","seqNumber","arrayEquals","trace","peerRecord","topologySymbol","TopologyImpl","onConnect","onDisconnect","registrar","disconnect","EventTarget","_EventEmitter_listeners","__classPrivateFieldGet","CustomEventPolyfill","Event","CustomEvent","MessageCache","gossip","historyCapacity","msgIdToStrFn","history","msgs","put","messageId","validated","msgIdStr","originatingPeers","iwantCounts","observeDuplicate","msgId","fromPeerIdStr","getWithIWantCount","getGossipIDs","topics","msgIdsByTopic","msgIds","cjs","FloodsubID","GossipsubIDv10","GossipsubIDv11","GossipsubMaxIHaveLength","createGossipRpc","shuffle","messageIdToString","StrictSign","StrictNoSign","SignaturePolicy","PublishConfigType","MessageAcceptance","RejectReason","ValidateError","MessageStatus","rejectReasonFromAcceptance","acceptance","Ignore","Reject","ERR_INVALID_PEER_SCORE_PARAMS","defaultPeerScoreParams","topicScoreCap","appSpecificScore","appSpecificWeight","IPColocationFactorWeight","IPColocationFactorThreshold","IPColocationFactorWhitelist","behaviourPenaltyWeight","behaviourPenaltyThreshold","behaviourPenaltyDecay","decayInterval","decayToZero","retainScore","defaultTopicScoreParams","topicWeight","timeInMeshWeight","timeInMeshQuantum","timeInMeshCap","firstMessageDeliveriesWeight","firstMessageDeliveriesDecay","firstMessageDeliveriesCap","meshMessageDeliveriesWeight","meshMessageDeliveriesDecay","meshMessageDeliveriesCap","meshMessageDeliveriesThreshold","meshMessageDeliveriesWindow","meshMessageDeliveriesActivation","meshFailurePenaltyWeight","meshFailurePenaltyDecay","invalidMessageDeliveriesWeight","invalidMessageDeliveriesDecay","createPeerScoreParams","topicScoreParams","createTopicScoreParams","validateTopicScoreParams","defaultPeerScoreThresholds","gossipThreshold","publishThreshold","graylistThreshold","acceptPXThreshold","opportunisticGraftThreshold","createPeerScoreThresholds","computeScore","pstats","peerIPs","score","tstats","topicParams","topicScore","inMesh","meshTime","p2","firstMessageDeliveries","meshMessageDeliveriesActive","meshMessageDeliveries","deficit","meshFailurePenalty","invalidMessageDeliveries","p5","ips","peersInIP","numPeersInIP","surplus","behaviourPenalty","excess","DeliveryRecordStatus","MessageDeliveries","records","ensureRecord","drec","unknown","firstSeen","isStartable","isInitializable","Components","started","setPeerId","addressManager","setAddressManager","setPeerStore","upgrader","setUpgrader","metrics","setMetrics","setRegistrar","setConnectionManager","transportManager","setTransportManager","connectionGater","setConnectionGater","contentRouting","setContentRouting","peerRouting","setPeerRouting","datastore","setDatastore","connectionProtector","setConnectionProtector","dht","setDHT","setPubSub","startable","beforeStart","afterStart","beforeStop","afterStop","getMetrics","getAddressManager","getPeerStore","getUpgrader","getRegistrar","getConnectionManager","getTransportManager","getConnectionGater","getContentRouting","getPeerRouting","getDatastore","getConnectionProtector","getDHT","getPubSub","PeerScore","validatePeerScoreParams","scoreCacheValidityMs","components","peerStats","_backgroundInterval","background","deliveryRecords","refreshScores","updateIPs","dumpPeerScoreStats","fromEntries","stats","connected","tparams","graftTime","removeIPs","scoreCache","scoreFnCalls","inc","cacheEntry","cacheUntil","scoreFnRuns","scoreCachedDelta","addPenalty","penalty","penaltyLabel","onScorePenalty","addPeer","getIPs","setIPs","removePeer","threshold","getPtopicStats","validateMessage","deliverMessage","markFirstMessageDelivery","markDuplicateMessageDelivery","rejectInvalidMessage","markInvalidMessageDelivery","rejectMessage","duplicateMessage","cap","validatedTime","deliveryDelayMs","isLateDelivery","onDuplicateMsgDelivery","newIPs","oldIPs","addNewIPs","xip","removeOldIPs","topicStats","IWantTracer","gossipsubIWantFollowupMs","requestMsByMsgExpire","requestMsByMsgSize","requestMsByMsg","addPromise","expireByPeer","iwantPromiseStarted","getBrokenPromises","brokenPromises","iwantPromiseBroken","trackMessage","iwantPromiseResolved","iwantPromiseResolvedPeers","maxMs","requestMs","iwantPromiseDeliveryTime","SimpleTimeCache","validityMs","validUntilMs","MessageSource","InclusionReason","ChurnReason","ScorePenalty","IHaveIgnoreReason","ScoreThreshold","hashName","keySize","dek","forgePbkdf2","forgeUtil","SignPrefix","msgIdFnStrictSign","sequenceNumber","seqnoBytes","msgIdFnStrictNoSign","computeScoreWeights","topicStrToLabel","byTopic","topicLabel","topicScores","p1w","p2w","p3w","p3bw","p4w","capF","ws","p5w","p6w","p7w","removeItemsFromSet","superSet","ineed","cond","subset","abortableSource","getIterator","nextAbortHandler","abortHandler","abortMessage","abortCode","isKnownAborter","onReturnError","returnOnAbort","abortable","abortableSink","abortableDuplex","prependAll","sublist","sliceStartInBuf","defaultEncoder","lengthBuf","ReadMode","defaultDecoder","LENGTH","dataLengthLength","DATA","OutboundStream","rawStream","errCallback","closeController","stat","close","InboundStream","GossipStatusCode","GossipSub","constants","stopped","heartbeatDuration","startTimer","heartbeat","finally","heartbeatTimeout","msToNextHeartbeat","hearbeatStartMs","heartbeatInterval","heartbeatSkipped","runHeartbeat","fallbackToFloodsub","floodPublish","doPX","directPeers","Dlo","Dhi","Dscore","Dout","Dlazy","fanoutTTL","minute","mcacheLength","mcacheGossip","seenTTL","prunePeers","pruneBackoff","graftFloodThreshold","opportunisticGraftPeers","opportunisticGraftTicks","directConnectTicks","scoreParams","scoreThresholds","globalSignaturePolicy","multicodecs","debugName","direct","seenCache","publishedMessageIds","msgIdFn","fastMsgIdFn","fastMsgIdCache","mcache","messageCache","dataTransform","metricsRegister","metricsTopicStrToLabel","maxMeshMessageDeliveriesWindowMs","topicParam","register","protocolsEnabled","gauge","help","labelNames","topicSubscriptionStatus","topicPeersCount","meshPeerCounts","meshPeerInclusionEvents","meshPeerChurnEvents","peersPerProtocol","histogram","buckets","asyncValidationResult","asyncValidationMcacheHit","rpcRecvBytes","rpcRecvCount","rpcRecvSubscription","rpcRecvMessage","rpcRecvControl","rpcRecvIHave","rpcRecvIWant","rpcRecvGraft","rpcRecvPrune","rpcRecvNotAccepted","rpcSentBytes","rpcSentCount","rpcSentSubscription","rpcSentMessage","rpcSentControl","rpcSentIHave","rpcSentIWant","rpcSentGraft","rpcSentPrune","msgPublishCount","msgPublishPeers","msgPublishPeersByGroup","msgPublishBytes","msgForwardCount","msgForwardPeers","msgReceivedPreValidation","msgReceivedStatus","msgReceivedInvalid","duplicateMsgDeliveryDelay","maxMeshMessageDeliveriesWindowSec","duplicateMsgLateDelivery","peersByScoreThreshold","avgMinMax","scoreWeights","scorePerMesh","scoringPenalties","ihaveRcvIgnored","ihaveRcvMsgids","ihaveRcvNotSeenMsgids","iwantRcvMsgids","iwantRcvDonthaveMsgids","gossipPromiseExpireSec","cacheSize","mcacheSize","toTopic","topicStr","onJoin","onLeave","onAddToMesh","onRemoveFromMesh","onReportValidationMcacheHit","hit","onReportValidation","onIhaveRcv","idonthave","onIwantRcv","iwantByTopic","iwantDonthave","onForwardMsg","tosendCount","onPublishMsg","tosendGroupCount","dataLen","peerGroup","floodsub","mesh","fanout","onMsgRecvPreValidation","onMsgRecvResult","onMsgRecvInvalid","onRpcRecv","rpcBytes","onRpcSent","registerScores","scores","graylist","publish","registerScoreWeights","sw","wsTopic","registerScorePerMesh","scoreByPeer","peersPerTopicLabel","peersInMesh","meshScores","addCollect","onScrapeMetrics","gossipTracer","maxInboundStreams","maxOutboundStreams","getPeers","publishConfig","signaturePolicy","author","getPublishConfigFromPeerId","outboundInflightQueue","connection","createOutboundStream","addrs","multicodec","onIncomingStream","topology","onPeerConnected","onPeerDisconnected","registrarTopologyIds","directPeerInitial","connect","unregister","outboundStream","streamsOutbound","inboundStream","streamsInbound","heartbeatTimer","fanoutLastpub","peerhave","iasked","outbound","createInboundStream","floodsubPeers","sendSubscriptions","priorInboundStream","pipePeerReadStream","acceptFromWhitelist","peersInTopic","getSubscribers","getTopics","awaitRpcHandler","handleReceivedRpc","acceptFrom","subOpt","handleReceivedSubscription","handleReceivedMessagePromise","handleReceivedMessage","awaitRpcMessageHandler","handleControlMessage","topicSet","rpcMsg","validationResult","validateReceivedMessage","asyncValidation","emitSelf","propagationSource","forwardMessage","fastMsgIdStr","msgIdCached","valid","fromPeerId","rpcMsgPreSign","validateToRawMessage","transformedData","inboundTransform","topicValidator","topicValidators","getScore","toPeer","sendRpc","controlMsg","handleIHave","handleIWant","handleGraft","handlePrune","messagesAccepted","acceptUntil","iask","iwantList","floodCutoff","addBackoff","makePrune","doAddBackoff","pxConnect","applyIwantPenalties","clearBackoff","heartbeatTicks","toconnect","eid","consumePeerRecord","openConnection","getTopologies","wasSubscribed","leave","toAdd","fanoutPeers","fanoutCount","getRandomGossipPeers","sendGraft","meshPeers","sendPrune","selectPeersToForward","excludePeers","tosend","selectPeersToPublish","newFanoutPeers","rawMsg","outboundTransform","buildRawMessage","willSendToSelf","allowPublishToZeroPeers","reportMessageValidationResult","ctrl","piggybackControl","piggybackGossip","outRpc","tograft","toprune","noPX","pruning","emitGossip","peersToGossipByTopic","gossipIDsByTopic","peersToGossip","doEmitGossip","candidateToGossip","factor","peerMessageIDs","pushGossip","flush","controlIHaveMsgs","xid","getRawEnvelope","directConnect","candidateMeshPeers","shuffledPeers","peerStreams","prunePeer","graftPeer","newMeshPeers","removeFirstNItemsFromSet","peersArray","rotate","peersList","medianIndex","medianScore","lastpb","topicPeers","candidateFanoutPeers","sendGraftPrune","backoffSize","peerIdStrs","swPeer","swPeerTopic","swTopic","computeAllPeersScoreWeights","WakuRelay","observers","addObserver","deleteObserver","callbackFn","pDefer","handshake","sourcePromise","sinkErr","sinkPromise","pbStream","shake","lpReader","readLP","readPB","writeLP","writePB","piped","NOISE_MSG_MAX_LENGTH_BYTES","DUMP_SESSION_KEYS","stablelib","hashSHA256","getHKDF","ikm","expand","generateX25519KeyPair","x25519","generateX25519KeyPairFromSeed","generateX25519SharedKey","chaCha20Poly1305Encrypt","seal","chaCha20Poly1305Decrypt","uint16BEEncode","uint16BEDecode","encode0","encode1","decode0","decode1","NoiseHandshakePayload","NoiseHandshakePayloadProto","getPayload","localPeer","staticPublicKey","earlyData","signedPayload","signPayload","getHandshakePayload","earlyDataPayload","libp2pPublicKey","identityKey","identitySig","createHandshakePayload","getPeerIdFromPayload","decodePayload","verifySignedPayload","noiseStaticKey","payloadPeerId","generatedPayload","isValidPublicKey","keyLogger","logLocalStaticKeys","logLocalEphemeralKeys","logRemoteStaticKey","rs","logRemoteEphemeralKey","logCipherState","session","cs1","cs2","getUint64","Nonce","assertValue","AbstractHandshake","encryptWithAd","decryptWithAd","hasKey","isEmptyKey","createEmptyKey","encryptAndHash","mixHash","encryptedMessage","decryptAndHash","derivedU8","mixKey","tempK","initializeKey","initializeSymmetric","protocolName","protocolNameBytes","hashProtocolName","tempk1","tempk2","writeMessageRegular","readMessageRegular","IK","initSession","initiator","prologue","psk","hs","initializeInitiator","initializeResponder","sendMessage","messageBuffer","writeMessageA","writeMessageB","recvMessage","readMessageA","readMessageB","spk","valid1","valid2","FailedIKError","initialMsg","IKHandshake","isInitiator","staticKeypair","remoteStaticKey","remoteEarlyData","receivedMsg","receivedMessageBuffer","decodedPayload","setRemoteEarlyData","getCS","getLocalEphemeralKeys","encryption","UnexpectedPeerError","InvalidCryptoExchangeError","InvalidCryptoTransmissionError","XX","writeMessageC","readMessageC","ephemeral","resultingBuffer","resultingPlaintext","resultingValid","XXHandshake","xx","encode2","decode2","getRemoteStaticKey","XXFallbackHandshake","ephemeralKeys","exchange","mapIterable","PeerMap","PeerSet","predicate","PeerList","peerIds","KeyCache","resetStorage","Noise","staticNoiseKey","useNoisePipes","staticKeys","wrappedConnection","performHandshake","conn","createSecureConnection","tryIK","performXXHandshake","ikHandshake","performIKHandshake","performXXFallbackHandshake","propose","stage0","stage1","secure","user","duplexPair","network","encryptStream","decrypted","decryptStream","MessageTypes","MessageTypeNames","InitiatorMessageTypes","NEW_STREAM","MESSAGE","MESSAGE_INITIATOR","CLOSE","CLOSE_INITIATOR","RESET","RESET_INITIATOR","ReceiverMessageTypes","MESSAGE_RECEIVER","CLOSE_RECEIVER","RESET_RECEIVER","POOL_SIZE","_pool","_poolOffset","_headerInfo","_decodeHeader","readVarInt","REST","MAX_MSG_SIZE","ERR_STREAM_RESET","TrackedMap","system","component","metric","updateComponentMetric","deleted","trackedMap","printMessage","MplexStreamMuxer","_streamId","_streams","initiators","receivers","_createSink","_createSource","streams","registry","_newStream","_newReceiverStream","maxMsgSize","abortController","resetController","Types","externalId","streamName","endErr","sourceEnded","sinkEnded","sinkSunk","timeline","onSinkEnd","closeRead","closeWrite","uint8ArrayList","toSend","metadata","createStream","onStreamEnd","abortSignals","maxSize","checkSize","restrictSize","_handleIncoming","pushableV","maxBufferSize","maxStreamBufferSize","Mplex","createStreamMuxer","socket","cleanup","handleOpen","handleErr","closeOnEnd","ready","wasClean","connectedSource","binaryType","isConnected","connError","cleanUp","cont","onOpen","onMessage","remoteAddress","remotePort","CONNECTING","OPEN","http","https","wsurl","WebSocket","websocket","reduceValue","Reducers","ip4","assumeHttp","explicitPort","tcpUri","dnsaddr","dns4","dns6","p2p","wss","isEnvWithDom","isElectron","detectElectron","isBrowser","isElectronMain","isElectronRenderer","release","isWebWorker","importScripts","WorkerGlobalScope","socketToMaConn","maConn","DNS4","DNS6","DNSADDR","DNS","IP","TCP","UDP","UTP","QUIC","WebSockets","WebSocketsSecure","HTTP","HTTPS","WebRTCStar","WebRTCDirect","Reliable","_P2P","_Circuit","CircuitRecursive","Circuit","makeMatchesFunction","partialMatch","matches","pnames","testMa","mafmt","_connect","upgradeOutbound","cOpts","errorPromise","errfn","rawSocket","toUri","createListener","filters","sortAll","iterable","pathSepS","pathSepB","pathSep","Key","_buf","uint8Array","nanoid","less","list1","list2","withNamespaces","baseNamespace","namespaceType","namespaceValue","isAncestorOf","isDecendantOf","isTopLevel","MemoryDatastore","batch","puts","dels","commit","drain","putMany","deleteMany","it","_all","orders","take","queryKeys","_allKeys","storeAddresses","uniquePeers","seen","requirePeers","DefaultPeerRouting","routers","refreshManagerInit","refreshManager","_findClosestPeersTask","timeoutId","bootDelay","getClosestPeers","router","findPeer","NOT_FOUND","CompoundContentRouting","findProviders","provide","NOT_STARTED_YET","nVals","gotValues","idStr","peerIdFromMultiaddr","defaultAddressFilter","DefaultAddressManager","announce","observed","announceFilter","getListenAddrs","getAnnounceAddrs","getObservedAddrs","addObservedAddr","getAddresses","getAddrs","addrSet","VisibilityChangeEmitter","visibilityChange","_initializeVisibilityVarNames","_addVisibilityChangeListener","mozHidden","msHidden","webkitHidden","_handleVisibilityChange","isVisible","visible","LatencyMonitor","latencyCheckIntervalMs","dataEmitIntervalMs","asyncTestFn","latencyRandomPercentage","latencyCheckMultiply","latencyCheckSubtract","hrtime","getDeltaMS","latencyData","initLatencyData","visibilityChangeEmitter","pageInFocus","_startTimers","_emitSummary","_stopTimers","checkLatencyID","checkLatency","emitIntervalID","unref","summary","getSummary","latency","minMs","avgMs","totalMs","lengthMs","randomness","localData","deltaOffset","deltaMS","NEGATIVE_INFINITY","CLOSING","CLOSED","DialRequest","dialAction","dialer","tokens","getTokens","tokenHolder","dialAbortControllers","completedDials","any","releaseToken","isPrivate","isIpPrivate","publicAddressesFirst","isAPrivate","isBPrivate","isCertified","METRICS","METRICS_COMPONENT","Dialer","addressSorter","maxAddrsToDial","dialTimeout","maxDialsPerPeer","maxParallelDials","pendingDials","pendingDialTargets","dial","pendingTarget","denyDialPeer","dialTarget","_createCancellableDialTarget","pendingDial","_createPendingDial","cancellablePromise","_createDialTarget","knownAddrs","denyDialMultiaddr","supportedAddrs","transportForMultiaddr","dialRequest","timeoutController","run","resolvedMultiaddrs","_resolveRecord","nm","newM","defaultOptions","maxConnections","minConnections","maxData","maxSentData","maxReceivedData","maxEventLoopDelay","pollInterval","autoDialInterval","movingAverageInterval","METRICS_SYSTEM","DefaultConnectionManager","mergeOptions","_checkMetrics","latencyMonitor","startupReconnectTimeout","inbound","conns","allStreams","counts","_onLatencyMeasure","keepAlivePeers","getTags","connectOnStartupController","_close","tasks","connectionList","movingAverages","getGlobal","getMovingAverages","received","dataReceived","movingAverage","_checkMaxLimit","sent","dataSent","_onConnect","storedConns","keyBook","numConnections","toPrune","storedConn","existingConnections","peerConnections","trackedConnection","getAll","STATUS","_maybePruneConnections","peerValues","tags","sortedConnections","peerAValue","peerBValue","toClose","AutoDialler","running","_autoDial","autoDialTimeout","allPeers","CircuitRelay","Status","__StatusValues","__TypeValues","Peer","srcPeer","dstPeer","streamToMaConnection","mapSource","RELAY_CODEC","writeResponse","streamHandler","validateAddrs","HOP","HOP_DST_MULTIADDR_INVALID","STOP_DST_MULTIADDR_INVALID","HOP_SRC_MULTIADDR_INVALID","STOP_SRC_MULTIADDR_INVALID","StreamHandler","handleHop","hopRequest","circuit","hopEnabled","CircuitPB","destinationPeer","destinationConnections","hopActive","stopRequest","destinationStream","sourceStream","_onProtocol","hop","virtualConnection","canHop","handleCanHop","handleStop","localAddr","upgradeInbound","relayAddr","destinationAddr","relayId","destinationId","errMsg","relayPeer","disconnectOnFailure","relayConnection","Errors","listeningAddrs","relayPeerStr","relayPeerId","relayConn","relayedAddr","namespaceToCid","HOP_METADATA_KEY","HOP_METADATA_VALUE","RELAY_RENDEZVOUS_NS","AutoRelay","maxListeners","listenRelays","_onProtocolChange","_onPeerDisconnected","supportsHop","metadataBook","_addListenRelay","_removeListenRelay","remoteAddrs","_listenOnAvailableHopRelays","peersToIgnore","knownHopsToDial","_tryToListenOnRelay","provider","autoRelay","_advertiseService","advertise","privates","CMS","keychain","plain","findKeyByName","getPrivateKey","getFullYear","serverAuth","clientAuth","codeSigning","emailProtection","timeStamping","certificateForKey","cmsData","cms","keyId","asyncCompare","findAsync","findKeyById","missingKeys","infoPrefix","NIST","iterationCount","validateKeyName","randomDelay","DsName","DsInfoName","KeyChain","pass","dsname","importPeer","keyInfo","kid","export","listKeys","oldName","newName","oldDsname","newDsname","oldInfoName","newInfoName","oldPass","newPass","oldDek","newDek","keyAsPEM","DefaultMovingAverage","timespan","variance","deviation","forecast","alpha","previousTime","sqrt","createMovingAverage","DefaultStats","frequencyLastTime","frequencyAccumulators","computeThrottleMaxQueueSize","computeThrottleTimeout","movingAverageIntervals","initialCounters","_resetComputeTimeout","_nextTimeout","urgency","_applyOp","_updateFrequency","latestTime","timeDiff","_updateFrequencyFor","timeDiffMS","hz","directionToEvent","in","DefaultMetrics","statsInit","globalStats","protocolStats","oldPeers","LRU","maxOldPeersRetention","_onMessage","systems","getComponentMetrics","systemMetrics","componentMetrics","calculate","forPeer","idString","getProtocols","forProtocol","updatePlaceholder","placeholderString","placeholderStats","peerIdString","existingStats","mergedStats","trackStream","each","pReflect","isFulfilled","isRejected","_classPrivateFieldInitSpec","privateMap","privateCollection","_classExtractFieldDescriptor","_classPrivateFieldSet","descriptor","_classPrivateFieldGet","_defineProperty","Node","Queue","enqueue","dequeue","pLimit","concurrency","activeCount","generator","pendingCount","clearQueue","pSettle","DefaultTransportManager","transports","faultTolerance","FaultTolerance","FATAL_ALL","getTransports","couldNotListen","NO_FATAL","PROTOCOL_ID","NewLine","writeAll","buffers","select","shakeStream","multistream","ConnectionImpl","getStreams","_getStreams","_closing","addStream","removeStream","DefaultRegistrar","topologies","_onDisconnect","protoBook","protocolList","peerProtocols","oldProtocols","added","findOutgoingStreamLimit","countStreams","streamCount","DefaultUpgrader","connectionEncryption","encrypter","muxers","muxer","inboundUpgradeTimeout","encryptedConn","upgradedConn","muxerFactory","cryptoProtocol","setPeer","proxyPeer","abortableStream","denyInboundConnection","mutableProxy","protectedConn","protector","protect","_encryptInbound","denyInboundEncryptedConnection","multiplexed","_multiplexInbound","denyInboundUpgradedConnection","_createConnection","remotePeerId","denyOutboundConnection","toB58String","_encryptOutbound","denyOutboundEncryptedConnection","_multiplexOutbound","denyOutboundUpgradedConnection","muxedStream","mss","incomingLimit","findIncomingStreamLimit","_onStream","outgoingLimit","_timeline","upgraded","errConnectionNotMultiplexed","multiplexer","secureInbound","secureOutbound","Identify","protocolVersion","agentVersion","listenAddrs","observedAddr","AGENT_VERSION","IdentifyService","identifyProtocolStr","protocolPrefix","identifyPushProtocolStr","identify","pushToPeerStore","_handleIdentify","_handlePush","maxPushIncomingStreams","maxPushOutgoingStreams","unhandle","pushes","maxIdentifyMessageSize","_identify","cleanObservedAddr","getCleanMultiaddr","peerData","peerRecordEnvelope","FetchRequest","FetchResponse","identifier","StatusCode","__StatusCodeValues","FetchService","lookupFunctions","handleMessage","OK","ERROR","errmsg","_getLookupFunction","registerLookupFunction","unregisterLookupFunction","PingService","isLoopback","DEFAULT_TTL","highPort","NatManager","externalAddress","localAddress","description","keepAlive","gateway","_start","_getClient","publicIp","externalIp","isPrivateIp","publicPort","localPort","fromNodeAddress","upnpNat","PeerRecordUpdater","DHTPeerRouting","closer","EVENT_NAME","allowAll","PeerStoreAddressBook","addressFilter","lock","writeLock","updatedPeer","storedEnvelope","storedRecord","filterMultiaddrs","patchOrCreate","oldMultiaddrs","readLock","hasPeer","mergeOrCreate","PeerStoreKeyBook","updatedKey","uint8arrayEquals","oldPublicKey","PeerStoreMetadataBook","oldMetadata","existingValue","patch","PeerStoreProtoBook","protocolSet","Address","Metadata","_PriorityQueue_queue","PriorityQueue","comparator","step","lowerBound","_PQueue_instances","_PQueue_carryoverConcurrencyCount","_PQueue_isIntervalIgnored","_PQueue_intervalCount","_PQueue_intervalCap","_PQueue_interval","_PQueue_intervalEnd","_PQueue_intervalId","_PQueue_timeoutId","_PQueue_queue","_PQueue_queueClass","_PQueue_pendingCount","_PQueue_concurrency","_PQueue_isPaused","_PQueue_throwOnTimeout","_PQueue_doesIntervalAllowAnother_get","_PQueue_doesConcurrentAllowAnother_get","_PQueue_next","_PQueue_emitEvents","_PQueue_onResumeInterval","_PQueue_isIntervalPaused_get","_PQueue_tryToStartAnother","_PQueue_initializeIntervalIfNeeded","_PQueue_onInterval","_PQueue_processQueue","_PQueue_onEvent","__classPrivateFieldSet","PQueue","_a","_b","_c","_d","carryoverConcurrencyCount","intervalCap","autoStart","queueClass","throwOnTimeout","newConcurrency","functions","pause","sizeBy","canInitializeInterval","job","WORKER_REQUEST_READ_LOCK","WORKER_RELEASE_READ_LOCK","MASTER_GRANT_READ_LOCK","WORKER_REQUEST_WRITE_LOCK","WORKER_RELEASE_WRITE_LOCK","MASTER_GRANT_WRITE_LOCK","observable","handleWorkerLockRequest","masterEvent","releaseType","grantType","requestEvent","MessageEvent","releaseEventListener","releaseEvent","makeWorkerLockRequest","responseEvent","singleProcess","mutexes","createReleaseable","createMortice","observer","isWorker","impl","masterQueue","readQueue","localReadQueue","readPromise","onIdle","createMutex","NAMESPACE_COMMON","PersistentStore","mortice","_peerIdToDatastoreKey","b32key","PeerPB","addressSet","_patch","_merge","addrStr","base32Str","Tags","Tag","expiry","PersistentPeerStore","providedValue","unexpiredTags","DHTContentRouting","providers","AutoDialer","globalFetch","globalHeaders","Headers","Request","Response","buildResource","serverResolver","recordType","resource","req","nativeFetch","accept","getCacheKey","maxCache","_TXTcache","_servers","_request","_abortControllers","getServers","_getShuffledServers","newServers","setServers","servers","rrType","resolve4","resolve6","resolveTxt","Answer","TTL","dnsaddrCode","DefaultConfig","noAnnounce","autoDial","Resolver","nat","active","PeerIdProto","createFromPrivKey","marshalPublicKey","marshalPrivateKey","DummyDHT","wan","DHT_DISABLED","lan","DummyPubSub","PUBSUB_DISABLED","Libp2pNode","initializables","filterMultiaddrForPeer","services","configureComponent","streamMuxers","keychainOpts","generateOptions","identifyService","peerRouters","onDiscoveryPeer","contentRouters","fetchService","pingService","autoDialer","peerDiscovery","servce","peerSet","closeConnections","peerInfo","peerKey","createLibp2pNode","createEd25519PeerId","resultingOptions","ERR_TRANSPORTS_REQUIRED","CONN_ENCRYPTION_REQUIRED","LIBP2P_FORCE_PNET","ERR_PROTECTOR_REQUIRED","validateConfig","getPseudoRandomSubset","wantedNumber","randInt","PeerDiscoveryStaticPeers","DefaultInterval","maxPeers","peerMas","_startTimer","_returnPeers","Fleet","fleets","createWaku","libp2pOptions","defaultBootstrap","nodes","fleet","Prod","Test","getPredefinedBootstrapNodes","wakuRelay","createLibp2p","filterAll","defaultLibp2p","wakuStore","wakuLightPush","wakuFilter","ContentTopic","SimpleChatMessage","setWaku","React","wakuStatus","setWakuStatus","sendCounter","setSendCounter","setMessages","processIncomingMessage","wakuMessage","ReactDOM","getElementById"],"sourceRoot":""} \ No newline at end of file diff --git a/store-js b/store-js new file mode 100644 index 0000000..ccb9ca8 --- /dev/null +++ b/store-js @@ -0,0 +1,83 @@ + + + + + + + JS-Waku store script tag example + + + + +

Timestamp of latest message seen in store

+
+ + + + + diff --git a/store-reactjs-chat/asset-manifest.json b/store-reactjs-chat/asset-manifest.json new file mode 100644 index 0000000..8682a2c --- /dev/null +++ b/store-reactjs-chat/asset-manifest.json @@ -0,0 +1,14 @@ +{ + "files": { + "main.css": "/store-reactjs-chat/static/css/main.e6c13ad2.css", + "main.js": "/store-reactjs-chat/static/js/main.dce8435a.js", + "static/media/rpc.cjs": "/store-reactjs-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs", + "index.html": "/store-reactjs-chat/index.html", + "main.e6c13ad2.css.map": "/store-reactjs-chat/static/css/main.e6c13ad2.css.map", + "main.dce8435a.js.map": "/store-reactjs-chat/static/js/main.dce8435a.js.map" + }, + "entrypoints": [ + "static/css/main.e6c13ad2.css", + "static/js/main.dce8435a.js" + ] +} \ No newline at end of file diff --git a/store-reactjs-chat/favicon.ico b/store-reactjs-chat/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..a11777cc471a4344702741ab1c8a588998b1311a GIT binary patch literal 3870 zcma);c{J4h9>;%nil|2-o+rCuEF-(I%-F}ijC~o(k~HKAkr0)!FCj~d>`RtpD?8b; zXOC1OD!V*IsqUwzbMF1)-gEDD=A573Z-&G7^LoAC9|WO7Xc0Cx1g^Zu0u_SjAPB
3vGa^W|sj)80f#V0@M_CAZTIO(t--xg= z!sii`1giyH7EKL_+Wi0ab<)&E_0KD!3Rp2^HNB*K2@PHCs4PWSA32*-^7d{9nH2_E zmC{C*N*)(vEF1_aMamw2A{ZH5aIDqiabnFdJ|y0%aS|64E$`s2ccV~3lR!u<){eS` z#^Mx6o(iP1Ix%4dv`t@!&Za-K@mTm#vadc{0aWDV*_%EiGK7qMC_(`exc>-$Gb9~W!w_^{*pYRm~G zBN{nA;cm^w$VWg1O^^<6vY`1XCD|s_zv*g*5&V#wv&s#h$xlUilPe4U@I&UXZbL z0)%9Uj&@yd03n;!7do+bfixH^FeZ-Ema}s;DQX2gY+7g0s(9;`8GyvPY1*vxiF&|w z>!vA~GA<~JUqH}d;DfBSi^IT*#lrzXl$fNpq0_T1tA+`A$1?(gLb?e#0>UELvljtQ zK+*74m0jn&)5yk8mLBv;=@}c{t0ztT<v;Avck$S6D`Z)^c0(jiwKhQsn|LDRY&w(Fmi91I7H6S;b0XM{e zXp0~(T@k_r-!jkLwd1_Vre^v$G4|kh4}=Gi?$AaJ)3I+^m|Zyj#*?Kp@w(lQdJZf4 z#|IJW5z+S^e9@(6hW6N~{pj8|NO*>1)E=%?nNUAkmv~OY&ZV;m-%?pQ_11)hAr0oAwILrlsGawpxx4D43J&K=n+p3WLnlDsQ$b(9+4 z?mO^hmV^F8MV{4Lx>(Q=aHhQ1){0d*(e&s%G=i5rq3;t{JC zmgbn5Nkl)t@fPH$v;af26lyhH!k+#}_&aBK4baYPbZy$5aFx4}ka&qxl z$=Rh$W;U)>-=S-0=?7FH9dUAd2(q#4TCAHky!$^~;Dz^j|8_wuKc*YzfdAht@Q&ror?91Dm!N03=4=O!a)I*0q~p0g$Fm$pmr$ zb;wD;STDIi$@M%y1>p&_>%?UP($15gou_ue1u0!4(%81;qcIW8NyxFEvXpiJ|H4wz z*mFT(qVx1FKufG11hByuX%lPk4t#WZ{>8ka2efjY`~;AL6vWyQKpJun2nRiZYDij$ zP>4jQXPaP$UC$yIVgGa)jDV;F0l^n(V=HMRB5)20V7&r$jmk{UUIe zVjKroK}JAbD>B`2cwNQ&GDLx8{pg`7hbA~grk|W6LgiZ`8y`{Iq0i>t!3p2}MS6S+ zO_ruKyAElt)rdS>CtF7j{&6rP-#c=7evGMt7B6`7HG|-(WL`bDUAjyn+k$mx$CH;q2Dz4x;cPP$hW=`pFfLO)!jaCL@V2+F)So3}vg|%O*^T1j>C2lx zsURO-zIJC$^$g2byVbRIo^w>UxK}74^TqUiRR#7s_X$e)$6iYG1(PcW7un-va-S&u zHk9-6Zn&>T==A)lM^D~bk{&rFzCi35>UR!ZjQkdSiNX*-;l4z9j*7|q`TBl~Au`5& z+c)*8?#-tgUR$Zd%Q3bs96w6k7q@#tUn`5rj+r@_sAVVLqco|6O{ILX&U-&-cbVa3 zY?ngHR@%l{;`ri%H*0EhBWrGjv!LE4db?HEWb5mu*t@{kv|XwK8?npOshmzf=vZA@ zVSN9sL~!sn?r(AK)Q7Jk2(|M67Uy3I{eRy z_l&Y@A>;vjkWN5I2xvFFTLX0i+`{qz7C_@bo`ZUzDugfq4+>a3?1v%)O+YTd6@Ul7 zAfLfm=nhZ`)P~&v90$&UcF+yXm9sq!qCx3^9gzIcO|Y(js^Fj)Rvq>nQAHI92ap=P z10A4@prk+AGWCb`2)dQYFuR$|H6iDE8p}9a?#nV2}LBCoCf(Xi2@szia7#gY>b|l!-U`c}@ zLdhvQjc!BdLJvYvzzzngnw51yRYCqh4}$oRCy-z|v3Hc*d|?^Wj=l~18*E~*cR_kU z{XsxM1i{V*4GujHQ3DBpl2w4FgFR48Nma@HPgnyKoIEY-MqmMeY=I<%oG~l!f<+FN z1ZY^;10j4M4#HYXP zw5eJpA_y(>uLQ~OucgxDLuf}fVs272FaMxhn4xnDGIyLXnw>Xsd^J8XhcWIwIoQ9} z%FoSJTAGW(SRGwJwb=@pY7r$uQRK3Zd~XbxU)ts!4XsJrCycrWSI?e!IqwqIR8+Jh zlRjZ`UO1I!BtJR_2~7AbkbSm%XQqxEPkz6BTGWx8e}nQ=w7bZ|eVP4?*Tb!$(R)iC z9)&%bS*u(lXqzitAN)Oo=&Ytn>%Hzjc<5liuPi>zC_nw;Z0AE3Y$Jao_Q90R-gl~5 z_xAb2J%eArrC1CN4G$}-zVvCqF1;H;abAu6G*+PDHSYFx@Tdbfox*uEd3}BUyYY-l zTfEsOqsi#f9^FoLO;ChK<554qkri&Av~SIM*{fEYRE?vH7pTAOmu2pz3X?Wn*!ROX ztd54huAk&mFBemMooL33RV-*1f0Q3_(7hl$<#*|WF9P!;r;4_+X~k~uKEqdzZ$5Al zV63XN@)j$FN#cCD;ek1R#l zv%pGrhB~KWgoCj%GT?%{@@o(AJGt*PG#l3i>lhmb_twKH^EYvacVY-6bsCl5*^~L0 zonm@lk2UvvTKr2RS%}T>^~EYqdL1q4nD%0n&Xqr^cK^`J5W;lRRB^R-O8b&HENO||mo0xaD+S=I8RTlIfVgqN@SXDr2&-)we--K7w= zJVU8?Z+7k9dy;s;^gDkQa`0nz6N{T?(A&Iz)2!DEecLyRa&FI!id#5Z7B*O2=PsR0 zEvc|8{NS^)!d)MDX(97Xw}m&kEO@5jqRaDZ!+%`wYOI<23q|&js`&o4xvjP7D_xv@ z5hEwpsp{HezI9!~6O{~)lLR@oF7?J7i>1|5a~UuoN=q&6N}EJPV_GD`&M*v8Y`^2j zKII*d_@Fi$+i*YEW+Hbzn{iQk~yP z>7N{S4)r*!NwQ`(qcN#8SRQsNK6>{)X12nbF`*7#ecO7I)Q$uZsV+xS4E7aUn+U(K baj7?x%VD!5Cxk2YbYLNVeiXvvpMCWYo=by@ literal 0 HcmV?d00001 diff --git a/store-reactjs-chat/index.html b/store-reactjs-chat/index.html new file mode 100644 index 0000000..fd9a90f --- /dev/null +++ b/store-reactjs-chat/index.html @@ -0,0 +1 @@ +React App
\ No newline at end of file diff --git a/store-reactjs-chat/logo192.png b/store-reactjs-chat/logo192.png new file mode 100644 index 0000000000000000000000000000000000000000..fc44b0a3796c0e0a64c3d858ca038bd4570465d9 GIT binary patch literal 5347 zcmZWtbyO6NvR-oO24RV%BvuJ&=?+<7=`LvyB&A_#M7mSDYw1v6DJkiYl9XjT!%$dLEBTQ8R9|wd3008in6lFF3GV-6mLi?MoP_y~}QUnaDCHI#t z7w^m$@6DI)|C8_jrT?q=f8D?0AM?L)Z}xAo^e^W>t$*Y0KlT5=@bBjT9kxb%-KNdk zeOS1tKO#ChhG7%{ApNBzE2ZVNcxbrin#E1TiAw#BlUhXllzhN$qWez5l;h+t^q#Eav8PhR2|T}y5kkflaK`ba-eoE+Z2q@o6P$)=&` z+(8}+-McnNO>e#$Rr{32ngsZIAX>GH??tqgwUuUz6kjns|LjsB37zUEWd|(&O!)DY zQLrq%Y>)Y8G`yYbYCx&aVHi@-vZ3|ebG!f$sTQqMgi0hWRJ^Wc+Ibv!udh_r%2|U) zPi|E^PK?UE!>_4`f`1k4hqqj_$+d!EB_#IYt;f9)fBOumGNyglU(ofY`yHq4Y?B%- zp&G!MRY<~ajTgIHErMe(Z8JG*;D-PJhd@RX@QatggM7+G(Lz8eZ;73)72Hfx5KDOE zkT(m}i2;@X2AT5fW?qVp?@WgN$aT+f_6eo?IsLh;jscNRp|8H}Z9p_UBO^SJXpZew zEK8fz|0Th%(Wr|KZBGTM4yxkA5CFdAj8=QSrT$fKW#tweUFqr0TZ9D~a5lF{)%-tTGMK^2tz(y2v$i%V8XAxIywrZCp=)83p(zIk6@S5AWl|Oa2hF`~~^W zI;KeOSkw1O#TiQ8;U7OPXjZM|KrnN}9arP)m0v$c|L)lF`j_rpG(zW1Qjv$=^|p*f z>)Na{D&>n`jOWMwB^TM}slgTEcjxTlUby89j1)|6ydRfWERn3|7Zd2&e7?!K&5G$x z`5U3uFtn4~SZq|LjFVrz$3iln-+ucY4q$BC{CSm7Xe5c1J<=%Oagztj{ifpaZk_bQ z9Sb-LaQMKp-qJA*bP6DzgE3`}*i1o3GKmo2pn@dj0;He}F=BgINo};6gQF8!n0ULZ zL>kC0nPSFzlcB7p41doao2F7%6IUTi_+!L`MM4o*#Y#0v~WiO8uSeAUNp=vA2KaR&=jNR2iVwG>7t%sG2x_~yXzY)7K& zk3p+O0AFZ1eu^T3s};B%6TpJ6h-Y%B^*zT&SN7C=N;g|#dGIVMSOru3iv^SvO>h4M=t-N1GSLLDqVTcgurco6)3&XpU!FP6Hlrmj}f$ zp95;b)>M~`kxuZF3r~a!rMf4|&1=uMG$;h^g=Kl;H&Np-(pFT9FF@++MMEx3RBsK?AU0fPk-#mdR)Wdkj)`>ZMl#^<80kM87VvsI3r_c@_vX=fdQ`_9-d(xiI z4K;1y1TiPj_RPh*SpDI7U~^QQ?%0&!$Sh#?x_@;ag)P}ZkAik{_WPB4rHyW#%>|Gs zdbhyt=qQPA7`?h2_8T;-E6HI#im9K>au*(j4;kzwMSLgo6u*}-K`$_Gzgu&XE)udQ zmQ72^eZd|vzI)~!20JV-v-T|<4@7ruqrj|o4=JJPlybwMg;M$Ud7>h6g()CT@wXm` zbq=A(t;RJ^{Xxi*Ff~!|3!-l_PS{AyNAU~t{h;(N(PXMEf^R(B+ZVX3 z8y0;0A8hJYp@g+c*`>eTA|3Tgv9U8#BDTO9@a@gVMDxr(fVaEqL1tl?md{v^j8aUv zm&%PX4^|rX|?E4^CkplWWNv*OKM>DxPa z!RJ)U^0-WJMi)Ksc!^ixOtw^egoAZZ2Cg;X7(5xZG7yL_;UJ#yp*ZD-;I^Z9qkP`} zwCTs0*%rIVF1sgLervtnUo&brwz?6?PXRuOCS*JI-WL6GKy7-~yi0giTEMmDs_-UX zo=+nFrW_EfTg>oY72_4Z0*uG>MnXP=c0VpT&*|rvv1iStW;*^={rP1y?Hv+6R6bxFMkxpWkJ>m7Ba{>zc_q zEefC3jsXdyS5??Mz7IET$Kft|EMNJIv7Ny8ZOcKnzf`K5Cd)&`-fTY#W&jnV0l2vt z?Gqhic}l}mCv1yUEy$%DP}4AN;36$=7aNI^*AzV(eYGeJ(Px-j<^gSDp5dBAv2#?; zcMXv#aj>%;MiG^q^$0MSg-(uTl!xm49dH!{X0){Ew7ThWV~Gtj7h%ZD zVN-R-^7Cf0VH!8O)uUHPL2mO2tmE*cecwQv_5CzWeh)ykX8r5Hi`ehYo)d{Jnh&3p z9ndXT$OW51#H5cFKa76c<%nNkP~FU93b5h-|Cb}ScHs@4Q#|}byWg;KDMJ#|l zE=MKD*F@HDBcX@~QJH%56eh~jfPO-uKm}~t7VkHxHT;)4sd+?Wc4* z>CyR*{w@4(gnYRdFq=^(#-ytb^5ESD?x<0Skhb%Pt?npNW1m+Nv`tr9+qN<3H1f<% zZvNEqyK5FgPsQ`QIu9P0x_}wJR~^CotL|n zk?dn;tLRw9jJTur4uWoX6iMm914f0AJfB@C74a;_qRrAP4E7l890P&{v<}>_&GLrW z)klculcg`?zJO~4;BBAa=POU%aN|pmZJn2{hA!d!*lwO%YSIzv8bTJ}=nhC^n}g(ld^rn#kq9Z3)z`k9lvV>y#!F4e{5c$tnr9M{V)0m(Z< z#88vX6-AW7T2UUwW`g<;8I$Jb!R%z@rCcGT)-2k7&x9kZZT66}Ztid~6t0jKb&9mm zpa}LCb`bz`{MzpZR#E*QuBiZXI#<`5qxx=&LMr-UUf~@dRk}YI2hbMsAMWOmDzYtm zjof16D=mc`^B$+_bCG$$@R0t;e?~UkF?7<(vkb70*EQB1rfUWXh$j)R2)+dNAH5%R zEBs^?N;UMdy}V};59Gu#0$q53$}|+q7CIGg_w_WlvE}AdqoS<7DY1LWS9?TrfmcvT zaypmplwn=P4;a8-%l^e?f`OpGb}%(_mFsL&GywhyN(-VROj`4~V~9bGv%UhcA|YW% zs{;nh@aDX11y^HOFXB$a7#Sr3cEtNd4eLm@Y#fc&j)TGvbbMwze zXtekX_wJqxe4NhuW$r}cNy|L{V=t#$%SuWEW)YZTH|!iT79k#?632OFse{+BT_gau zJwQcbH{b}dzKO?^dV&3nTILYlGw{27UJ72ZN){BILd_HV_s$WfI2DC<9LIHFmtyw? zQ;?MuK7g%Ym+4e^W#5}WDLpko%jPOC=aN)3!=8)s#Rnercak&b3ESRX3z{xfKBF8L z5%CGkFmGO@x?_mPGlpEej!3!AMddChabyf~nJNZxx!D&{@xEb!TDyvqSj%Y5@A{}9 zRzoBn0?x}=krh{ok3Nn%e)#~uh;6jpezhA)ySb^b#E>73e*frBFu6IZ^D7Ii&rsiU z%jzygxT-n*joJpY4o&8UXr2s%j^Q{?e-voloX`4DQyEK+DmrZh8A$)iWL#NO9+Y@!sO2f@rI!@jN@>HOA< z?q2l{^%mY*PNx2FoX+A7X3N}(RV$B`g&N=e0uvAvEN1W^{*W?zT1i#fxuw10%~))J zjx#gxoVlXREWZf4hRkgdHx5V_S*;p-y%JtGgQ4}lnA~MBz-AFdxUxU1RIT$`sal|X zPB6sEVRjGbXIP0U+?rT|y5+ev&OMX*5C$n2SBPZr`jqzrmpVrNciR0e*Wm?fK6DY& zl(XQZ60yWXV-|Ps!A{EF;=_z(YAF=T(-MkJXUoX zI{UMQDAV2}Ya?EisdEW;@pE6dt;j0fg5oT2dxCi{wqWJ<)|SR6fxX~5CzblPGr8cb zUBVJ2CQd~3L?7yfTpLNbt)He1D>*KXI^GK%<`bq^cUq$Q@uJifG>p3LU(!H=C)aEL zenk7pVg}0{dKU}&l)Y2Y2eFMdS(JS0}oZUuVaf2+K*YFNGHB`^YGcIpnBlMhO7d4@vV zv(@N}(k#REdul8~fP+^F@ky*wt@~&|(&&meNO>rKDEnB{ykAZ}k>e@lad7to>Ao$B zz<1(L=#J*u4_LB=8w+*{KFK^u00NAmeNN7pr+Pf+N*Zl^dO{LM-hMHyP6N!~`24jd zXYP|Ze;dRXKdF2iJG$U{k=S86l@pytLx}$JFFs8e)*Vi?aVBtGJ3JZUj!~c{(rw5>vuRF$`^p!P8w1B=O!skwkO5yd4_XuG^QVF z`-r5K7(IPSiKQ2|U9+`@Js!g6sfJwAHVd|s?|mnC*q zp|B|z)(8+mxXyxQ{8Pg3F4|tdpgZZSoU4P&9I8)nHo1@)9_9u&NcT^FI)6|hsAZFk zZ+arl&@*>RXBf-OZxhZerOr&dN5LW9@gV=oGFbK*J+m#R-|e6(Loz(;g@T^*oO)0R zN`N=X46b{7yk5FZGr#5&n1!-@j@g02g|X>MOpF3#IjZ_4wg{dX+G9eqS+Es9@6nC7 zD9$NuVJI}6ZlwtUm5cCAiYv0(Yi{%eH+}t)!E^>^KxB5^L~a`4%1~5q6h>d;paC9c zTj0wTCKrhWf+F#5>EgX`sl%POl?oyCq0(w0xoL?L%)|Q7d|Hl92rUYAU#lc**I&^6p=4lNQPa0 znQ|A~i0ip@`B=FW-Q;zh?-wF;Wl5!+q3GXDu-x&}$gUO)NoO7^$BeEIrd~1Dh{Tr` z8s<(Bn@gZ(mkIGnmYh_ehXnq78QL$pNDi)|QcT*|GtS%nz1uKE+E{7jdEBp%h0}%r zD2|KmYGiPa4;md-t_m5YDz#c*oV_FqXd85d@eub?9N61QuYcb3CnVWpM(D-^|CmkL z(F}L&N7qhL2PCq)fRh}XO@U`Yn<?TNGR4L(mF7#4u29{i~@k;pLsgl({YW5`Mo+p=zZn3L*4{JU;++dG9 X@eDJUQo;Ye2mwlRs?y0|+_a0zY+Zo%Dkae}+MySoIppb75o?vUW_?)>@g{U2`ERQIXV zeY$JrWnMZ$QC<=ii4X|@0H8`si75jB(ElJb00HAB%>SlLR{!zO|C9P3zxw_U8?1d8uRZ=({Ga4shyN}3 zAK}WA(ds|``G4jA)9}Bt2Hy0+f3rV1E6b|@?hpGA=PI&r8)ah|)I2s(P5Ic*Ndhn^ z*T&j@gbCTv7+8rpYbR^Ty}1AY)YH;p!m948r#%7x^Z@_-w{pDl|1S4`EM3n_PaXvK z1JF)E3qy$qTj5Xs{jU9k=y%SQ0>8E$;x?p9ayU0bZZeo{5Z@&FKX>}s!0+^>C^D#z z>xsCPvxD3Z=dP}TTOSJhNTPyVt14VCQ9MQFN`rn!c&_p?&4<5_PGm4a;WS&1(!qKE z_H$;dDdiPQ!F_gsN`2>`X}$I=B;={R8%L~`>RyKcS$72ai$!2>d(YkciA^J0@X%G4 z4cu!%Ps~2JuJ8ex`&;Fa0NQOq_nDZ&X;^A=oc1&f#3P1(!5il>6?uK4QpEG8z0Rhu zvBJ+A9RV?z%v?!$=(vcH?*;vRs*+PPbOQ3cdPr5=tOcLqmfx@#hOqX0iN)wTTO21jH<>jpmwRIAGw7`a|sl?9y9zRBh>(_%| zF?h|P7}~RKj?HR+q|4U`CjRmV-$mLW>MScKnNXiv{vD3&2@*u)-6P@h0A`eeZ7}71 zK(w%@R<4lLt`O7fs1E)$5iGb~fPfJ?WxhY7c3Q>T-w#wT&zW522pH-B%r5v#5y^CF zcC30Se|`D2mY$hAlIULL%-PNXgbbpRHgn<&X3N9W!@BUk@9g*P5mz-YnZBb*-$zMM z7Qq}ic0mR8n{^L|=+diODdV}Q!gwr?y+2m=3HWwMq4z)DqYVg0J~^}-%7rMR@S1;9 z7GFj6K}i32X;3*$SmzB&HW{PJ55kT+EI#SsZf}bD7nW^Haf}_gXciYKX{QBxIPSx2Ma? zHQqgzZq!_{&zg{yxqv3xq8YV+`S}F6A>Gtl39_m;K4dA{pP$BW0oIXJ>jEQ!2V3A2 zdpoTxG&V=(?^q?ZTj2ZUpDUdMb)T?E$}CI>r@}PFPWD9@*%V6;4Ag>D#h>!s)=$0R zRXvdkZ%|c}ubej`jl?cS$onl9Tw52rBKT)kgyw~Xy%z62Lr%V6Y=f?2)J|bZJ5(Wx zmji`O;_B+*X@qe-#~`HFP<{8$w@z4@&`q^Q-Zk8JG3>WalhnW1cvnoVw>*R@c&|o8 zZ%w!{Z+MHeZ*OE4v*otkZqz11*s!#s^Gq>+o`8Z5 z^i-qzJLJh9!W-;SmFkR8HEZJWiXk$40i6)7 zZpr=k2lp}SasbM*Nbn3j$sn0;rUI;%EDbi7T1ZI4qL6PNNM2Y%6{LMIKW+FY_yF3) zSKQ2QSujzNMSL2r&bYs`|i2Dnn z=>}c0>a}>|uT!IiMOA~pVT~R@bGlm}Edf}Kq0?*Af6#mW9f9!}RjW7om0c9Qlp;yK z)=XQs(|6GCadQbWIhYF=rf{Y)sj%^Id-ARO0=O^Ad;Ph+ z0?$eE1xhH?{T$QI>0JP75`r)U_$#%K1^BQ8z#uciKf(C701&RyLQWBUp*Q7eyn76} z6JHpC9}R$J#(R0cDCkXoFSp;j6{x{b&0yE@P7{;pCEpKjS(+1RQy38`=&Yxo%F=3y zCPeefABp34U-s?WmU#JJw23dcC{sPPFc2#J$ZgEN%zod}J~8dLm*fx9f6SpO zn^Ww3bt9-r0XaT2a@Wpw;C23XM}7_14#%QpubrIw5aZtP+CqIFmsG4`Cm6rfxl9n5 z7=r2C-+lM2AB9X0T_`?EW&Byv&K?HS4QLoylJ|OAF z`8atBNTzJ&AQ!>sOo$?^0xj~D(;kS$`9zbEGd>f6r`NC3X`tX)sWgWUUOQ7w=$TO&*j;=u%25ay-%>3@81tGe^_z*C7pb9y*Ed^H3t$BIKH2o+olp#$q;)_ zfpjCb_^VFg5fU~K)nf*d*r@BCC>UZ!0&b?AGk_jTPXaSnCuW110wjHPPe^9R^;jo3 zwvzTl)C`Zl5}O2}3lec=hZ*$JnkW#7enKKc)(pM${_$9Hc=Sr_A9Biwe*Y=T?~1CK z6eZ9uPICjy-sMGbZl$yQmpB&`ouS8v{58__t0$JP%i3R&%QR3ianbZqDs<2#5FdN@n5bCn^ZtH992~5k(eA|8|@G9u`wdn7bnpg|@{m z^d6Y`*$Zf2Xr&|g%sai#5}Syvv(>Jnx&EM7-|Jr7!M~zdAyjt*xl;OLhvW-a%H1m0 z*x5*nb=R5u><7lyVpNAR?q@1U59 zO+)QWwL8t zyip?u_nI+K$uh{y)~}qj?(w0&=SE^8`_WMM zTybjG=999h38Yes7}-4*LJ7H)UE8{mE(6;8voE+TYY%33A>S6`G_95^5QHNTo_;Ao ztIQIZ_}49%{8|=O;isBZ?=7kfdF8_@azfoTd+hEJKWE!)$)N%HIe2cplaK`ry#=pV z0q{9w-`i0h@!R8K3GC{ivt{70IWG`EP|(1g7i_Q<>aEAT{5(yD z=!O?kq61VegV+st@XCw475j6vS)_z@efuqQgHQR1T4;|-#OLZNQJPV4k$AX1Uk8Lm z{N*b*ia=I+MB}kWpupJ~>!C@xEN#Wa7V+7{m4j8c?)ChV=D?o~sjT?0C_AQ7B-vxqX30s0I_`2$in86#`mAsT-w?j{&AL@B3$;P z31G4(lV|b}uSDCIrjk+M1R!X7s4Aabn<)zpgT}#gE|mIvV38^ODy@<&yflpCwS#fRf9ZX3lPV_?8@C5)A;T zqmouFLFk;qIs4rA=hh=GL~sCFsXHsqO6_y~*AFt939UYVBSx1s(=Kb&5;j7cSowdE;7()CC2|-i9Zz+_BIw8#ll~-tyH?F3{%`QCsYa*b#s*9iCc`1P1oC26?`g<9))EJ3%xz+O!B3 zZ7$j~To)C@PquR>a1+Dh>-a%IvH_Y7^ys|4o?E%3`I&ADXfC8++hAdZfzIT#%C+Jz z1lU~K_vAm0m8Qk}K$F>|>RPK%<1SI0(G+8q~H zAsjezyP+u!Se4q3GW)`h`NPSRlMoBjCzNPesWJwVTY!o@G8=(6I%4XHGaSiS3MEBK zhgGFv6Jc>L$4jVE!I?TQuwvz_%CyO!bLh94nqK11C2W$*aa2ueGopG8DnBICVUORP zgytv#)49fVXDaR$SukloYC3u7#5H)}1K21=?DKj^U)8G;MS)&Op)g^zR2($<>C*zW z;X7`hLxiIO#J`ANdyAOJle4V%ppa*(+0i3w;8i*BA_;u8gOO6)MY`ueq7stBMJTB; z-a0R>hT*}>z|Gg}@^zDL1MrH+2hsR8 zHc}*9IvuQC^Ju)^#Y{fOr(96rQNPNhxc;mH@W*m206>Lo<*SaaH?~8zg&f&%YiOEG zGiz?*CP>Bci}!WiS=zj#K5I}>DtpregpP_tfZtPa(N<%vo^#WCQ5BTv0vr%Z{)0q+ z)RbfHktUm|lg&U3YM%lMUM(fu}i#kjX9h>GYctkx9Mt_8{@s%!K_EI zScgwy6%_fR?CGJQtmgNAj^h9B#zmaMDWgH55pGuY1Gv7D z;8Psm(vEPiwn#MgJYu4Ty9D|h!?Rj0ddE|&L3S{IP%H4^N!m`60ZwZw^;eg4sk6K{ ziA^`Sbl_4~f&Oo%n;8Ye(tiAdlZKI!Z=|j$5hS|D$bDJ}p{gh$KN&JZYLUjv4h{NY zBJ>X9z!xfDGY z+oh_Z&_e#Q(-}>ssZfm=j$D&4W4FNy&-kAO1~#3Im;F)Nwe{(*75(p=P^VI?X0GFakfh+X-px4a%Uw@fSbmp9hM1_~R>?Z8+ ziy|e9>8V*`OP}4x5JjdWp}7eX;lVxp5qS}0YZek;SNmm7tEeSF*-dI)6U-A%m6YvCgM(}_=k#a6o^%-K4{`B1+}O4x zztDT%hVb;v#?j`lTvlFQ3aV#zkX=7;YFLS$uIzb0E3lozs5`Xy zi~vF+%{z9uLjKvKPhP%x5f~7-Gj+%5N`%^=yk*Qn{`> z;xj&ROY6g`iy2a@{O)V(jk&8#hHACVDXey5a+KDod_Z&}kHM}xt7}Md@pil{2x7E~ zL$k^d2@Ec2XskjrN+IILw;#7((abu;OJii&v3?60x>d_Ma(onIPtcVnX@ELF0aL?T zSmWiL3(dOFkt!x=1O!_0n(cAzZW+3nHJ{2S>tgSK?~cFha^y(l@-Mr2W$%MN{#af8J;V*>hdq!gx=d0h$T7l}>91Wh07)9CTX zh2_ZdQCyFOQ)l(}gft0UZG`Sh2`x-w`5vC2UD}lZs*5 zG76$akzn}Xi))L3oGJ75#pcN=cX3!=57$Ha=hQ2^lwdyU#a}4JJOz6ddR%zae%#4& za)bFj)z=YQela(F#Y|Q#dp}PJghITwXouVaMq$BM?K%cXn9^Y@g43$=O)F&ZlOUom zJiad#dea;-eywBA@e&D6Pdso1?2^(pXiN91?jvcaUyYoKUmvl5G9e$W!okWe*@a<^ z8cQQ6cNSf+UPDx%?_G4aIiybZHHagF{;IcD(dPO!#=u zWfqLcPc^+7Uu#l(Bpxft{*4lv#*u7X9AOzDO z1D9?^jIo}?%iz(_dwLa{ex#T}76ZfN_Z-hwpus9y+4xaUu9cX}&P{XrZVWE{1^0yw zO;YhLEW!pJcbCt3L8~a7>jsaN{V3>tz6_7`&pi%GxZ=V3?3K^U+*ryLSb)8^IblJ0 zSRLNDvIxt)S}g30?s_3NX>F?NKIGrG_zB9@Z>uSW3k2es_H2kU;Rnn%j5qP)!XHKE zPB2mHP~tLCg4K_vH$xv`HbRsJwbZMUV(t=ez;Ec(vyHH)FbfLg`c61I$W_uBB>i^r z&{_P;369-&>23R%qNIULe=1~T$(DA`ev*EWZ6j(B$(te}x1WvmIll21zvygkS%vwG zzkR6Z#RKA2!z!C%M!O>!=Gr0(J0FP=-MN=5t-Ir)of50y10W}j`GtRCsXBakrKtG& zazmITDJMA0C51&BnLY)SY9r)NVTMs);1<=oosS9g31l{4ztjD3#+2H7u_|66b|_*O z;Qk6nalpqdHOjx|K&vUS_6ITgGll;TdaN*ta=M_YtyC)I9Tmr~VaPrH2qb6sd~=AcIxV+%z{E&0@y=DPArw zdV7z(G1hBx7hd{>(cr43^WF%4Y@PXZ?wPpj{OQ#tvc$pABJbvPGvdR`cAtHn)cSEV zrpu}1tJwQ3y!mSmH*uz*x0o|CS<^w%&KJzsj~DU0cLQUxk5B!hWE>aBkjJle8z~;s z-!A=($+}Jq_BTK5^B!`R>!MulZN)F=iXXeUd0w5lUsE5VP*H*oCy(;?S$p*TVvTxwAeWFB$jHyb0593)$zqalVlDX=GcCN1gU0 zlgU)I$LcXZ8Oyc2TZYTPu@-;7<4YYB-``Qa;IDcvydIA$%kHhJKV^m*-zxcvU4viy&Kr5GVM{IT>WRywKQ9;>SEiQD*NqplK-KK4YR`p0@JW)n_{TU3bt0 zim%;(m1=#v2}zTps=?fU5w^(*y)xT%1vtQH&}50ZF!9YxW=&7*W($2kgKyz1mUgfs zfV<*XVVIFnohW=|j+@Kfo!#liQR^x>2yQdrG;2o8WZR+XzU_nG=Ed2rK?ntA;K5B{ z>M8+*A4!Jm^Bg}aW?R?6;@QG@uQ8&oJ{hFixcfEnJ4QH?A4>P=q29oDGW;L;= z9-a0;g%c`C+Ai!UmK$NC*4#;Jp<1=TioL=t^YM)<<%u#hnnfSS`nq63QKGO1L8RzX z@MFDqs1z ztYmxDl@LU)5acvHk)~Z`RW7=aJ_nGD!mOSYD>5Odjn@TK#LY{jf?+piB5AM-CAoT_ z?S-*q7}wyLJzK>N%eMPuFgN)Q_otKP;aqy=D5f!7<=n(lNkYRXVpkB{TAYLYg{|(jtRqYmg$xH zjmq?B(RE4 zQx^~Pt}gxC2~l=K$$-sYy_r$CO(d=+b3H1MB*y_5g6WLaWTXn+TKQ|hNY^>Mp6k*$ zwkovomhu776vQATqT4blf~g;TY(MWCrf^^yfWJvSAB$p5l;jm@o#=!lqw+Lqfq>X= z$6~kxfm7`3q4zUEB;u4qa#BdJxO!;xGm)wwuisj{0y2x{R(IGMrsIzDY9LW>m!Y`= z04sx3IjnYvL<4JqxQ8f7qYd0s2Ig%`ytYPEMKI)s(LD}D@EY>x`VFtqvnADNBdeao zC96X+MxnwKmjpg{U&gP3HE}1=s!lv&D{6(g_lzyF3A`7Jn*&d_kL<;dAFx!UZ>hB8 z5A*%LsAn;VLp>3${0>M?PSQ)9s3}|h2e?TG4_F{}{Cs>#3Q*t$(CUc}M)I}8cPF6% z=+h(Kh^8)}gj(0}#e7O^FQ6`~fd1#8#!}LMuo3A0bN`o}PYsm!Y}sdOz$+Tegc=qT z8x`PH$7lvnhJp{kHWb22l;@7B7|4yL4UOOVM0MP_>P%S1Lnid)+k9{+3D+JFa#Pyf zhVc#&df87APl4W9X)F3pGS>@etfl=_E5tBcVoOfrD4hmVeTY-cj((pkn%n@EgN{0f zwb_^Rk0I#iZuHK!l*lN`ceJn(sI{$Fq6nN& zE<-=0_2WN}m+*ivmIOxB@#~Q-cZ>l136w{#TIJe478`KE7@=a{>SzPHsKLzYAyBQO zAtuuF$-JSDy_S@6GW0MOE~R)b;+0f%_NMrW(+V#c_d&U8Z9+ec4=HmOHw?gdjF(Lu zzra83M_BoO-1b3;9`%&DHfuUY)6YDV21P$C!Rc?mv&{lx#f8oc6?0?x zK08{WP65?#>(vPfA-c=MCY|%*1_<3D4NX zeVTi-JGl2uP_2@0F{G({pxQOXt_d{g_CV6b?jNpfUG9;8yle-^4KHRvZs-_2siata zt+d_T@U$&t*xaD22(fH(W1r$Mo?3dc%Tncm=C6{V9y{v&VT#^1L04vDrLM9qBoZ4@ z6DBN#m57hX7$C(=#$Y5$bJmwA$T8jKD8+6A!-IJwA{WOfs%s}yxUw^?MRZjF$n_KN z6`_bGXcmE#5e4Ym)aQJ)xg3Pg0@k`iGuHe?f(5LtuzSq=nS^5z>vqU0EuZ&75V%Z{ zYyhRLN^)$c6Ds{f7*FBpE;n5iglx5PkHfWrj3`x^j^t z7ntuV`g!9Xg#^3!x)l*}IW=(Tz3>Y5l4uGaB&lz{GDjm2D5S$CExLT`I1#n^lBH7Y zDgpMag@`iETKAI=p<5E#LTkwzVR@=yY|uBVI1HG|8h+d;G-qfuj}-ZR6fN>EfCCW z9~wRQoAPEa#aO?3h?x{YvV*d+NtPkf&4V0k4|L=uj!U{L+oLa(z#&iuhJr3-PjO3R z5s?=nn_5^*^Rawr>>Nr@K(jwkB#JK-=+HqwfdO<+P5byeim)wvqGlP-P|~Nse8=XF zz`?RYB|D6SwS}C+YQv+;}k6$-%D(@+t14BL@vM z2q%q?f6D-A5s$_WY3{^G0F131bbh|g!}#BKw=HQ7mx;Dzg4Z*bTLQSfo{ed{4}NZW zfrRm^Ca$rlE{Ue~uYv>R9{3smwATcdM_6+yWIO z*ZRH~uXE@#p$XTbCt5j7j2=86e{9>HIB6xDzV+vAo&B?KUiMP|ttOElepnl%|DPqL b{|{}U^kRn2wo}j7|0ATu<;8xA7zX}7|B6mN literal 0 HcmV?d00001 diff --git a/store-reactjs-chat/manifest.json b/store-reactjs-chat/manifest.json new file mode 100644 index 0000000..080d6c7 --- /dev/null +++ b/store-reactjs-chat/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/store-reactjs-chat/robots.txt b/store-reactjs-chat/robots.txt new file mode 100644 index 0000000..e9e57dc --- /dev/null +++ b/store-reactjs-chat/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/store-reactjs-chat/static/css/main.e6c13ad2.css b/store-reactjs-chat/static/css/main.e6c13ad2.css new file mode 100644 index 0000000..50410fa --- /dev/null +++ b/store-reactjs-chat/static/css/main.e6c13ad2.css @@ -0,0 +1,2 @@ +body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;margin:0}code{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace} +/*# sourceMappingURL=main.e6c13ad2.css.map*/ \ No newline at end of file diff --git a/store-reactjs-chat/static/css/main.e6c13ad2.css.map b/store-reactjs-chat/static/css/main.e6c13ad2.css.map new file mode 100644 index 0000000..5c4dfb9 --- /dev/null +++ b/store-reactjs-chat/static/css/main.e6c13ad2.css.map @@ -0,0 +1 @@ +{"version":3,"file":"static/css/main.e6c13ad2.css","mappings":"AAAA,KAKE,kCAAmC,CACnC,iCAAkC,CAJlC,mIAEY,CAHZ,QAMF,CAEA,KACE,uEAEF","sources":["index.css"],"sourcesContent":["body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n monospace;\n}\n"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/store-reactjs-chat/static/js/main.dce8435a.js b/store-reactjs-chat/static/js/main.dce8435a.js new file mode 100644 index 0000000..bf872d0 --- /dev/null +++ b/store-reactjs-chat/static/js/main.dce8435a.js @@ -0,0 +1,3 @@ +/*! For license information please see main.dce8435a.js.LICENSE.txt */ +(()=>{var __webpack_modules__={7206:e=>{"use strict";e.exports=function(e,t){var r=new Array(arguments.length-1),n=0,i=2,s=!0;for(;i{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),i=new Array(123),s=0;s<64;)i[n[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;r.encode=function(e,t,r){for(var i,s=null,o=[],a=0,c=0;t>2],i=(3&l)<<4,c=1;break;case 1:o[a++]=n[i|l>>4],i=(15&l)<<2,c=2;break;case 2:o[a++]=n[i|l>>6],o[a++]=n[63&l],c=0}a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=n[i],o[a++]=61,1===c&&(o[a++]=61)),s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var o="invalid encoding";r.decode=function(e,t,r){for(var n,s=r,a=0,c=0;c1)break;if(void 0===(l=i[l]))throw Error(o);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(o);return r-s},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},3297:e=>{"use strict";function t(e,r){"string"===typeof e&&(r=e,e=void 0);var n=[];function i(e){if("string"!==typeof e){var r=s();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var o=Object.keys(e),a=new Array(o.length+1),c=new Array(o.length),l=0;l{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n{"use strict";e.exports=s;var n=r(7206),i=r(7172)("fs");function s(e,t,r){return"function"===typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&i&&i.readFile?i.readFile(e,(function(n,i){return n&&"undefined"!==typeof XMLHttpRequest?s.xhr(e,t,r):n?r(n):r(null,t.binary?i:i.toString("utf8"))})):s.xhr(e,t,r):n(s,this,e,t)}s.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var i=0;i{"use strict";function t(e){return"undefined"!==typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3]}function s(e,n,i){t[0]=e,n[i]=r[3],n[i+1]=r[2],n[i+2]=r[1],n[i+3]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?i:s,e.writeFloatBE=n?s:i,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():function(){function t(e,t,r,n){var i=t<0?1:0;if(i&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((i<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((i<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var s=Math.floor(Math.log(t)/Math.LN2);e((i<<31|s+127<<23|8388607&Math.round(t*Math.pow(2,-s)*8388608))>>>0,r,n)}}function o(e,t,r){var n=e(t,r),i=2*(n>>31)+1,s=n>>>23&255,o=8388607&n;return 255===s?o?NaN:i*(1/0):0===s?1401298464324817e-60*i*o:i*Math.pow(2,s-150)*(o+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=o.bind(null,i),e.readFloatBE=o.bind(null,s)}(),"undefined"!==typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3],n[i+4]=r[4],n[i+5]=r[5],n[i+6]=r[6],n[i+7]=r[7]}function s(e,n,i){t[0]=e,n[i]=r[7],n[i+1]=r[6],n[i+2]=r[5],n[i+3]=r[4],n[i+4]=r[3],n[i+5]=r[2],n[i+6]=r[1],n[i+7]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?i:s,e.writeDoubleBE=n?s:i,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function t(e,t,r,n,i,s){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,i,s+t),e(1/n>0?0:2147483648,i,s+r);else if(isNaN(n))e(0,i,s+t),e(2146959360,i,s+r);else if(n>17976931348623157e292)e(0,i,s+t),e((o<<31|2146435072)>>>0,i,s+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,i,s+t),e((o<<31|a/4294967296)>>>0,i,s+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,i,s+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,i,s+r)}}}function o(e,t,r,n,i){var s=e(n,i+t),o=e(n,i+r),a=2*(o>>31)+1,c=o>>>20&2047,l=4294967296*(1048575&o)+s;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=o.bind(null,i,0,4),e.readDoubleBE=o.bind(null,s,4,0)}(),e}function r(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},7172:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},7468:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},i=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),i="";r&&(i=t.shift()+"/");for(var s=0;s0&&".."!==t[s-1]?t.splice(--s,2):r?t.splice(s,1):++s:"."===t[s]?t.splice(s,1):++s;return i+t.join("/")};r.resolve=function(e,t,r){return r||(t=i(t)),n(t)?t:(r||(e=i(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?i(e+"/"+t):t)}},8236:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(r){if(r<1||r>i)return e(r);o+r>n&&(s=e(n),o=0);var a=t.call(s,o,o+=r);return 7&o&&(o=1+(7|o)),a}}},3861:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?s[o++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(n>>10),s[o++]=56320+(1023&n)):s[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0);return i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))},r.write=function(e,t,r){for(var n,i,s=r,o=0;o>6|192,t[r++]=63&n|128):55296===(64512&n)&&56320===(64512&(i=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&i),++o,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-s}},6232:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(5073);function i(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>8,t[r+1]=e>>>0,t}function s(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t}function o(e,t){return void 0===t&&(t=0),e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function a(e,t){return void 0===t&&(t=0),(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function c(e,t){return void 0===t&&(t=0),e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function l(e,t){return void 0===t&&(t=0),(e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t])>>>0}function u(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>24,t[r+1]=e>>>16,t[r+2]=e>>>8,t[r+3]=e>>>0,t}function h(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24,t}function d(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),u(e/4294967296>>>0,t,r),u(e>>>0,t,r+4),t}function f(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),h(e>>>0,t,r),h(e/4294967296>>>0,t,r+4),t}t.readInt16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])<<16>>16},t.readUint16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])>>>0},t.readInt16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])<<16>>16},t.readUint16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])>>>0},t.writeUint16BE=i,t.writeInt16BE=i,t.writeUint16LE=s,t.writeInt16LE=s,t.readInt32BE=o,t.readUint32BE=a,t.readInt32LE=c,t.readUint32LE=l,t.writeUint32BE=u,t.writeInt32BE=u,t.writeUint32LE=h,t.writeInt32LE=h,t.readInt64BE=function(e,t){void 0===t&&(t=0);var r=o(e,t),n=o(e,t+4);return 4294967296*r+n-4294967296*(n>>31)},t.readUint64BE=function(e,t){return void 0===t&&(t=0),4294967296*a(e,t)+a(e,t+4)},t.readInt64LE=function(e,t){void 0===t&&(t=0);var r=c(e,t);return 4294967296*c(e,t+4)+r-4294967296*(r>>31)},t.readUint64LE=function(e,t){void 0===t&&(t=0);var r=l(e,t);return 4294967296*l(e,t+4)+r},t.writeUint64BE=d,t.writeInt64BE=d,t.writeUint64LE=f,t.writeInt64LE=f,t.readUintBE=function(e,t,r){if(void 0===r&&(r=0),e%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=e/8+r-1;s>=r;s--)n+=t[s]*i,i*=256;return n},t.readUintLE=function(e,t,r){if(void 0===r&&(r=0),e%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=i;o--)r[o]=t/s&255,s*=256;return r},t.writeUintLE=function(e,t,r,i){if(void 0===r&&(r=new Uint8Array(e/8)),void 0===i&&(i=0),e%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!n.isSafeInteger(t))throw new Error("writeUintLE value must be an integer");for(var s=1,o=i;o{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(6232),i=r(9116);function s(e,t,r){for(var i=1634760805,s=857760878,o=2036477234,a=1797285236,c=r[3]<<24|r[2]<<16|r[1]<<8|r[0],l=r[7]<<24|r[6]<<16|r[5]<<8|r[4],u=r[11]<<24|r[10]<<16|r[9]<<8|r[8],h=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],f=r[23]<<24|r[22]<<16|r[21]<<8|r[20],p=r[27]<<24|r[26]<<16|r[25]<<8|r[24],g=r[31]<<24|r[30]<<16|r[29]<<8|r[28],y=t[3]<<24|t[2]<<16|t[1]<<8|t[0],m=t[7]<<24|t[6]<<16|t[5]<<8|t[4],v=t[11]<<24|t[10]<<16|t[9]<<8|t[8],w=t[15]<<24|t[14]<<16|t[13]<<8|t[12],b=i,E=s,S=o,_=a,I=c,A=l,C=u,T=h,R=d,k=f,P=p,N=g,D=y,L=m,O=v,B=w,x=0;x<20;x+=2)I=(I^=R=R+(D=(D^=b=b+I|0)>>>16|D<<16)|0)>>>20|I<<12,A=(A^=k=k+(L=(L^=E=E+A|0)>>>16|L<<16)|0)>>>20|A<<12,C=(C^=P=P+(O=(O^=S=S+C|0)>>>16|O<<16)|0)>>>20|C<<12,T=(T^=N=N+(B=(B^=_=_+T|0)>>>16|B<<16)|0)>>>20|T<<12,C=(C^=P=P+(O=(O^=S=S+C|0)>>>24|O<<8)|0)>>>25|C<<7,T=(T^=N=N+(B=(B^=_=_+T|0)>>>24|B<<8)|0)>>>25|T<<7,A=(A^=k=k+(L=(L^=E=E+A|0)>>>24|L<<8)|0)>>>25|A<<7,I=(I^=R=R+(D=(D^=b=b+I|0)>>>24|D<<8)|0)>>>25|I<<7,A=(A^=P=P+(B=(B^=b=b+A|0)>>>16|B<<16)|0)>>>20|A<<12,C=(C^=N=N+(D=(D^=E=E+C|0)>>>16|D<<16)|0)>>>20|C<<12,T=(T^=R=R+(L=(L^=S=S+T|0)>>>16|L<<16)|0)>>>20|T<<12,I=(I^=k=k+(O=(O^=_=_+I|0)>>>16|O<<16)|0)>>>20|I<<12,T=(T^=R=R+(L=(L^=S=S+T|0)>>>24|L<<8)|0)>>>25|T<<7,I=(I^=k=k+(O=(O^=_=_+I|0)>>>24|O<<8)|0)>>>25|I<<7,C=(C^=N=N+(D=(D^=E=E+C|0)>>>24|D<<8)|0)>>>25|C<<7,A=(A^=P=P+(B=(B^=b=b+A|0)>>>24|B<<8)|0)>>>25|A<<7;n.writeUint32LE(b+i|0,e,0),n.writeUint32LE(E+s|0,e,4),n.writeUint32LE(S+o|0,e,8),n.writeUint32LE(_+a|0,e,12),n.writeUint32LE(I+c|0,e,16),n.writeUint32LE(A+l|0,e,20),n.writeUint32LE(C+u|0,e,24),n.writeUint32LE(T+h|0,e,28),n.writeUint32LE(R+d|0,e,32),n.writeUint32LE(k+f|0,e,36),n.writeUint32LE(P+p|0,e,40),n.writeUint32LE(N+g|0,e,44),n.writeUint32LE(D+y|0,e,48),n.writeUint32LE(L+m|0,e,52),n.writeUint32LE(O+v|0,e,56),n.writeUint32LE(B+w|0,e,60)}function o(e,t,r,n,o){if(void 0===o&&(o=0),32!==e.length)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,t++;if(n>0)throw new Error("ChaCha: counter overflow")}t.streamXOR=o,t.stream=function(e,t,r,n){return void 0===n&&(n=0),i.wipe(r),o(e,t,r,r,n)}},3642:(e,t,r)=>{"use strict";var n=r(8284),i=r(5629),s=r(9116),o=r(6232),a=r(8770);t.Cv=32,t.WH=12,t.pg=16;var c=new Uint8Array(16),l=function(){function e(e){if(this.nonceLength=t.WH,this.tagLength=t.pg,e.length!==t.Cv)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return e.prototype.seal=function(e,t,r,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var o=new Uint8Array(16);o.set(e,o.length-e.length);var a=new Uint8Array(32);n.stream(this._key,o,a,4);var c,l=t.length+this.tagLength;if(i){if(i.length!==l)throw new Error("ChaCha20Poly1305: incorrect destination length");c=i}else c=new Uint8Array(l);return n.streamXOR(this._key,o,t,c,4),this._authenticate(c.subarray(c.length-this.tagLength,c.length),a,c.subarray(0,c.length-this.tagLength),r),s.wipe(o),c},e.prototype.open=function(e,t,r,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(t.length0&&a.update(c.subarray(n.length%16))),a.update(r),r.length%16>0&&a.update(c.subarray(r.length%16));var l=new Uint8Array(8);n&&o.writeUint64LE(n.length,l),a.update(l),o.writeUint64LE(r.length,l),a.update(l);for(var u=a.digest(),h=0;h{"use strict";function r(e,t){if(e.length!==t.length)return 0;for(var r=0,n=0;n>>8}Object.defineProperty(t,"__esModule",{value:!0}),t.select=function(e,t,r){return~(e-1)&t|e-1&r},t.lessOrEqual=function(e,t){return(0|e)-(0|t)-1>>>31&1},t.compare=r,t.equal=function(e,t){return 0!==e.length&&0!==t.length&&0!==r(e,t)}},1412:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSerializableHash=function(e){return"undefined"!==typeof e.saveState&&"undefined"!==typeof e.restoreState&&"undefined"!==typeof e.cleanSavedState}},2497:(e,t,r)=>{"use strict";var n=r(5499),i=r(9116),s=function(){function e(e,t,r,i){void 0===r&&(r=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=n.hmac(this._hash,r,t);this._hmac=new n.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return e.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(0===e)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},e.prototype.expand=function(e){for(var t=new Uint8Array(e),r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(1412),i=r(8770),s=r(9116),o=function(){function e(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var r=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(r).clean():r.set(t);for(var i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mul=Math.imul||function(e,t){var r=65535&e,n=65535&t;return r*n+((e>>>16&65535)*n+r*(t>>>16&65535)<<16>>>0)|0},t.add=function(e,t){return e+t|0},t.sub=function(e,t){return e-t|0},t.rotl=function(e,t){return e<>>32-t},t.rotr=function(e,t){return e<<32-t|e>>>t},t.isInteger=Number.isInteger||function(e){return"number"===typeof e&&isFinite(e)&&Math.floor(e)===e},t.MAX_SAFE_INTEGER=9007199254740991,t.isSafeInteger=function(e){return t.isInteger(e)&&e>=-t.MAX_SAFE_INTEGER&&e<=t.MAX_SAFE_INTEGER}},5629:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8770),i=r(9116);t.DIGEST_LENGTH=16;var s=function(){function e(e){this.digestLength=t.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=8191&r;var n=e[2]|e[3]<<8;this._r[1]=8191&(r>>>13|n<<3);var i=e[4]|e[5]<<8;this._r[2]=7939&(n>>>10|i<<6);var s=e[6]|e[7]<<8;this._r[3]=8191&(i>>>7|s<<9);var o=e[8]|e[9]<<8;this._r[4]=255&(s>>>4|o<<12),this._r[5]=o>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=8191&(o>>>14|a<<2);var c=e[12]|e[13]<<8;this._r[7]=8065&(a>>>11|c<<5);var l=e[14]|e[15]<<8;this._r[8]=8191&(c>>>8|l<<8),this._r[9]=l>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return e.prototype._blocks=function(e,t,r){for(var n=this._fin?0:2048,i=this._h[0],s=this._h[1],o=this._h[2],a=this._h[3],c=this._h[4],l=this._h[5],u=this._h[6],h=this._h[7],d=this._h[8],f=this._h[9],p=this._r[0],g=this._r[1],y=this._r[2],m=this._r[3],v=this._r[4],w=this._r[5],b=this._r[6],E=this._r[7],S=this._r[8],_=this._r[9];r>=16;){var I=e[t+0]|e[t+1]<<8;i+=8191&I;var A=e[t+2]|e[t+3]<<8;s+=8191&(I>>>13|A<<3);var C=e[t+4]|e[t+5]<<8;o+=8191&(A>>>10|C<<6);var T=e[t+6]|e[t+7]<<8;a+=8191&(C>>>7|T<<9);var R=e[t+8]|e[t+9]<<8;c+=8191&(T>>>4|R<<12),l+=R>>>1&8191;var k=e[t+10]|e[t+11]<<8;u+=8191&(R>>>14|k<<2);var P=e[t+12]|e[t+13]<<8;h+=8191&(k>>>11|P<<5);var N=e[t+14]|e[t+15]<<8,D=0,L=D;L+=i*p,L+=s*(5*_),L+=o*(5*S),L+=a*(5*E),D=(L+=c*(5*b))>>>13,L&=8191,L+=l*(5*w),L+=u*(5*v),L+=h*(5*m),L+=(d+=8191&(P>>>8|N<<8))*(5*y);var O=D+=(L+=(f+=N>>>5|n)*(5*g))>>>13;O+=i*g,O+=s*p,O+=o*(5*_),O+=a*(5*S),D=(O+=c*(5*E))>>>13,O&=8191,O+=l*(5*b),O+=u*(5*w),O+=h*(5*v),O+=d*(5*m),D+=(O+=f*(5*y))>>>13,O&=8191;var B=D;B+=i*y,B+=s*g,B+=o*p,B+=a*(5*_),D=(B+=c*(5*S))>>>13,B&=8191,B+=l*(5*E),B+=u*(5*b),B+=h*(5*w),B+=d*(5*v);var x=D+=(B+=f*(5*m))>>>13;x+=i*m,x+=s*y,x+=o*g,x+=a*p,D=(x+=c*(5*_))>>>13,x&=8191,x+=l*(5*S),x+=u*(5*E),x+=h*(5*b),x+=d*(5*w);var M=D+=(x+=f*(5*v))>>>13;M+=i*v,M+=s*m,M+=o*y,M+=a*g,D=(M+=c*p)>>>13,M&=8191,M+=l*(5*_),M+=u*(5*S),M+=h*(5*E),M+=d*(5*b);var U=D+=(M+=f*(5*w))>>>13;U+=i*w,U+=s*v,U+=o*m,U+=a*y,D=(U+=c*g)>>>13,U&=8191,U+=l*p,U+=u*(5*_),U+=h*(5*S),U+=d*(5*E);var F=D+=(U+=f*(5*b))>>>13;F+=i*b,F+=s*w,F+=o*v,F+=a*m,D=(F+=c*y)>>>13,F&=8191,F+=l*g,F+=u*p,F+=h*(5*_),F+=d*(5*S);var V=D+=(F+=f*(5*E))>>>13;V+=i*E,V+=s*b,V+=o*w,V+=a*v,D=(V+=c*m)>>>13,V&=8191,V+=l*y,V+=u*g,V+=h*p,V+=d*(5*_);var K=D+=(V+=f*(5*S))>>>13;K+=i*S,K+=s*E,K+=o*b,K+=a*w,D=(K+=c*v)>>>13,K&=8191,K+=l*m,K+=u*y,K+=h*g,K+=d*p;var j=D+=(K+=f*(5*_))>>>13;j+=i*_,j+=s*S,j+=o*E,j+=a*b,D=(j+=c*w)>>>13,j&=8191,j+=l*v,j+=u*m,j+=h*y,j+=d*g,i=L=8191&(D=(D=((D+=(j+=f*p)>>>13)<<2)+D|0)+(L&=8191)|0),s=O+=D>>>=13,o=B&=8191,a=x&=8191,c=M&=8191,l=U&=8191,u=F&=8191,h=V&=8191,d=K&=8191,f=j&=8191,t+=16,r-=16}this._h[0]=i,this._h[1]=s,this._h[2]=o,this._h[3]=a,this._h[4]=c,this._h[5]=l,this._h[6]=u,this._h[7]=h,this._h[8]=d,this._h[9]=f},e.prototype.finish=function(e,t){void 0===t&&(t=0);var r,n,i,s,o=new Uint16Array(10);if(this._leftover){for(s=this._leftover,this._buffer[s++]=1;s<16;s++)this._buffer[s]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(r=this._h[1]>>>13,this._h[1]&=8191,s=2;s<10;s++)this._h[s]+=r,r=this._h[s]>>>13,this._h[s]&=8191;for(this._h[0]+=5*r,r=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=r,r=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=r,o[0]=this._h[0]+5,r=o[0]>>>13,o[0]&=8191,s=1;s<10;s++)o[s]=this._h[s]+r,r=o[s]>>>13,o[s]&=8191;for(o[9]-=8192,n=(1^r)-1,s=0;s<10;s++)o[s]&=n;for(n=~n,s=0;s<10;s++)this._h[s]=this._h[s]&n|o[s];for(this._h[0]=65535&(this._h[0]|this._h[1]<<13),this._h[1]=65535&(this._h[1]>>>3|this._h[2]<<10),this._h[2]=65535&(this._h[2]>>>6|this._h[3]<<7),this._h[3]=65535&(this._h[3]>>>9|this._h[4]<<4),this._h[4]=65535&(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14),this._h[5]=65535&(this._h[6]>>>2|this._h[7]<<11),this._h[6]=65535&(this._h[7]>>>5|this._h[8]<<8),this._h[7]=65535&(this._h[8]>>>8|this._h[9]<<5),i=this._h[0]+this._pad[0],this._h[0]=65535&i,s=1;s<8;s++)i=(this._h[s]+this._pad[s]|0)+(i>>>16)|0,this._h[s]=65535&i;return e[t+0]=this._h[0]>>>0,e[t+1]=this._h[0]>>>8,e[t+2]=this._h[1]>>>0,e[t+3]=this._h[1]>>>8,e[t+4]=this._h[2]>>>0,e[t+5]=this._h[2]>>>8,e[t+6]=this._h[3]>>>0,e[t+7]=this._h[3]>>>8,e[t+8]=this._h[4]>>>0,e[t+9]=this._h[4]>>>8,e[t+10]=this._h[5]>>>0,e[t+11]=this._h[5]>>>8,e[t+12]=this._h[6]>>>0,e[t+13]=this._h[6]>>>8,e[t+14]=this._h[7]>>>0,e[t+15]=this._h[7]>>>8,this._finished=!0,this},e.prototype.update=function(e){var t,r=0,n=e.length;if(this._leftover){(t=16-this._leftover)>n&&(t=n);for(var i=0;i=16&&(t=n-n%16,this._blocks(e,r,t),r+=t,n-=t),n){for(i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.randomStringForEntropy=t.randomString=t.randomUint32=t.randomBytes=t.defaultRandomSource=void 0;const n=r(933),i=r(6232),s=r(9116);function o(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.defaultRandomSource;return r.randomBytes(e)}t.defaultRandomSource=new n.SystemRandomSource,t.randomBytes=o,t.randomUint32=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t.defaultRandomSource;const r=o(4,e),n=(0,i.readUint32LE)(r);return(0,s.wipe)(r),n};const a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function c(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.defaultRandomSource;if(r.length<2)throw new Error("randomString charset is too short");if(r.length>256)throw new Error("randomString charset is too long");let i="";const c=r.length,l=256-256%c;for(;e>0;){const t=o(Math.ceil(256*e/l),n);for(let n=0;n0;n++){const s=t[n];s1&&void 0!==arguments[1]?arguments[1]:a,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.defaultRandomSource;const i=Math.ceil(e/(Math.log(r.length)/Math.LN2));return c(i,r,n)}},8136:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserRandomSource=void 0;t.BrowserRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;const e="undefined"!==typeof self?self.crypto||self.msCrypto:null;e&&void 0!==e.getRandomValues&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");const t=new Uint8Array(e);for(let r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NodeRandomSource=void 0;const n=r(9116);t.NodeRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;{const e=r(5883);e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");const r=new Uint8Array(e);for(let n=0;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemRandomSource=void 0;const n=r(8136),i=r(8188);t.SystemRandomSource=class{constructor(){return this.isAvailable=!1,this.name="",this._source=new n.BrowserRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Browser")):(this._source=new i.NodeRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Node")):void 0)}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}}},4888:(e,t,r)=>{"use strict";var n=r(6232),i=r(9116);t.k=32,t.cn=64;var s=function(){function e(){this.digestLength=t.k,this.blockSize=t.cn,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return e.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},e.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},e.prototype.clean=function(){i.wipe(this._buffer),i.wipe(this._temp),this.reset()},e.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var r=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[r++],t--;this._bufferLength===this.blockSize&&(a(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(r=a(this._temp,this._state,e,r,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[r++],t--;return this},e.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,r=this._bufferLength,i=t/536870912|0,s=t<<3,o=t%64<56?64:128;this._buffer[r]=128;for(var c=r+1;c0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},e.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},e.prototype.cleanSavedState=function(e){i.wipe(e.state),e.buffer&&i.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},e}();t.mE=s;var o=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function a(e,t,r,i,s){for(;s>=64;){for(var a=t[0],c=t[1],l=t[2],u=t[3],h=t[4],d=t[5],f=t[6],p=t[7],g=0;g<16;g++){var y=i+4*g;e[g]=n.readUint32BE(r,y)}for(g=16;g<64;g++){var m=e[g-2],v=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,w=((m=e[g-15])>>>7|m<<25)^(m>>>18|m<<14)^m>>>3;e[g]=(v+e[g-7]|0)+(w+e[g-16]|0)}for(g=0;g<64;g++){v=(((h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(h&d^~h&f)|0)+(p+(o[g]+e[g]|0)|0)|0,w=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&c^a&l^c&l)|0;p=f,f=d,d=h,h=u+v|0,u=l,l=c,c=a,a=v+w|0}t[0]+=a,t[1]+=c,t[2]+=l,t[3]+=u,t[4]+=h,t[5]+=d,t[6]+=f,t[7]+=p,i+=64,s-=64}return i}t.vp=function(e){var t=new s;t.update(e);var r=t.digest();return t.clean(),r}},9116:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wipe=function(e){for(var t=0;t{"use strict";t.gi=t.Au=t._w=t.KS=t.kz=void 0;const n=r(6271),i=r(9116);function s(e){const t=new Float64Array(16);if(e)for(let r=0;r=0;--s){const e=r[s>>>3]>>>(7&s)&1;l(i,o,e),l(p,g,e),u(y,i,p),h(i,i,p),u(p,o,g),h(o,o,g),f(g,y),f(m,i),d(i,p,i),d(p,o,y),u(y,i,p),h(i,i,p),f(o,i),h(p,g,m),d(i,p,a),u(i,i,g),d(p,p,i),d(i,g,m),d(g,o,n),f(o,y),l(i,o,e),l(p,g,e)}for(let s=0;s<16;s++)n[s+16]=i[s],n[s+32]=p[s],n[s+48]=o[s],n[s+64]=g[s];const v=n.subarray(32),w=n.subarray(16);!function(e,t){const r=s();for(let n=0;n<16;n++)r[n]=t[n];for(let n=253;n>=0;n--)f(r,r),2!==n&&4!==n&&d(r,r,t);for(let n=0;n<16;n++)e[n]=r[n]}(v,v),d(w,w,v);const b=new Uint8Array(32);return function(e,t){const r=s(),n=s();for(let i=0;i<16;i++)n[i]=t[i];c(n),c(n),c(n);for(let i=0;i<2;i++){r[0]=n[0]-65517;for(let t=1;t<15;t++)r[t]=n[t]-65535-(r[t-1]>>16&1),r[t-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);const e=r[15]>>16&1;r[14]&=65535,l(n,r,1-e)}for(let i=0;i<16;i++)e[2*i]=255&n[i],e[2*i+1]=n[i]>>8}(b,w),b}function g(e){return p(e,o)}function y(e){if(e.length!==t.KS)throw new Error("x25519: seed must be ".concat(t.KS," bytes"));const r=new Uint8Array(e);return{publicKey:g(r),secretKey:r}}t._w=y,t.Au=function(e){const t=(0,n.randomBytes)(32,e),r=y(t);return(0,i.wipe)(t),r},t.gi=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(e.length!==t.kz)throw new Error("X25519: incorrect secret key length");if(r.length!==t.kz)throw new Error("X25519: incorrect public key length");const i=p(e,r);if(n){let e=0;for(let t=0;t{function t(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)t&&t.removeEventListener&&t.removeEventListener("abort",r)}for(const n of e)if(n&&n.addEventListener){if(n.aborted){r();break}n.addEventListener("abort",r)}return t.signal}e.exports=t,e.exports.anySignal=t},312:e=>{var t=1e3,r=60*t,n=60*r,i=24*n,s=7*i,o=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var s=Math.abs(e);if(s>=i)return a(e,s,i,"day");if(s>=n)return a(e,s,n,"hour");if(s>=r)return a(e,s,r,"minute");if(s>=t)return a(e,s,t,"second");return e+" ms"}(e):function(e){var s=Math.abs(e);if(s>=i)return Math.round(e/i)+"d";if(s>=n)return Math.round(e/n)+"h";if(s>=r)return Math.round(e/r)+"m";if(s>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},8392:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(r){}!e&&"undefined"!==typeof process&&"env"in process&&(e={NODE_ENV:"production",PUBLIC_URL:"/store-reactjs-chat",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.DEBUG);return e},t.useColors=function(){if("undefined"!==typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!==typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!==typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(8472)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}},8472:(e,t,r)=>{e.exports=function(e){function t(e){let r,i,s,o=null;function a(){for(var e=arguments.length,n=new Array(e),i=0;i{if("%%"===e)return"%";l++;const i=t.formatters[r];if("function"===typeof i){const t=n[l];e=i.call(s,t),n.splice(l,1),l--}return e})),t.formatArgs.call(s,n);const u=s.log||t.log;u.apply(s,n)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"===typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+("undefined"===typeof r?":":r)+e);return n.log=this.log,n}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"===typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";function t(e,t){t=t||{};this._head=0,this._tail=0,this._capacity=t.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}t.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}},t.prototype.get=function(e){return this.peekAt(e)},t.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},t.prototype.peekFront=function(){return this.peek()},t.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(t.prototype,"length",{get:function(){return this.size()}}),t.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},t.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var i,s=this._list[t];if(e0;i--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(i=r-1-e;i>0;i--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return s}}},t.prototype.remove=function(e,t){var r,n=e,i=t;if(n===(0|n)&&this._head!==this._tail){var s=this.size(),o=this._list.length;if(!(n>=s||n<-s||t<1)){if(n<0&&(n+=s),1===t||!t)return(r=new Array(1))[0]=this.removeOne(n),r;if(0===n&&n+t>=s)return r=this.toArray(),this.clear(),r;var a;for(n+t>s&&(t=s-n),r=new Array(t),a=0;a0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+o&this._capacityMask,a=t-1;a>0;a--)this._list[n=n+1+o&this._capacityMask]=void 0;return r}if(n0;a--)this.unshift(this._list[n=n-1+o&this._capacityMask]);for(n=this._head-1+o&this._capacityMask;i>0;)this._list[n=n-1+o&this._capacityMask]=void 0,i--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+o&this._capacityMask,a=s-(t+e);a>0;a--)this.push(this._list[n++]);for(n=this._tail;i>0;)this._list[n=n+1+o&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=o>>>2&&this._shrinkArray(),r}}},t.prototype.splice=function(e,t){var r=e;if(r===(0|r)){var n=this.size();if(r<0&&(r+=n),!(r>n)){if(arguments.length>2){var i,s,o,a=arguments.length,c=this._list.length,l=2;if(!n||r0&&(this._head=this._head+r+c&this._capacityMask)):(o=this.remove(r,t),this._head=this._head+r+c&this._capacityMask);a>l;)this.unshift(arguments[--a]);for(i=r;i>0;i--)this.unshift(s[i-1])}else{var u=(s=new Array(n-(r+t))).length;for(i=0;ithis._tail){for(t=this._head;t>>=1,this._capacityMask>>>=1},e.exports=t},7963:e=>{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,n){if(!e||"string"===typeof e)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"===typeof r&&(n=r,r=""),r&&(n.code=r);try{return t(e,n)}catch(i){n.message=e.message,n.stack=e.stack;const r=function(){};r.prototype=Object.create(Object.getPrototypeOf(e));return t(new r,n)}}},3634:(e,t,r)=>{"use strict";const n=r(5413);t.zN=n.EventIterator,n.EventIterator},5413:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn("EventIterator queue reached ".concat(this.pushQueue.length," items")))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e){let{highWaterMark:t=100,lowWaterMark:n=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new r;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},7143:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,o){if("function"!==typeof n)throw new TypeError("The listener must be a function");var a=new i(n,s||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i{"use strict";var t,r="object"===typeof Reflect?Reflect:null,n=r&&"function"===typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"===typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"===typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}g(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"===typeof e.on&&g(e,"error",t,r)}(e,i,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!==typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function l(e,t,r,n){var i,s,o,l;if(a(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"===typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=c(e))>0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,l=u,console&&console.warn&&console.warn(l)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=u.bind(n);return i.listener=r,n.wrapFn=i,i}function d(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"===typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return!1;if("function"===typeof c)n(c,this,t);else{var l=c.length,u=p(c,l);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return d(this,e,!0)},s.prototype.rawListeners=function(e){return d(this,e,!1)},s.listenerCount=function(e,t){return"function"===typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},1167:e=>{e.exports=class{constructor(e){if(!(e>0)||0!==(e-1&e))throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}}},5125:(e,t,r)=>{const n=r(1167);e.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head}push(e){if(!this.head.push(e)){const t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){const e=this.tail.shift();if(void 0===e&&this.tail.next){const e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}},4737:e=>{e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,s){r[i]=s,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},8974:e=>{"use strict";const t="[a-fA-F\\d:]",r=e=>e&&e.includeBoundaries?"(?:(?<=\\s|^)(?=".concat(t,")|(?<=").concat(t,")(?=\\s|$))"):"",n="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",i="[a-fA-F\\d]{1,4}",s="\n(?:\n(?:".concat(i,":){7}(?:").concat(i,"|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:").concat(i,":){6}(?:").concat(n,"|:").concat(i,"|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:").concat(i,":){5}(?::").concat(n,"|(?::").concat(i,"){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:").concat(i,":){4}(?:(?::").concat(i,"){0,1}:").concat(n,"|(?::").concat(i,"){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:").concat(i,":){3}(?:(?::").concat(i,"){0,2}:").concat(n,"|(?::").concat(i,"){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:").concat(i,":){2}(?:(?::").concat(i,"){0,3}:").concat(n,"|(?::").concat(i,"){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:").concat(i,":){1}(?:(?::").concat(i,"){0,4}:").concat(n,"|(?::").concat(i,"){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::").concat(i,"){0,5}:").concat(n,"|(?::").concat(i,"){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n").replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),o=new RegExp("(?:^".concat(n,"$)|(?:^").concat(s,"$)")),a=new RegExp("^".concat(n,"$")),c=new RegExp("^".concat(s,"$")),l=e=>e&&e.exact?o:new RegExp("(?:".concat(r(e)).concat(n).concat(r(e),")|(?:").concat(r(e)).concat(s).concat(r(e),")"),"g");l.v4=e=>e&&e.exact?a:new RegExp("".concat(r(e)).concat(n).concat(r(e)),"g"),l.v6=e=>e&&e.exact?c:new RegExp("".concat(r(e)).concat(s).concat(r(e)),"g"),e.exports=l},7201:function(e){!function(t){"use strict";const r="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^".concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"$"),"i"),threeOctet:new RegExp("^".concat(r,"\\.").concat(r,"\\.").concat(r,"$"),"i"),twoOctet:new RegExp("^".concat(r,"\\.").concat(r,"$"),"i"),longValue:new RegExp("^".concat(r,"$"),"i")},i=new RegExp("^0[0-7]+$","i"),s=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",a="(?:[0-9a-f]+::?)+",c={zoneIndex:new RegExp(o,"i"),native:new RegExp("^(::)?(".concat(a,")?([0-9a-f]+)?(::)?(").concat(o,")?$"),"i"),deprecatedTransitional:new RegExp("^(?:::)(".concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"(").concat(o,")?)$"),"i"),transitional:new RegExp("^((?:".concat(a,")|(?:::)(?:").concat(a,")?)").concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"(").concat(o,")?$"),"i")};function l(e,t){if(e.indexOf("::")!==e.lastIndexOf("::"))return null;let r,n,i=0,s=-1,o=(e.match(c.zoneIndex)||[])[0];for(o&&(o=o.substring(1),e=e.replace(/%.+$/,""));(s=e.indexOf(":",s+1))>=0;)i++;if("::"===e.substr(0,2)&&i--,"::"===e.substr(-2,2)&&i--,i>t)return null;for(n=t-i,r=":";n--;)r+="0:";return":"===(e=e.replace("::",r))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){const t=e.split(":"),r=[];for(let e=0;e0;){if(i=r-n,i<0&&(i=0),e[s]>>i!==t[s]>>i)return!1;n-=r,s+=1}return!0}function h(e){if(s.test(e))return parseInt(e,16);if("0"===e[0]&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw new Error("ipaddr: cannot parse ".concat(e," as octal"))}return parseInt(e,10)}function d(e,t){for(;e.length=0;n-=1){if(i=this.octets[n],!(i in r))return null;if(s=r[i],t&&0!==s)return null;8!==s&&(t=!0),e+=s}return 32-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return f.IPv6.parse("::ffff:".concat(this.toString()))},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(".")},e}(),f.IPv4.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let s=0;for(;s<4;)i.push(parseInt(r[s],10)|255^parseInt(n[s],10)),s++;return new this(i)}catch(t){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.isIPv4=function(e){return null!==this.parser(e)},f.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(t){return!1}},f.IPv4.isValidFourPartDecimal=function(e){return!(!f.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},f.IPv4.networkAddressFromCIDR=function(e){let t,r,n,i,s;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(o){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.parse=function(e){const t=this.parser(e);if(null===t)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(t)},f.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){const e=parseInt(t[2]);if(e>=0&&e<=32){const r=[this.parse(t[1]),e];return Object.defineProperty(r,"toString",{value:function(){return this.join("/")}}),r}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},f.IPv4.parser=function(e){let t,r,i;if(t=e.match(n.fourOctet))return function(){const e=t.slice(1,6),n=[];for(let t=0;t4294967295||i<0)throw new Error("ipaddr: address outside defined range");return function(){const e=[];let t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e}().reverse()}return(t=e.match(n.twoOctet))?function(){const e=t.slice(1,4),r=[];if(i=h(e[1]),i>16777215||i<0)throw new Error("ipaddr: address outside defined range");return r.push(h(e[0])),r.push(i>>16&255),r.push(i>>8&255),r.push(255&i),r}():(t=e.match(n.threeOctet))?function(){const e=t.slice(1,5),r=[];if(i=h(e[2]),i>65535||i<0)throw new Error("ipaddr: address outside defined range");return r.push(h(e[0])),r.push(h(e[1])),r.push(i>>8&255),r.push(255&i),r}():null},f.IPv4.subnetMaskFromPrefixLength=function(e){if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");const t=[0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r=0;s-=1){if(n=this.parts[s],!(n in r))return null;if(i=r[n],t&&0!==i)return null;16!==i&&(t=!0),e+=i}return 128-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e;const t=[],r=this.parts;for(let n=0;n>8),t.push(255&e);return t},e.prototype.toFixedLengthString=function(){const e=function(){const e=[];for(let t=0;t>8,255&t,r>>8,255&r])},e.prototype.toNormalizedString=function(){const e=function(){const e=[];for(let t=0;ti&&(n=r.index,i=r[0].length);return i<0?t:"".concat(t.substring(0,n),"::").concat(t.substring(n+i))},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e}(),f.IPv6.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let s=0;for(;s<16;)i.push(parseInt(r[s],10)|255^parseInt(n[s],10)),s++;return new this(i)}catch(t){throw new Error("ipaddr: the address does not have IPv6 CIDR format (".concat(t,")"))}},f.IPv6.isIPv6=function(e){return null!==this.parser(e)},f.IPv6.isValid=function(e){if("string"===typeof e&&-1===e.indexOf(":"))return!1;try{const t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch(t){return!1}},f.IPv6.networkAddressFromCIDR=function(e){let t,r,n,i,s;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<16;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(o){throw new Error("ipaddr: the address does not have IPv6 CIDR format (".concat(o,")"))}},f.IPv6.parse=function(e){const t=this.parser(e);if(null===t.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(t.parts,t.zoneId)},f.IPv6.parseCIDR=function(e){let t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]),t>=0&&t<=128))return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},f.IPv6.parser=function(e){let t,r,n,i,s,o;if(n=e.match(c.deprecatedTransitional))return this.parser("::ffff:".concat(n[1]));if(c.native.test(e))return l(e,8);if((n=e.match(c.transitional))&&(o=n[6]||"",t=l(n[1].slice(0,-1)+o,6),t.parts)){for(s=[parseInt(n[2]),parseInt(n[3]),parseInt(n[4]),parseInt(n[5])],r=0;r128)throw new Error("ipaddr: invalid IPv6 prefix length");const t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r{e.exports=function(){return"undefined"!==typeof window&&"object"===typeof window.process&&"renderer"===window.process.type||(!("undefined"===typeof process||"object"!==typeof process.versions||!process.versions.electron)||"object"===typeof navigator&&"string"===typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}},2795:(e,t,r)=>{"use strict";const n=r(8974),i=e=>n({exact:!0}).test(e);i.v4=e=>n.v4({exact:!0}).test(e),i.v6=e=>n.v6({exact:!0}).test(e),i.version=e=>i(e)?i.v4(e)?4:6:void 0,e.exports=i},887:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},6791:(e,t,r)=>{"use strict";const{URLWithLegacySupport:n,format:i,URLSearchParams:s,defaultBase:o}=r(5732),a=r(9640);e.exports={URL:n,URLSearchParams:s,format:i,relative:a,defaultBase:o}},9640:(e,t,r)=>{"use strict";const{URLWithLegacySupport:n,format:i}=r(5732);e.exports=function(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3?arguments[3]:void 0,a=r.protocol?r.protocol.replace(":",""):"http";a=(s[a]||o||a)+":";try{t=new n(e)}catch(l){t={}}const c=Object.assign({},r,{protocol:a||t.protocol,host:r.host||t.host});return new n(e,i(c)).toString()}},5732:e=>{"use strict";const t="undefined"!==typeof navigator&&"ReactNative"===navigator.product;const r=self.URL,n=t?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:"";e.exports={URLWithLegacySupport:class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;this.super=new r(e,t),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(e){this.super.hash=e}set host(e){this.super.host=e}set hostname(e){this.super.hostname=e}set href(e){this.super.href=e}set password(e){this.super.password=e}set pathname(e){this.super.pathname=e}set port(e){this.super.port=e}set protocol(e){this.super.protocol=e}set search(e){this.super.search=e}set username(e){this.super.username=e}static createObjectURL(e){return r.createObjectURL(e)}static revokeObjectURL(e){r.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}},URLSearchParams:self.URLSearchParams,defaultBase:n,format:function(e){if("string"===typeof e){return new r(e).toString()}if(!(e instanceof r)){const t=e.username&&e.password?"".concat(e.username,":").concat(e.password,"@"):"",r=e.auth?e.auth+"@":"",n=e.port?":"+e.port:"",i=e.protocol?e.protocol+"//":"",s=e.host||"",o=e.hostname||"",a=e.search||(e.query?"?"+e.query:""),c=e.hash||"",l=e.pathname||"",u=e.path||l+a;return"".concat(i).concat(t||r).concat(s||o+n).concat(u).concat(c)}}}},464:e=>{"use strict";e.exports=async e=>{const t=[];for await(const r of e)t.push(r);return t}},9272:e=>{"use strict";e.exports=async e=>{for await(const t of e);}},2393:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)await t(r)&&(yield r)}},4744:e=>{"use strict";e.exports=async e=>{for await(const t of e)return t}},1309:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)await t(r),yield r}},7889:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)yield t(r)}},6155:(e,t,r)=>{"use strict";const n=r(9202);e.exports=async function*(){for(var e=arguments.length,t=new Array(e),r=0;r{try{await Promise.all(t.map((async e=>{for await(const t of e)i.push(t)}))),i.end()}catch(e){i.end(e)}}),0),yield*i}},9202:(e,t,r)=>{const n=r(5125);e.exports=e=>{let t;"function"===typeof(e=e||{})?(t=e,e={}):t=e.onEnd;let r,i,s,o=new n;const a=e=>i?i(e):(o.push(e),r),c=e=>s?r:a({done:!1,value:e}),l=e=>s?r:(s=!0,e?(e=>(o=new n,i?i({error:e}):(o.push({error:e}),r)))(e):a({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:()=>{if(!o.isEmpty()){if(e.writev){let e;const t=[];for(;!o.isEmpty();){if(e=o.shift(),e.error)throw e.error;t.push(e.value)}return{done:e.done,value:t}}const t=o.shift();if(t.error)throw t.error;return t}return s?{done:!0}:new Promise(((t,n)=>{i=s=>(i=null,s.error?n(s.error):e.writev&&!s.done?t({done:s.done,value:[s.value]}):t(s),r)}))},return:()=>(o=new n,l(),{done:!0}),throw:e=>(l(e),{done:!0}),push:c,end:l},!t)return r;const u=r;return r={[Symbol.asyncIterator](){return this},next:()=>u.next(),throw:e=>(u.throw(e),t&&(t(e),t=null),{done:!0}),return:()=>(u.return(),t&&(t(),t=null),{done:!0}),push:c,end:e=>(u.end(e),t&&(t(e),t=null),r)},r}},2035:(e,t,r)=>{"use strict";const n=r(464);e.exports=async function*(e,t){const r=await n(e);yield*r.sort(t)}},5959:e=>{"use strict";e.exports=async function*(e,t){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}},7898:(e,t,r)=>{var n;!function(){"use strict";var i="input is invalid type",s="object"===typeof window,o=s?window:{};o.JS_SHA3_NO_WINDOW&&(s=!1);var a=!s&&"object"===typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"===typeof process&&process.versions&&process.versions.node?o=r.g:a&&(o=self);var c=!o.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!==typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],f=[0,8,16,24],p=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],v={128:168,256:136};!o.JS_SHA3_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!u||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"===typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});for(var w=function(e,t,r){return function(n){return new O(e,t,e).update(n)[r]()}},b=function(e,t,r){return function(n,i){return new O(e,t,i).update(n)[r]()}},E=function(e,t,r){return function(t,n,i,s){return C["cshake"+e].update(t,n,i,s)[r]()}},S=function(e,t,r){return function(t,n,i,s){return C["kmac"+e].update(t,n,i,s)[r]()}},_=function(e,t,r,n){for(var i=0;i>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function B(e,t,r){O.call(this,e,t,r)}O.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(i);if(null===e)throw new Error(i);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!u||!ArrayBuffer.isView(e)))throw new Error(i);t=!0}for(var n,s,o=this.blocks,a=this.byteCount,c=e.length,l=this.blockCount,h=0,d=this.s;h>2]|=e[h]<>2]|=s<>2]|=(192|s>>6)<>2]|=(128|63&s)<=57344?(o[n>>2]|=(224|s>>12)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<>2]|=(240|s>>18)<>2]|=(128|s>>12&63)<>2]|=(128|s>>6&63)<>2]|=(128|63&s)<=a){for(this.start=n-a,this.block=o[l],n=0;n>=8);r>0;)i.unshift(r),r=255&(e>>=8),++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},O.prototype.encodeString=function(e){var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(i);if(null===e)throw new Error(i);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!u||!ArrayBuffer.isView(e)))throw new Error(i);t=!0}var n=0,s=e.length;if(t)n=s;else for(var o=0;o=57344?n+=3:(a=65536+((1023&a)<<10|1023&e.charCodeAt(++o)),n+=4)}return n+=this.encode(8*n),this.update(e),n},O.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];o%t===0&&(x(r),s=0)}return i&&(e=r[s],a+=h[e>>4&15]+h[15&e],i>1&&(a+=h[e>>12&15]+h[e>>8&15]),i>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},O.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,s=0,o=0,a=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r===0&&x(n)}return s&&(e=a<<2,t=n[o],c[e]=255&t,s>1&&(c[e+1]=t>>8&255),s>2&&(c[e+2]=t>>16&255)),c},B.prototype=new O,B.prototype.finalize=function(){return this.encode(this.outputBits,!0),O.prototype.finalize.call(this)};var x=function(e){var t,r,n,i,s,o,a,c,l,u,h,d,f,g,y,m,v,w,b,E,S,_,I,A,C,T,R,k,P,N,D,L,O,B,x,M,U,F,V,K,j,z,q,H,G,W,Q,Y,X,$,J,Z,ee,te,re,ne,ie,se,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|l>>>31),r=s^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(u<<1|h>>>31),r=a^(h<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|f>>>31),r=l^(f<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(i<<1|s>>>31),r=h^(s<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Q=e[10]<<4|e[11]>>>28,k=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,q=e[41]<<18|e[40]>>>14,B=e[2]<<1|e[3]>>>31,x=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,X=e[23]<<10|e[22]>>>22,N=e[33]<<13|e[32]>>>19,D=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,M=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,b=e[24]<<11|e[25]>>>21,$=e[34]<<15|e[35]>>>17,J=e[35]<<15|e[34]>>>17,L=e[45]<<29|e[44]>>>3,O=e[44]<<29|e[45]>>>3,A=e[6]<<28|e[7]>>>4,C=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,V=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,H=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,T=e[18]<<20|e[19]>>>12,R=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,K=e[38]<<8|e[39]>>>24,j=e[39]<<8|e[38]>>>24,_=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~v&b,e[10]=A^~T&k,e[11]=C^~R&P,e[20]=B^~M&F,e[21]=x^~U&V,e[30]=H^~W&Y,e[31]=G^~Q&X,e[40]=te^~ne&se,e[41]=re^~ie&oe,e[2]=m^~w&E,e[3]=v^~b&S,e[12]=T^~k&N,e[13]=R^~P&D,e[22]=M^~F&K,e[23]=U^~V&j,e[32]=W^~Y&$,e[33]=Q^~X&J,e[42]=ne^~se&ae,e[43]=ie^~oe&ce,e[4]=w^~E&_,e[5]=b^~S&I,e[14]=k^~N&L,e[15]=P^~D&O,e[24]=F^~K&z,e[25]=V^~j&q,e[34]=Y^~$&Z,e[35]=X^~J&ee,e[44]=se^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~_&g,e[7]=S^~I&y,e[16]=N^~L&A,e[17]=D^~O&C,e[26]=K^~z&B,e[27]=j^~q&x,e[36]=$^~Z&H,e[37]=J^~ee&G,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=_^~g&m,e[9]=I^~y&v,e[18]=L^~A&T,e[19]=O^~C&R,e[28]=z^~B&M,e[29]=q^~x&U,e[38]=Z^~H&W,e[39]=ee^~G&Q,e[48]=le^~te&ne,e[49]=ue^~re&ie,e[0]^=p[n],e[1]^=p[n+1]};if(c)e.exports=C;else{for(R=0;RObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},l=e=>{const t=[];for(const r in e)i.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)s.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{o(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{o(t,r,u(e[r]))})),t}(e):e}const h=(e,t,r,n)=>(r.forEach((r=>{"undefined"===typeof t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?o(e,r,d(e[r],t[r],n)):o(e,r,u(t[r])))})),e);function d(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?((e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!a.includes(e))),r)})),n})(e,t,r):n(t)&&n(e)?h(e,t,l(t),r):u(t)}e.exports=function(){const e=d(u(c),this!==a&&this||{},c);let t={_:{}};for(var r=arguments.length,i=new Array(r),s=0;s{var t=1e3,r=60*t,n=60*r,i=24*n,s=7*i,o=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var s=Math.abs(e);if(s>=i)return a(e,s,i,"day");if(s>=n)return a(e,s,n,"hour");if(s>=r)return a(e,s,r,"minute");if(s>=t)return a(e,s,t,"second");return e+" ms"}(e):function(e){var s=Math.abs(e);if(s>=i)return Math.round(e/i)+"d";if(s>=n)return Math.round(e/n)+"h";if(s>=r)return Math.round(e/r)+"m";if(s>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},486:e=>{"use strict";function t(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,i,s,o,a;for(t=[],i=s=0;s<=3&&0!==e.length;i=++s){if(i>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}o=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(o)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},i=(n=function(e){return e.charCodeAt(0)})("0"),o=n("a"),s=n("A"),r=function(e){var t,r,a,c,l;for(c=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),l=a;a>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-s)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,i;if("string"!==typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"===typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(s){throw s,new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(s){throw s,new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"===typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},8605:(e,t,r)=>{var n=r(392);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(3397),r(4533),r(3877),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!1,mode:n});return i.start(t),i},n.aes.createEncryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!0,mode:n});return i.start(t),i},n.aes.createDecryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){u||h();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return f(r._w,e,t,!1)},decrypt:function(e,t){return f(r._w,e,t,!0)}}}),r._init=!1},n.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!==typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var i=0;i>>=2;for(i=0;i>8^255&h^99,s[g]=h,o[h]=g,f=(d=e[h])<<24^h<<16^h<<8^h^d,p=((r=e[g])^(n=e[r])^(i=e[n]))<<24^(g^i)<<16^(g^n^i)<<8^g^r^i;for(var m=0;m<4;++m)c[m][g]=f,l[m][h]=p,f=f<<24|f>>>8,p=p<<24|p>>>8;0===g?g=y=1:(g=r^e[e[e[r^i]]],y^=e[e[y]])}}function d(e,t){for(var r,n=e.slice(0),i=1,o=n.length,c=4*(o+6+1),u=o;u>>16&255]<<24^s[r>>>8&255]<<16^s[255&r]<<8^s[r>>>24]^a[i]<<24,i++):o>6&&u%o===4&&(r=s[r>>>24]<<24^s[r>>>16&255]<<16^s[r>>>8&255]<<8^s[255&r]),n[u]=n[u-o]^r;if(t){for(var h,d=l[0],f=l[1],p=l[2],g=l[3],y=n.slice(0),m=(u=0,(c=n.length)-4);u>>24]]^f[s[h>>>16&255]]^p[s[h>>>8&255]]^g[s[255&h]];n=y}return n}function f(e,t,r,n){var i,a,u,h,d,f,p,g,y,m,v,w,b=e.length/4-1;n?(i=l[0],a=l[1],u=l[2],h=l[3],d=o):(i=c[0],a=c[1],u=c[2],h=c[3],d=s),f=t[0]^e[0],p=t[n?3:1]^e[1],g=t[2]^e[2],y=t[n?1:3]^e[3];for(var E=3,S=1;S>>24]^a[p>>>16&255]^u[g>>>8&255]^h[255&y]^e[++E],v=i[p>>>24]^a[g>>>16&255]^u[y>>>8&255]^h[255&f]^e[++E],w=i[g>>>24]^a[y>>>16&255]^u[f>>>8&255]^h[255&p]^e[++E],y=i[y>>>24]^a[f>>>16&255]^u[p>>>8&255]^h[255&g]^e[++E],f=m,p=v,g=w;r[0]=d[f>>>24]<<24^d[p>>>16&255]<<16^d[g>>>8&255]<<8^d[255&y]^e[++E],r[n?3:1]=d[p>>>24]<<24^d[g>>>16&255]<<16^d[y>>>8&255]<<8^d[255&f]^e[++E],r[2]=d[g>>>24]<<24^d[y>>>16&255]<<16^d[f>>>8&255]<<8^d[255&p]^e[++E],r[n?1:3]=d[y>>>24]<<24^d[f>>>16&255]<<16^d[p>>>8&255]<<8^d[255&g]^e[++E]}function p(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var s=null;r instanceof n.util.ByteBuffer&&(s=r,r={}),(r=r||{}).output=s,r.iv=e,i.call(t,r)},t}},5049:(e,t,r)=>{var n=r(392);r(3877),r(2886);var i=e.exports=n.asn1=n.asn1||{};function s(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}i.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},i.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},i.create=function(e,t,r,s,o){if(n.util.isArray(s)){for(var a=[],c=0;ct){if(n.strict){var p=new Error("Too few bytes to read ASN.1 value.");throw p.available=e.length(),p.remaining=t,p.requested=f,p}f=t}var g=32===(32&c);if(g)if(h=[],void 0===f)for(;;){if(s(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}a=e.length(),h.push(o(e,t,r+1,n)),t-=a-e.length()}else for(;f>0;)a=e.length(),h.push(o(e,f,r+1,n)),t-=a-e.length(),f-=a-e.length();if(void 0===h&&l===i.Class.UNIVERSAL&&u===i.Type.BITSTRING&&(d=e.bytes(f)),void 0===h&&n.decodeBitStrings&&l===i.Class.UNIVERSAL&&u===i.Type.BITSTRING&&f>1){var y=e.read,m=t,v=0;if(u===i.Type.BITSTRING&&(s(e,t,1),v=e.getByte(),t--),0===v)try{a=e.length();var w=o(e,t,r+1,{strict:!0,decodeBitStrings:!0}),b=a-e.length();t-=b,u==i.Type.BITSTRING&&b++;var E=w.tagClass;b!==f||E!==i.Class.UNIVERSAL&&E!==i.Class.CONTEXT_SPECIFIC||(h=[w])}catch(_){}void 0===h&&(e.read=y,t=m)}if(void 0===h){if(void 0===f){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");f=t}if(u===i.Type.BMPSTRING)for(h="";f>0;f-=2)s(e,t,2),h+=String.fromCharCode(e.getInt16()),t-=2;else h=e.getBytes(f),t-=f}var S=void 0===d?null:{bitStringContents:d};return i.create(l,u,g,h,S)}i.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"===typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.length(),i=o(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var s=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw s.byteCount=r,s.remaining=e.length(),s}return i},i.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,s=n.util.createBuffer(),o=!1;if("bitStringContents"in e&&(o=!0,e.original&&(o=i.equals(e,e.original))),o)s.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:s.putByte(0);for(var a=0;a1&&(0===e.value.charCodeAt(0)&&0===(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128===(128&e.value.charCodeAt(1)))?s.putBytes(e.value.substr(1)):s.putBytes(e.value);if(t.putByte(r),s.length()<=127)t.putByte(127&s.length());else{var c=s.length(),l="";do{l+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|l.length);for(a=l.length-1;a>=0;--a)t.putByte(l.charCodeAt(a))}return t.putBuffer(s),t},i.oidToDer=function(e){var t,r,i,s,o=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(o[0],10)+parseInt(o[1],10));for(var c=2;c>>=7,t||(s|=128),r.push(s),t=!1}while(i>0);for(var l=r.length-1;l>=0;--l)a.putByte(r[l])}return a},i.derToOid=function(e){var t;"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var i=0;e.length()>0;)i<<=7,128&(r=e.getByte())?i+=127&r:(t+="."+(i+r),i=0);return t},i.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),s=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),l=10;"+"!==c&&"-"!==c&&(a=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,0),l&&("+"===(c=e.charAt(l))||"-"===c)){var u=60*parseInt(e.substr(l+1,2),10)+parseInt(e.substr(l+4,2),10);u*=6e4,"+"===c?t.setTime(+t-u):t.setTime(+t+u)}return t},i.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,l=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var h=e.length-5,d=e.charAt(h);"+"!==d&&"-"!==d||(l=60*parseInt(e.substr(h+1,2),10)+parseInt(e.substr(h+4,2),10),l*=6e4,"+"===d&&(l*=-1),u=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(r,n,i),t.setUTCHours(s,o,a,c),t.setTime(+t+l)):(t.setFullYear(r,n,i),t.setHours(s,o,a,c)),t},i.dateToUtcTime=function(e){if("string"===typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},i.derToInteger=function(e){"string"===typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},i.validate=function(e,t,r,s){var o=!1;if(e.tagClass!==t.tagClass&&"undefined"!==typeof t.tagClass||e.type!==t.type&&"undefined"!==typeof t.type)s&&(e.tagClass!==t.tagClass&&s.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&s.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||"undefined"===typeof t.constructed){if(o=!0,t.value&&n.util.isArray(t.value))for(var a=0,c=0;o&&c0&&(s+="\n");for(var o="",c=0;c1?s+="0x"+n.util.bytesToHex(e.value.slice(1)):s+="(none)",e.value.length>0){var d=e.value.charCodeAt(0);1==d?s+=" (1 unused bit shown)":d>1&&(s+=" ("+d+" unused bits shown)")}}else if(e.type===i.Type.OCTETSTRING)a.test(e.value)||(s+="("+e.value+") "),s+="0x"+n.util.bytesToHex(e.value);else if(e.type===i.Type.UTF8)try{s+=n.util.decodeUtf8(e.value)}catch(p){if("URI malformed"!==p.message)throw p;s+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===i.Type.PRINTABLESTRING||e.type===i.Type.IA5String?s+=e.value:a.test(e.value)?s+="0x"+n.util.bytesToHex(e.value):0===e.value.length?s+="[null]":s+=e.value}return s}},5754:e=>{var t={};e.exports=t;var r={};t.encode=function(e,t,r){if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!==typeof r)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var i=0,s=t.length,o=t.charAt(0),a=[0];for(i=0;i0;)a.push(l%s),l=l/s|0}for(i=0;0===e[i]&&i=0;--i)n+=t[a[i]]}else n=function(e,t){var r=0,n=t.length,i=t.charAt(0),s=[0];for(r=0;r0;)s.push(a%n),a=a/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[s[r]];return c}(e,t);if(r){var u=new RegExp(".{1,"+r+"}","g");n=n.match(u).join("\r\n")}return n},t.decode=function(e,t){if("string"!==typeof e)throw new TypeError('"input" must be a string.');if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');var n=r[t];if(!n){n=r[t]=[];for(var i=0;i>=8;for(;u>0;)a.push(255&u),u>>=8}for(var h=0;e[h]===o&&h{var n=r(392);r(3877),e.exports=n.cipher=n.cipher||{},n.cipher.algorithms=n.cipher.algorithms||{},n.cipher.createCipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})},n.cipher.createDecipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})},n.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),n.cipher.algorithms[e]=t},n.cipher.getAlgorithm=function(e){return(e=e.toUpperCase())in n.cipher.algorithms?n.cipher.algorithms[e]:null};var i=n.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};i.prototype.start=function(e){e=e||{};var t={};for(var r in e)t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=n.util.createBuffer(),this.output=e.output||n.util.createBuffer(),this.mode.start(t)},i.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},i.prototype.finish=function(e){!e||"ECB"!==this.mode.name&&"CBC"!==this.mode.name||(this.mode.pad=function(t){return e(this.blockSize,t,!1)},this.mode.unpad=function(t){return e(this.blockSize,t,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t))&&(this._finish=!0,this.update(),!(this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))&&!(this.mode.afterFinish&&!this.mode.afterFinish(this.output,t)))}},4533:(e,t,r)=>{var n=r(392);r(3877),n.cipher=n.cipher||{};var i=e.exports=n.cipher.modes=n.cipher.modes||{};function s(e,t){if("string"===typeof e&&(e=n.util.createBuffer(e)),n.util.isArray(e)&&e.length>4){var r=e;e=n.util.createBuffer();for(var i=0;i0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},i.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},i.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb.prototype.decrypt=i.ofb.prototype.encrypt,i.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=s(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}o(this._inBlock)},i.ctr.prototype.decrypt=i.ctr.prototype.encrypt,i.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},i.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var i=r.length();if(12===i)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(a(8*i)))}this._inBlock=this._j0.slice(0),o(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var s=t.length()%this.blockSize;for(s&&t.fillWithByte(0,this.blockSize-s),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},i.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),o(this._inBlock)},i.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),o(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},i.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,i=this._m[r][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},i.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},i.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,i=16*r,s=new Array(i),o=0;o>>1,i=new Array(r);i[n]=e.slice(0);for(var s=n>>>1;s>0;)this.pow(i[2*s],i[s]=[]),s>>=1;for(s=2;s{var n=r(392);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.des.Algorithm(e,t)}))}r(3397),r(4533),r(3877),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createEncryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!1,mode:t})},n.des.startDecrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createDecryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!0,mode:t})},n.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return f(r._keys,e,t,!1)},decrypt:function(e,t){return f(r._keys,e,t,!0)}}}),r._init=!1},n.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=n.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=function(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],s=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],o=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],p=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length()>8?3:1,m=[],v=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],w=0,b=0;b>>4^S))<<4,E^=t=65535&((S^=t)>>>-16^E),E^=(t=858993459&(E>>>2^(S^=t<<-16)))<<2,E^=t=65535&((S^=t)>>>-16^E),E^=(t=1431655765&(E>>>1^(S^=t<<-16)))<<1,E^=t=16711935&((S^=t)>>>8^E),t=(E^=(t=1431655765&(E>>>1^(S^=t<<8)))<<1)<<8|(S^=t)>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var _=0;_>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27),S&=-15;var I=r[(E&=-15)>>>28]|n[E>>>24&15]|i[E>>>20&15]|s[E>>>16&15]|o[E>>>12&15]|a[E>>>8&15]|c[E>>>4&15],A=l[S>>>28]|u[S>>>24&15]|h[S>>>20&15]|d[S>>>16&15]|f[S>>>12&15]|p[S>>>8&15]|g[S>>>4&15];t=65535&(A>>>16^I),m[w++]=I^t,m[w++]=A^t<<16}}return m}(t),this._init=!0}},i("DES-ECB",n.cipher.modes.ecb),i("DES-CBC",n.cipher.modes.cbc),i("DES-CFB",n.cipher.modes.cfb),i("DES-OFB",n.cipher.modes.ofb),i("DES-CTR",n.cipher.modes.ctr),i("3DES-ECB",n.cipher.modes.ecb),i("3DES-CBC",n.cipher.modes.cbc),i("3DES-CFB",n.cipher.modes.cfb),i("3DES-OFB",n.cipher.modes.ofb),i("3DES-CTR",n.cipher.modes.ctr);var s=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],o=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],a=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],c=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],l=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],u=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],h=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],d=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function f(e,t,r,n){var i,f,p=32===e.length?3:9;i=3===p?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],y=t[1];g^=(f=252645135&(g>>>4^y))<<4,g^=(f=65535&(g>>>16^(y^=f)))<<16,g^=f=858993459&((y^=f)>>>2^g),g^=f=16711935&((y^=f<<2)>>>8^g),g=(g^=(f=1431655765&(g>>>1^(y^=f<<8)))<<1)<<1|g>>>31,y=(y^=f)<<1|y>>>31;for(var m=0;m>>4|y<<28)^e[b+1];f=g,g=y,y=f^(o[E>>>24&63]|c[E>>>16&63]|u[E>>>8&63]|d[63&E]|s[S>>>24&63]|a[S>>>16&63]|l[S>>>8&63]|h[63&S])}f=g,g=y,y=f}y=y>>>1|y<<31,y^=f=1431655765&((g=g>>>1|g<<31)>>>1^y),y^=(f=16711935&(y>>>8^(g^=f<<1)))<<8,y^=(f=858993459&(y>>>2^(g^=f)))<<2,y^=f=65535&((g^=f)>>>16^y),y^=f=252645135&((g^=f<<16)>>>4^y),g^=f<<4,r[0]=g,r[1]=y}function p(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var s=null;r instanceof n.util.ByteBuffer&&(s=r,r={}),(r=r||{}).output=s,r.iv=e,i.call(t,r)},t}},392:e=>{e.exports={options:{usePureJavaScript:!1}}},878:(e,t,r)=>{var n=r(392);r(29),r(3877),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,i=null,s={start:function(s,o){if(null!==s)if("string"===typeof s){if(!((s=s.toLowerCase())in n.md.algorithms))throw new Error('Unknown hash algorithm "'+s+'"');t=n.md.algorithms[s].create()}else t=s;if(null===o)o=e;else{if("string"===typeof o)o=n.util.createBuffer(o);else if(n.util.isArray(o)){var a=o;o=n.util.createBuffer();for(var c=0;ct.blockLength&&(t.start(),t.update(o.bytes()),o=t.digest()),r=n.util.createBuffer(),i=n.util.createBuffer(),l=o.length();for(c=0;c{var n,i=r(392);e.exports=i.jsbn=i.jsbn||{};function s(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function o(){return new s(null)}function a(e,t,r,n,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this.data[e],l=this.data[e++]>>14,u=a*c+l*o;i=((c=o*c+((16383&u)<<14)+r.data[n]+i)>>28)+(u>>14)+a*l,r.data[n++]=268435455&c}return i}i.jsbn.BigInteger=s,"undefined"===typeof navigator?(s.prototype.am=a,n=28):"Microsoft Internet Explorer"==navigator.appName?(s.prototype.am=function(e,t,r,n,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this.data[e],l=this.data[e++]>>15,u=a*c+l*o;i=((c=o*c+((32767&u)<<15)+r.data[n]+(1073741823&i))>>>30)+(u>>>15)+a*l+(i>>>30),r.data[n++]=1073741823&c}return i},n=30):"Netscape"!=navigator.appName?(s.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this.data[e++]+r.data[n]+i;i=Math.floor(o/67108864),r.data[n++]=67108863&o}return i},n=26):(s.prototype.am=a,n=28),s.prototype.DB=n,s.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function g(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function _(){}function I(e){return e}function A(e){this.r2=o(),this.q3=o(),s.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}g.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=o();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(s.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=o();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},s.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},s.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},s.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var a=8==r?255&e[n]:d(e,n);a<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==o?this.data[this.t++]=a:o+r>this.DB?(this.data[this.t-1]|=(a&(1<>this.DB-o):this.data[this.t-1]|=a<=this.DB&&(o-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,o>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},s.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},s.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+o+1]=this.data[r]>>i|a,a=(this.data[r]&s)<=0;--r)t.data[r]=0;t.data[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},s.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,s=(1<>n;for(var o=r+1;o>n;n>0&&(t.data[this.t-r-1]|=(this.s&s)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},s.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},s.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(u,a),i.lShiftTo(u,r)):(n.copyTo(a),i.copyTo(r));var h=a.t,d=a.data[h-1];if(0!=d){var f=d*(1<1?a.data[h-2]>>this.F2:0),g=this.FV/f,y=(1<=0&&(r.data[r.t++]=1,r.subTo(b,r)),s.ONE.dlShiftTo(h,b),b.subTo(a,a);a.t=0;){var E=r.data[--v]==d?this.DM:Math.floor(r.data[v]*g+(r.data[v-1]+m)*y);if((r.data[v]+=a.am(0,E,r,w,0,h))0&&r.rShiftTo(u,r),c<0&&s.ZERO.subTo(r,r)}}},s.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},s.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},s.prototype.exp=function(e,t){if(e>4294967295||e<1)return s.ONE;var r=o(),n=o(),i=t.convert(this),a=p(e)-1;for(i.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var c=r;r=n,n=c}return t.revert(r)},s.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,s=h(r));o>=0;)a>(a+=this.DB-t)):(r=this.data[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(i=!0),i&&(s+=h(r));return i?s:"0"},s.prototype.negate=function(){var e=o();return s.ZERO.subTo(this,e),e},s.prototype.abs=function(){return this.s<0?this.negate():this},s.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},s.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+p(this.data[this.t-1]^this.s&this.DM)},s.prototype.mod=function(e){var t=o();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(s.ZERO)>0&&e.subTo(t,t),t},s.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new g(t):new y(t),this.exp(e,r)},s.ZERO=f(0),s.ONE=f(1),_.prototype.convert=I,_.prototype.revert=I,_.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},_.prototype.sqrTo=function(e,t){e.squareTo(t)},A.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=o();return e.copyTo(t),this.reduce(t),t},A.prototype.revert=function(e){return e},A.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},A.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},A.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var C=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],T=(1<<26)/C[C.length-1];s.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},s.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=f(r),i=o(),s=o(),a="";for(this.divRemTo(n,i,s);i.signum()>0;)a=(r+s.intValue()).toString(e).substr(1)+a,i.divRemTo(n,i,s);return s.intValue().toString(e)+a},s.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,a=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(a,0)),i&&s.ZERO.subTo(this,this)},s.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(s.ONE.shiftLeft(e-1),v,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(s.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},s.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},s.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},s.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r.data[--i]=0;for(n=r.t-this.t;i=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r},s.prototype.millerRabin=function(e){var t=this.subtract(s.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,i=t.shiftRight(r),o={nextBytes:function(e){for(var t=0;t=0);var c=n.modPow(i,this);if(0!=c.compareTo(s.ONE)&&0!=c.compareTo(t)){for(var l=1;l++>24},s.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},s.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},s.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},s.prototype.equals=function(e){return 0==this.compareTo(e)},s.prototype.min=function(e){return this.compareTo(e)<0?this:e},s.prototype.max=function(e){return this.compareTo(e)>0?this:e},s.prototype.and=function(e){var t=o();return this.bitwiseTo(e,m,t),t},s.prototype.or=function(e){var t=o();return this.bitwiseTo(e,v,t),t},s.prototype.xor=function(e){var t=o();return this.bitwiseTo(e,w,t),t},s.prototype.andNot=function(e){var t=o();return this.bitwiseTo(e,b,t),t},s.prototype.not=function(){for(var e=o(),t=0;t=this.t?0!=this.s:0!=(this.data[t]&1<1){var h=o();for(n.sqrTo(a[1],h);c<=u;)a[c]=o(),n.mulTo(h,a[c-2],a[c]),c+=2}var d,m,v=e.t-1,w=!0,b=o();for(i=p(e.data[v])-1;v>=0;){for(i>=l?d=e.data[v]>>i-l&u:(d=(e.data[v]&(1<0&&(d|=e.data[v-1]>>this.DB+i-l)),c=r;0==(1&d);)d>>=1,--c;if((i-=c)<0&&(i+=this.DB,--v),w)a[d].copyTo(s),w=!1;else{for(;c>1;)n.sqrTo(s,b),n.sqrTo(b,s),c-=2;c>0?n.sqrTo(s,b):(m=s,s=b,b=m),n.mulTo(b,a[d],s)}for(;v>=0&&0==(e.data[v]&1<=0?(r.subTo(n,r),t&&i.subTo(a,i),o.subTo(c,o)):(n.subTo(r,n),t&&a.subTo(i,a),c.subTo(o,c))}return 0!=n.compareTo(s.ONE)?s.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},s.prototype.pow=function(e){return this.exp(e,new _)},s.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},s.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=C[C.length-1]){for(t=0;t{var n=r(392);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},1746:(e,t,r)=>{var n=r(392);r(7263),e.exports=n.mgf=n.mgf||{},n.mgf.mgf1=n.mgf1},7263:(e,t,r)=>{var n=r(392);r(3877),n.mgf=n.mgf||{},(e.exports=n.mgf.mgf1=n.mgf1=n.mgf1||{}).create=function(e){return{generate:function(t,r){for(var i=new n.util.ByteBuffer,s=Math.ceil(r/e.digestLength),o=0;o{var n=r(392);n.pki=n.pki||{};var i=e.exports=n.pki.oids=n.oids=n.oids||{};function s(e,t){i[e]=t,i[t]=e}function o(e,t){i[e]=t}s("1.2.840.113549.1.1.1","rsaEncryption"),s("1.2.840.113549.1.1.4","md5WithRSAEncryption"),s("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),s("1.2.840.113549.1.1.7","RSAES-OAEP"),s("1.2.840.113549.1.1.8","mgf1"),s("1.2.840.113549.1.1.9","pSpecified"),s("1.2.840.113549.1.1.10","RSASSA-PSS"),s("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),s("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),s("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),s("1.3.101.112","EdDSA25519"),s("1.2.840.10040.4.3","dsa-with-sha1"),s("1.3.14.3.2.7","desCBC"),s("1.3.14.3.2.26","sha1"),s("1.3.14.3.2.29","sha1WithRSASignature"),s("2.16.840.1.101.3.4.2.1","sha256"),s("2.16.840.1.101.3.4.2.2","sha384"),s("2.16.840.1.101.3.4.2.3","sha512"),s("2.16.840.1.101.3.4.2.4","sha224"),s("2.16.840.1.101.3.4.2.5","sha512-224"),s("2.16.840.1.101.3.4.2.6","sha512-256"),s("1.2.840.113549.2.2","md2"),s("1.2.840.113549.2.5","md5"),s("1.2.840.113549.1.7.1","data"),s("1.2.840.113549.1.7.2","signedData"),s("1.2.840.113549.1.7.3","envelopedData"),s("1.2.840.113549.1.7.4","signedAndEnvelopedData"),s("1.2.840.113549.1.7.5","digestedData"),s("1.2.840.113549.1.7.6","encryptedData"),s("1.2.840.113549.1.9.1","emailAddress"),s("1.2.840.113549.1.9.2","unstructuredName"),s("1.2.840.113549.1.9.3","contentType"),s("1.2.840.113549.1.9.4","messageDigest"),s("1.2.840.113549.1.9.5","signingTime"),s("1.2.840.113549.1.9.6","counterSignature"),s("1.2.840.113549.1.9.7","challengePassword"),s("1.2.840.113549.1.9.8","unstructuredAddress"),s("1.2.840.113549.1.9.14","extensionRequest"),s("1.2.840.113549.1.9.20","friendlyName"),s("1.2.840.113549.1.9.21","localKeyId"),s("1.2.840.113549.1.9.22.1","x509Certificate"),s("1.2.840.113549.1.12.10.1.1","keyBag"),s("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),s("1.2.840.113549.1.12.10.1.3","certBag"),s("1.2.840.113549.1.12.10.1.4","crlBag"),s("1.2.840.113549.1.12.10.1.5","secretBag"),s("1.2.840.113549.1.12.10.1.6","safeContentsBag"),s("1.2.840.113549.1.5.13","pkcs5PBES2"),s("1.2.840.113549.1.5.12","pkcs5PBKDF2"),s("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),s("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),s("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),s("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),s("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),s("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),s("1.2.840.113549.2.7","hmacWithSHA1"),s("1.2.840.113549.2.8","hmacWithSHA224"),s("1.2.840.113549.2.9","hmacWithSHA256"),s("1.2.840.113549.2.10","hmacWithSHA384"),s("1.2.840.113549.2.11","hmacWithSHA512"),s("1.2.840.113549.3.7","des-EDE3-CBC"),s("2.16.840.1.101.3.4.1.2","aes128-CBC"),s("2.16.840.1.101.3.4.1.22","aes192-CBC"),s("2.16.840.1.101.3.4.1.42","aes256-CBC"),s("2.5.4.3","commonName"),s("2.5.4.4","surname"),s("2.5.4.5","serialNumber"),s("2.5.4.6","countryName"),s("2.5.4.7","localityName"),s("2.5.4.8","stateOrProvinceName"),s("2.5.4.9","streetAddress"),s("2.5.4.10","organizationName"),s("2.5.4.11","organizationalUnitName"),s("2.5.4.12","title"),s("2.5.4.13","description"),s("2.5.4.15","businessCategory"),s("2.5.4.17","postalCode"),s("2.5.4.42","givenName"),s("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),s("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),s("2.16.840.1.113730.1.1","nsCertType"),s("2.16.840.1.113730.1.13","nsComment"),o("2.5.29.1","authorityKeyIdentifier"),o("2.5.29.2","keyAttributes"),o("2.5.29.3","certificatePolicies"),o("2.5.29.4","keyUsageRestriction"),o("2.5.29.5","policyMapping"),o("2.5.29.6","subtreesConstraint"),o("2.5.29.7","subjectAltName"),o("2.5.29.8","issuerAltName"),o("2.5.29.9","subjectDirectoryAttributes"),o("2.5.29.10","basicConstraints"),o("2.5.29.11","nameConstraints"),o("2.5.29.12","policyConstraints"),o("2.5.29.13","basicConstraints"),s("2.5.29.14","subjectKeyIdentifier"),s("2.5.29.15","keyUsage"),o("2.5.29.16","privateKeyUsagePeriod"),s("2.5.29.17","subjectAltName"),s("2.5.29.18","issuerAltName"),s("2.5.29.19","basicConstraints"),o("2.5.29.20","cRLNumber"),o("2.5.29.21","cRLReason"),o("2.5.29.22","expirationDate"),o("2.5.29.23","instructionCode"),o("2.5.29.24","invalidityDate"),o("2.5.29.25","cRLDistributionPoints"),o("2.5.29.26","issuingDistributionPoint"),o("2.5.29.27","deltaCRLIndicator"),o("2.5.29.28","issuingDistributionPoint"),o("2.5.29.29","certificateIssuer"),o("2.5.29.30","nameConstraints"),s("2.5.29.31","cRLDistributionPoints"),s("2.5.29.32","certificatePolicies"),o("2.5.29.33","policyMappings"),o("2.5.29.34","policyConstraints"),s("2.5.29.35","authorityKeyIdentifier"),o("2.5.29.36","policyConstraints"),s("2.5.29.37","extKeyUsage"),o("2.5.29.46","freshestCRL"),o("2.5.29.54","inhibitAnyPolicy"),s("1.3.6.1.4.1.11129.2.4.2","timestampList"),s("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),s("1.3.6.1.5.5.7.3.1","serverAuth"),s("1.3.6.1.5.5.7.3.2","clientAuth"),s("1.3.6.1.5.5.7.3.3","codeSigning"),s("1.3.6.1.5.5.7.3.4","emailProtection"),s("1.3.6.1.5.5.7.3.8","timeStamping")},9835:(e,t,r)=>{var n=r(392);if(r(8605),r(5049),r(1400),r(29),r(2886),r(6019),r(6193),r(3860),r(654),r(5493),r(3877),"undefined"===typeof i)var i=n.jsbn.BigInteger;var s=n.asn1,o=n.pki=n.pki||{};e.exports=o.pbe=n.pbe=n.pbe||{};var a=o.oids,c={name:"EncryptedPrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},l={name:"PBES2Algorithms",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},u={name:"pkcs-12PbeParams",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"iterations"}]};function h(e,t){return e.start().update(t).digest().getBytes()}function d(e){var t;if(e){if(!(t=o.oids[s.derToOid(e)])){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}}else t="hmacWithSHA1";return f(t)}function f(e){var t=n.md;switch(e){case"hmacWithSHA224":t=n.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}o.encryptPrivateKeyInfo=function(e,t,r){(r=r||{}).saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var i,c,l,u=n.random.getBytesSync(r.saltSize),h=r.count,d=s.integerToDer(h);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var p,g,y;switch(r.algorithm){case"aes128":i=16,p=16,g=a["aes128-CBC"],y=n.aes.createEncryptionCipher;break;case"aes192":i=24,p=16,g=a["aes192-CBC"],y=n.aes.createEncryptionCipher;break;case"aes256":i=32,p=16,g=a["aes256-CBC"],y=n.aes.createEncryptionCipher;break;case"des":i=8,p=8,g=a.desCBC,y=n.des.createEncryptionCipher;break;default:throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S}var m="hmacWith"+r.prfAlgorithm.toUpperCase(),v=f(m),w=n.pkcs5.pbkdf2(t,u,h,i,v),b=n.random.getBytesSync(p);(_=y(w)).start(b),_.update(s.toDer(e)),_.finish(),l=_.output.getBytes();var E=function(e,t,r,i){var a=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,e),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,t.getBytes())]);"hmacWithSHA1"!==i&&a.value.push(s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,n.util.hexToBytes(r.toString(16))),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(o.oids[i]).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]));return a}(u,d,i,m);c=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a.pkcs5PBES2).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a.pkcs5PBKDF2).getBytes()),E]),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(g).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,b)])])])}else{var S;if("3des"!==r.algorithm)throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S;i=24;var _,I=new n.util.ByteBuffer(u);w=o.pbe.generatePkcs12Key(t,I,1,h,i),b=o.pbe.generatePkcs12Key(t,I,2,h,i);(_=n.des.createEncryptionCipher(w)).start(b),_.update(s.toDer(e)),_.finish(),l=_.output.getBytes(),c=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,u),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,d.getBytes())])])}return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[c,s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,l)])},o.decryptPrivateKeyInfo=function(e,t){var r=null,i={},a=[];if(!s.validate(e,c,i,a)){var l=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=a,l}var u=s.derToOid(i.encryptionOid),h=o.pbe.getCipher(u,i.encryptionParams,t),d=n.util.createBuffer(i.encryptedData);return h.update(d),h.finish()&&(r=s.fromDer(h.output)),r},o.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:s.toDer(e).getBytes()};return n.pem.encode(r,{maxline:t})},o.encryptedPrivateKeyFromPem=function(e){var t=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==t.type){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return s.fromDer(t.body)},o.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var i=o.wrapRsaPrivateKey(o.privateKeyToAsn1(e));return i=o.encryptPrivateKeyInfo(i,t,r),o.encryptedPrivateKeyToPem(i)}var a,c,l,u;switch(r.algorithm){case"aes128":a="AES-128-CBC",l=16,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes192":a="AES-192-CBC",l=24,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes256":a="AES-256-CBC",l=32,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"3des":a="DES-EDE3-CBC",l=24,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;case"des":a="DES-CBC",l=8,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;default:var h=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw h.algorithm=r.algorithm,h}var d=u(n.pbe.opensslDeriveBytes(t,c.substr(0,8),l));d.start(c),d.update(s.toDer(o.privateKeyToAsn1(e))),d.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:a,parameters:n.util.bytesToHex(c).toUpperCase()},body:d.output.getBytes()};return n.pem.encode(f)},o.decryptRsaPrivateKey=function(e,t){var r=null,i=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==i.type&&"PRIVATE KEY"!==i.type&&"RSA PRIVATE KEY"!==i.type)throw(l=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=l,l;if(i.procType&&"ENCRYPTED"===i.procType.type){var a,c;switch(i.dekInfo.algorithm){case"DES-CBC":a=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":a=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":a=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var l;throw(l=new Error('Could not decrypt private key; unsupported encryption algorithm "'+i.dekInfo.algorithm+'".')).algorithm=i.dekInfo.algorithm,l}var u=n.util.hexToBytes(i.dekInfo.parameters),h=c(n.pbe.opensslDeriveBytes(t,u.substr(0,8),a));if(h.start(u),h.update(n.util.createBuffer(i.body)),!h.finish())return r;r=h.output.getBytes()}else r=i.body;return null!==(r="ENCRYPTED PRIVATE KEY"===i.type?o.decryptPrivateKeyInfo(s.fromDer(r),t):s.fromDer(r))&&(r=o.privateKeyFromAsn1(r)),r},o.pbe.generatePkcs12Key=function(e,t,r,i,s,o){var a,c;if("undefined"===typeof o||null===o){if(!("sha1"in n.md))throw new Error('"sha1" hash algorithm unavailable.');o=n.md.sha1.create()}var l=o.digestLength,u=o.blockLength,h=new n.util.ByteBuffer,d=new n.util.ByteBuffer;if(null!==e&&void 0!==e){for(c=0;c=0;c--)k>>=8,k+=A.at(c)+R.at(c),R.setAt(c,255&k);T.putBuffer(R)}b=T,h.putBuffer(_)}return h.truncate(h.length()-s),h},o.pbe.getCipher=function(e,t,r){switch(e){case o.oids.pkcs5PBES2:return o.pbe.getCipherForPBES2(e,t,r);case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case o.oids["pbewithSHAAnd40BitRC2-CBC"]:return o.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},o.pbe.getCipherForPBES2=function(e,t,r){var i,a={},c=[];if(!s.validate(t,l,a,c))throw(i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,i;if((e=s.derToOid(a.kdfOid))!==o.oids.pkcs5PBKDF2)throw(i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,i.supportedOids=["pkcs5PBKDF2"],i;if((e=s.derToOid(a.encOid))!==o.oids["aes128-CBC"]&&e!==o.oids["aes192-CBC"]&&e!==o.oids["aes256-CBC"]&&e!==o.oids["des-EDE3-CBC"]&&e!==o.oids.desCBC)throw(i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i;var u,h,f=a.kdfSalt,p=n.util.createBuffer(a.kdfIterationCount);switch(p=p.getInt(p.length()<<3),o.oids[e]){case"aes128-CBC":u=16,h=n.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,h=n.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,h=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,h=n.des.createDecryptionCipher;break;case"desCBC":u=8,h=n.des.createDecryptionCipher}var g=d(a.prfOid),y=n.pkcs5.pbkdf2(r,f,p,u,g),m=a.encIv,v=h(y);return v.start(m),v},o.pbe.getCipherForPKCS12PBE=function(e,t,r){var i={},a=[];if(!s.validate(t,u,i,a))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=a,g;var c,l,h,f=n.util.createBuffer(i.salt),p=n.util.createBuffer(i.iterations);switch(p=p.getInt(p.length()<<3),e){case o.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,l=8,h=n.des.startDecrypting;break;case o.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,l=8,h=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var y=d(i.prfOid),m=o.pbe.generatePkcs12Key(r,f,1,p,c,y);return y.start(),h(m,o.pbe.generatePkcs12Key(r,f,2,p,l,y))},o.pbe.opensslDeriveBytes=function(e,t,r,i){if("undefined"===typeof i||null===i){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');i=n.md.md5.create()}null===t&&(t="");for(var s=[h(i,e+t)],o=16,a=1;o{var n=r(392);r(878),r(29),r(3877);var i,s=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(i=r(5819)),e.exports=n.pbkdf2=s.pbkdf2=function(e,t,r,s,o,a){if("function"===typeof o&&(a=o,o=null),n.util.isNodejs&&!n.options.usePureJavaScript&&i.pbkdf2&&(null===o||"object"!==typeof o)&&(i.pbkdf2Sync.length>4||!o||"sha1"===o))return"string"!==typeof o&&(o="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),a?4===i.pbkdf2Sync.length?i.pbkdf2(e,t,r,s,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):i.pbkdf2(e,t,r,s,o,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):4===i.pbkdf2Sync.length?i.pbkdf2Sync(e,t,r,s).toString("binary"):i.pbkdf2Sync(e,t,r,s,o).toString("binary");if("undefined"!==typeof o&&null!==o||(o="sha1"),"string"===typeof o){if(!(o in n.md.algorithms))throw new Error("Unknown hash algorithm: "+o);o=n.md[o].create()}var c=o.digestLength;if(s>4294967295*c){var l=new Error("Derived key is too long.");if(a)return a(l);throw l}var u=Math.ceil(s/c),h=s-(u-1)*c,d=n.hmac.create();d.start(o,e);var f,p,g,y="";if(!a){for(var m=1;m<=u;++m){d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),f=g=d.digest().getBytes();for(var v=2;v<=r;++v)d.start(null,null),d.update(g),p=d.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p;y+=mu)return a(null,y);d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(m)),f=g=d.digest().getBytes(),v=2,b()}function b(){if(v<=r)return d.start(null,null),d.update(g),p=d.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p,++v,n.util.setImmediate(b);y+=m{var n=r(392);r(3877);var i=e.exports=n.pem=n.pem||{};function s(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},i=0;i65&&-1!==o){var a=t[o];","===a?(++o,t=t.substr(0,o)+"\r\n "+t.substr(o)):t=t.substr(0,o)+"\r\n"+a+t.substr(o+1),s=i-o-1,o=-1,++i}else" "!==t[i]&&"\t"!==t[i]&&","!==t[i]||(o=i);return t}function o(e){return e.replace(/^\s+/,"")}i.encode=function(e,t){t=t||{};var r,i="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(i+=s(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(i+=s(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),i+=s(r)),e.headers)for(var o=0;o{var n=r(392);r(3877),r(3860),r(928);var i=e.exports=n.pkcs1=n.pkcs1||{};function s(e,t,r){r||(r=n.md.sha1.create());for(var i="",s=Math.ceil(t/r.digestLength),o=0;o>24&255,o>>16&255,o>>8&255,255&o);r.start(),r.update(e+a),i+=r.digest().getBytes()}return i.substring(0,t)}i.encode_rsa_oaep=function(e,t,r){var i,o,a,c;"string"===typeof r?(i=r,o=arguments[3]||void 0,a=arguments[4]||void 0):r&&(i=r.label||void 0,o=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),c||(c=a);var l=Math.ceil(e.n.bitLength()/8),u=l-2*a.digestLength-2;if(t.length>u)throw(y=new Error("RSAES-OAEP input message length is too long.")).length=t.length,y.maxLength=u,y;i||(i=""),a.update(i,"raw");for(var h=a.digest(),d="",f=u-t.length,p=0;p{var n=r(392);r(8605),r(5049),r(1400),r(2886),r(6193),r(4922),r(3860),r(3877),r(3391);var i=n.asn1,s=e.exports=n.pkcs7=n.pkcs7||{};function o(e){var t={},r=[];if(!i.validate(e,s.asn1.recipientInfoValidator,t,r)){var o=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw o.errors=r,o}return{version:t.version.charCodeAt(0),issuer:n.pki.RDNAttributesAsArray(t.issuer),serialNumber:n.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:i.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function a(e){for(var t,r=[],s=0;s0){for(var r=i.create(i.Class.CONTEXT_SPECIFIC,1,!0,[]),s=0;s=r&&o0&&o.value[0].value.push(i.create(i.Class.CONTEXT_SPECIFIC,0,!0,t)),s.length>0&&o.value[0].value.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,s)),o.value[0].value.push(i.create(i.Class.UNIVERSAL,i.Type.SET,!0,e.signerInfos)),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.type).getBytes()),o])},addSigner:function(t){var r=t.issuer,i=t.serialNumber;if(t.certificate){var s=t.certificate;"string"===typeof s&&(s=n.pki.certificateFromPem(s)),r=s.issuer.attributes,i=s.serialNumber}var o=t.key;if(!o)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"===typeof o&&(o=n.pki.privateKeyFromPem(o));var a=t.digestAlgorithm||n.pki.oids.sha1;switch(a){case n.pki.oids.sha1:case n.pki.oids.sha256:case n.pki.oids.sha384:case n.pki.oids.sha512:case n.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+a)}var c=t.authenticatedAttributes||[];if(c.length>0){for(var l=!1,u=!1,h=0;h{var n=r(392);r(5049),r(3877);var i=n.asn1,s=e.exports=n.pkcs7asn1=n.pkcs7asn1||{};n.pkcs7=n.pkcs7||{},n.pkcs7.asn1=s;var o={name:"ContentInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};s.contentInfoValidator=o;var a={name:"EncryptedContentInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};s.envelopedDataValidator={name:"EnvelopedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(a)},s.encryptedDataValidator={name:"EncryptedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"}].concat(a)};var c={name:"SignerInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};s.signedDataValidator={name:"SignedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},o,{name:"SignedData.Certificates",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,capture:"signerInfos",optional:!0,value:[c]}]},s.recipientInfoValidator={name:"RecipientInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},5132:(e,t,r)=>{var n=r(392);r(3877),r(3055),r(3860),function(){if(n.prime)e.exports=n.prime;else{var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,i=[6,4,2,4,2,4,6,2],s=new r(null);s.fromInt(30);var o=function(e,t){return e|t};t.generateProbablePrime=function(e,t,i){"function"===typeof t&&(i=t,t={});var s=(t=t||{}).algorithm||"PRIMEINC";"string"===typeof s&&(s={name:s}),s.options=s.options||{};var o=t.prng||n.random,c={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;re&&(o=l(e,t));var f=o.toString(16);i.target.postMessage({hex:f,workLoad:u}),o.dAddOffset(h,0)}}}f()}(e,t,i,s);return a(e,t,i,s)}(e,c,s.options,i);throw new Error("Invalid prime generation algorithm: "+s.name)}}function a(e,t,r,n){var i=l(e,t),s=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(i.bitLength());"millerRabinTests"in r&&(s=r.millerRabinTests);var o=10;"maxBlockTime"in r&&(o=r.maxBlockTime),c(i,e,t,0,s,o,n)}function c(e,t,r,s,o,a,u){var h=+new Date;do{if(e.bitLength()>t&&(e=l(t,r)),e.isProbablePrime(o))return u(null,e);e.dAddOffset(i[s++%8],0)}while(a<0||+new Date-h{var n=r(392);r(3877);var i=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(i=r(5819)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,s=new Array(32),o=0;o<32;++o)s[o]=r.create();function a(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r===0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var i=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(i),t.generated=0}function l(e){var t=null,r=n.util.globalScope,i=r.crypto||r.msCrypto;i&&i.getRandomValues&&(t=function(e){return i.getRandomValues(e)});var s=n.util.createBuffer();if(t)for(;s.length()>16)))<<16,d=4294967295&(u=(2147483647&(u+=l>>15))+(u>>31));for(c=0;c<3;++c)h=d>>>(c<<3),h^=Math.floor(256*Math.random()),s.putByte(255&h)}return s.getBytes(e)}return t.pools=s,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var i=t.plugin.cipher,s=t.plugin.increment,o=t.plugin.formatKey,a=t.plugin.formatSeed,l=n.util.createBuffer();t.key=null,function u(h){if(h)return r(h);if(l.length()>=e)return r(null,l.getBytes(e));t.generated>1048575&&(t.key=null);if(null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(u)}));var d=i(t.key,t.seed);t.generated+=d.length,l.putBytes(d),t.key=o(i(t.key,s(t.seed))),t.seed=a(i(t.key,t.seed)),n.util.setImmediate(u)}()},t.generateSync=function(e){var r=t.plugin.cipher,i=t.plugin.increment,s=t.plugin.formatKey,o=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&a();var l=r(t.key,t.seed);t.generated+=l.length,c.putBytes(l),t.key=s(r(t.key,i(t.seed))),t.seed=o(r(t.key,t.seed))}return c.getBytes(e)},i?(t.seedFile=function(e,t){i.randomBytes(e,(function(e,r){if(e)return t(e);t(null,r.toString())}))},t.seedFileSync=function(e){return i.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,l(e))}catch(r){t(r)}},t.seedFileSync=l),t.collect=function(e){for(var r=e.length,n=0;n>i&255);t.collect(n)},t.registerWorker=function(e){if(e===self)t.seedFile=function(e,t){self.addEventListener("message",(function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))})),self.postMessage({forge:{prng:{needed:e}}})};else{e.addEventListener("message",(function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,(function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})}))}))}},t}},325:(e,t,r)=>{var n=r(392);r(3860),r(3877),(e.exports=n.pss=n.pss||{}).create=function(e){3===arguments.length&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t,r=e.md,i=e.mgf,s=r.digestLength,o=e.salt||null;if("string"===typeof o&&(o=n.util.createBuffer(o)),"saltLength"in e)t=e.saltLength;else{if(null===o)throw new Error("Salt length not specified or specific salt not given.");t=o.length()}if(null!==o&&o.length()!==t)throw new Error("Given salt length does not match length of given salt.");var a=e.prng||n.random,c={encode:function(e,c){var l,u,h=c-1,d=Math.ceil(h/8),f=e.digest().getBytes();if(d>8*d-h&255;return(b=String.fromCharCode(b.charCodeAt(0)&~E)+b.substr(1))+g+String.fromCharCode(188)},verify:function(e,o,a){var c,l=a-1,u=Math.ceil(l/8);if(o=o.substr(-u),u>8*u-l&255;if(0!==(d.charCodeAt(0)&p))throw new Error("Bits beyond keysize not zero as expected.");var g=i.generate(f,h),y="";for(c=0;c{var n=r(392);r(8605),r(7404),r(6140),r(3877),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},i=new Array(4),s=n.util.createBuffer();function o(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,i,!1),s.putInt32(i[0]),s.putInt32(i[1]),s.putInt32(i[2]),s.putInt32(i[3]),s.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=o(),c=null,l=n.util.globalScope,u=l.crypto||l.msCrypto;if(u&&u.getRandomValues&&(c=function(e){return u.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){if("undefined"===typeof window||window.document,a.collectInt(+new Date,32),"undefined"!==typeof navigator){var h="";for(var d in navigator)try{"string"==typeof navigator[d]&&(h+=navigator[d])}catch(f){}a.collect(h),h=null}t&&(t().mousemove((function(e){a.collectInt(e.clientX,16),a.collectInt(e.clientY,16)})),t().keypress((function(e){a.collectInt(e.charCode,8)})))}if(n.random)for(var d in a)n.random[d]=a[d];else n.random=a;n.random.createInstance=o,e.exports=n.random}("undefined"!==typeof jQuery?jQuery:null)},654:(e,t,r)=>{var n=r(392);r(3877);var i=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],s=[1,2,3,5],o=function(e,t){return e<>16-t},a=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"===typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,s=e,o=e.length(),a=t,c=Math.ceil(a/8),l=255>>(7&a);for(r=o;r<128;r++)s.putByte(i[s.at(r-1)+s.at(r-o)&255]);for(s.setAt(128-c,i[s.at(128-c)&l]),r=127-c;r>=0;r--)s.setAt(r,i[s.at(r+1)^s.at(r+c)]);return s};var c=function(e,t,r){var i,c,l,u,h=!1,d=null,f=null,p=null,g=[];for(e=n.rc2.expandKey(e,t),l=0;l<64;l++)g.push(e.getInt16Le());r?(i=function(e){for(l=0;l<4;l++)e[l]+=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),e[l]=o(e[l],s[l]),u++},c=function(e){for(l=0;l<4;l++)e[l]+=g[63&e[(l+3)%4]]}):(i=function(e){for(l=3;l>=0;l--)e[l]=a(e[l],s[l]),e[l]-=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),u--},c=function(e){for(l=3;l>=0;l--)e[l]-=g[63&e[(l+3)%4]]});var y=function(e){var t=[];for(l=0;l<4;l++){var n=d.getInt16Le();null!==p&&(r?n^=p.getInt16Le():p.putInt16Le(n)),t.push(65535&n)}u=r?0:63;for(var i=0;i=8;)y([[5,i],[1,c],[6,i],[1,c],[5,i]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,d,!r);else{var n=8===d.length()?8:8-d.length();d.fillWithByte(n,n)}if(t&&(h=!0,m.update()),!r&&(t=0===d.length()))if(e)t=e(8,f,!r);else{var i=f.length(),s=f.at(i-1);s>i?t=!1:f.truncate(s)}return t}}};n.rc2.startEncrypting=function(e,t,r){var i=n.rc2.createEncryptionCipher(e,128);return i.start(t,r),i},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var i=n.rc2.createDecryptionCipher(e,128);return i.start(t,r),i},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},5493:(e,t,r)=>{var n=r(392);if(r(5049),r(3055),r(2886),r(2627),r(5132),r(3860),r(3877),"undefined"===typeof i)var i=n.jsbn.BigInteger;var s=n.util.isNodejs?r(5819):null,o=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,l=[6,4,2,4,2,4,6,2],u={name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},h={name:"RSAPrivateKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},d={name:"RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},f=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},p={name:"DigestInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:o.Class.UNIVERSAL,type:o.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=o.oidToDer(t).getBytes(),i=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]),s=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[]);s.value.push(o.create(o.Class.UNIVERSAL,o.Type.OID,!1,n)),s.value.push(o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,""));var a=o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(s),i.value.push(a),o.toDer(i).getBytes()},y=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var s;t.dP||(t.dP=t.d.mod(t.p.subtract(i.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(i.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{s=new i(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(s.compareTo(t.n)>=0||!s.gcd(t.n).equals(i.ONE));for(var o=(e=e.multiply(s.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);o.compareTo(a)<0;)o=o.add(t.p);var c=o.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return c=c.multiply(s.modInverse(t.n)).mod(t.n)};function m(e,t,r){var i=n.util.createBuffer(),s=Math.ceil(t.n.bitLength()/8);if(e.length>s-11){var o=new Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=s-11,o}i.putByte(0),i.putByte(r);var a,c=s-3-e.length;if(0===r||1===r){a=0===r?0:255;for(var l=0;l0;){var u=0,h=n.random.getBytes(c);for(l=0;l1;){if(255!==o.getByte()){--o.read;break}++l}else if(2===c)for(l=0;o.length()>1;){if(0===o.getByte()){--o.read;break}++l}if(0!==o.getByte()||l!==s-3-o.length())throw new Error("Encryption block is invalid.");return o.getBytes()}function w(e,t,r){"function"===typeof t&&(r=t,t={});var s={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function o(){a(e.pBits,(function(t,n){return t?r(t):(e.p=n,null!==e.q?l(t,e.q):void a(e.qBits,l))}))}function a(e,t){n.prime.generateProbablePrime(e,s,t)}function l(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var s=e.p;e.p=e.q,e.q=s}if(0!==e.p.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.p=null,void o();if(0!==e.q.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.q=null,void a(e.qBits,l);if(e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(i.ONE))return e.p=e.q=null,void o();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,l);var u=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(s.prng=t.prng),o()}function b(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0===(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128===(128&r.charCodeAt(1)))?r.substr(1):r}function E(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function S(e){return n.util.isNodejs&&"function"===typeof s[e]}function _(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.crypto&&"object"===typeof a.globalScope.crypto.subtle&&"function"===typeof a.globalScope.crypto.subtle[e]}function I(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.msCrypto&&"object"===typeof a.globalScope.msCrypto.subtle&&"function"===typeof a.globalScope.msCrypto.subtle[e]}function A(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),i=0;i0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),u.getBytes()},c.rsa.decrypt=function(e,t,r,s){var o=Math.ceil(t.n.bitLength()/8);if(e.length!==o){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=o,a}var c=new i(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var l=y(c,t,r).toString(16),u=n.util.createBuffer(),h=o-Math.ceil(l.length/2);h>0;)u.putByte(0),--h;return u.putBytes(n.util.hexToBytes(l)),!1!==s?v(u.getBytes(),t,r):u.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"===typeof e&&(e=parseInt(e,10)),e=e||2048;var s,o=(r=r||{}).prng||n.random,a={nextBytes:function(e){for(var t=o.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(s.eInt),s},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new i(null);r.fromInt(30);for(var n,s=0,o=function(e,t){return e|t},a=+new Date,u=0;null===e.keys&&(t<=0||uh?e.pqState=0:e.num.isProbablePrime(E(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(l[s++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(i.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var f=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}u+=(n=+new Date)-a,a=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,i){if(1===arguments.length?"object"===typeof e?(r=e,e=void 0):"function"===typeof e&&(i=e,e=void 0):2===arguments.length?"number"===typeof e?"function"===typeof t?(i=t,t=void 0):"number"!==typeof t&&(r=t,t=void 0):(r=e,i=t,e=void 0,t=void 0):3===arguments.length&&("number"===typeof t?"function"===typeof r&&(i=r,r=void 0):(i=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(i){if(S("generateKeyPair"))return s.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return i(e);i(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(_("generateKey")&&_("exportKey"))return a.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then((function(e){return a.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)})).then(void 0,(function(e){i(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(e)));i(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(I("generateKey")&&I("exportKey")){var l=a.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:A(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return l.oncomplete=function(e){var t=e.target.result,r=a.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=c.privateKeyFromAsn1(o.fromDer(n.util.createBuffer(t)));i(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){i(e)}},void(l.onerror=function(e){i(e)})}}else if(S("generateKeyPairSync")){var u=s.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(u.privateKey),publicKey:c.publicKeyFromPem(u.publicKey)}}var h=c.rsa.createKeyPairGenerationState(e,t,r);if(!i)return c.rsa.stepKeyPairGenerationState(h,0),h.keys;w(h,r,i)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,i){if("string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return m(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,i)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"===typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var s=t.encode(e,r,!0);return c.rsa.encrypt(s,r,!0)},verify:function(e,t,i,s){"string"===typeof i?i=i.toUpperCase():void 0===i&&(i="RSASSA-PKCS1-V1_5"),void 0===s&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===i?i={verify:function(e,t){t=v(t,r,!0);var i=o.fromDer(t,{parseAllBytes:s._parseAllDigestBytes}),a={},c=[];if(!o.validate(i,p,a,c))throw(l=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,l;var l,u=o.derToOid(a.algorithmIdentifier);if(u!==n.oids.md2&&u!==n.oids.md5&&u!==n.oids.sha1&&u!==n.oids.sha224&&u!==n.oids.sha256&&u!==n.oids.sha384&&u!==n.oids.sha512&&u!==n.oids["sha512-224"]&&u!==n.oids["sha512-256"])throw(l=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=u,l;if((u===n.oids.md2||u===n.oids.md5)&&!("parameters"in a))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return e===a.digest}}:"NONE"!==i&&"NULL"!==i&&null!==i||(i={verify:function(e,t){return e===(t=v(t,r,!0))}});var a=c.rsa.decrypt(t,r,!0,!1);return i.verify(e,a,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,i,s,o,a,l){var u={n:e,e:t,d:r,p:i,q:s,dP:o,dQ:a,qInv:l,decrypt:function(e,t,r){"string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var i=c.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:v};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(i,u,!1)},sign:function(e,t){var r=!1;"string"===typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var n=t.encode(e,u.n.bitLength());return c.rsa.encrypt(n,u,r)}};return u},c.wrapRsaPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,o.toDer(e).getBytes())])},c.privateKeyFromAsn1=function(e){var t,r,s,a,l,d,f,p,g={},y=[];if(o.validate(e,u,g,y)&&(e=o.fromDer(n.util.createBuffer(g.privateKey))),g={},y=[],!o.validate(e,h,g,y)){var m=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw m.errors=y,m}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),s=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),l=n.util.createBuffer(g.privateKeyPrime2).toHex(),d=n.util.createBuffer(g.privateKeyExponent1).toHex(),f=n.util.createBuffer(g.privateKeyExponent2).toHex(),p=n.util.createBuffer(g.privateKeyCoefficient).toHex(),c.setRsaPrivateKey(new i(t,16),new i(r,16),new i(s,16),new i(a,16),new i(l,16),new i(d,16),new i(f,16),new i(p,16))},c.privateKeyToAsn1=c.privateKeyToRSAPrivateKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,o.integerToDer(0).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.e)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.d)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.p)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.q)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.dP)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.dQ)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.qInv))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(o.validate(e,f,t,r)){var s,a=o.derToOid(t.publicKeyOid);if(a!==c.oids.rsaEncryption)throw(s=new Error("Cannot read public key. Unknown OID.")).oid=a,s;e=t.rsaPublicKey}if(r=[],!o.validate(e,d,t,r))throw(s=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,s;var l=n.util.createBuffer(t.publicKeyModulus).toHex(),u=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new i(l,16),new i(u,16))},c.publicKeyToAsn1=c.publicKeyToSubjectPublicKeyInfo=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(c.oids.rsaEncryption).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]),o.create(o.Class.UNIVERSAL,o.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.publicKeyToRSAPublicKey=function(e){return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.n)),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,b(e.e))])}},928:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=i,i.create=function(){o||(s=String.fromCharCode(128),s+=n.util.fillString(String.fromCharCode(0),64),o=!0);var e=null,t=n.util.createBuffer(),r=new Array(80),i={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s>>0,c>>>0];for(var l=i.fullMessageLength.length-1;l>=0;--l)i.fullMessageLength[l]+=c[1],c[1]=c[0]+(i.fullMessageLength[l]/4294967296>>>0),i.fullMessageLength[l]=i.fullMessageLength[l]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(s),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var c,l=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;o.putBytes(s.substr(0,i.blockLength-l));for(var u=8*i.fullMessageLength[0],h=0;h>>0,o.putInt32(u>>>0),u=c>>>0;o.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,o);var f=n.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f},i};var s=null,o=!1;function a(e,t,r){for(var n,i,s,o,a,c,l,u=r.length();u>=64;){for(i=e.h0,s=e.h1,o=e.h2,a=e.h3,c=e.h4,l=0;l<16;++l)n=r.getInt32(),t[l]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<20;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(i<<5|i>>>27)+(a^s&(o^a))+c+1518500249+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<32;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(i<<5|i>>>27)+(s^o^a)+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<40;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(s^o^a)+c+1859775393+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<60;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(s&o|a&(s^o))+c+2400959708+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;for(;l<80;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(s^o^a)+c+3395469782+n,c=a,a=o,o=(s<<30|s>>>2)>>>0,s=i,i=n;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+o|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,u-=64}}},7404:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=i,i.create=function(){o||(s=String.fromCharCode(128),s+=n.util.fillString(String.fromCharCode(0),64),a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],o=!0);var e=null,t=n.util.createBuffer(),r=new Array(64),i={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,s=0;s>>0,a>>>0];for(var l=i.fullMessageLength.length-1;l>=0;--l)i.fullMessageLength[l]+=a[1],a[1]=a[0]+(i.fullMessageLength[l]/4294967296>>>0),i.fullMessageLength[l]=i.fullMessageLength[l]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(s),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var o=n.util.createBuffer();o.putBytes(t.bytes());var a,l=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;o.putBytes(s.substr(0,i.blockLength-l));for(var u=8*i.fullMessageLength[0],h=0;h>>0,o.putInt32(u>>>0),u=a>>>0;o.putInt32(u);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};c(d,r,o);var f=n.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f.putInt32(d.h5),f.putInt32(d.h6),f.putInt32(d.h7),f},i};var s=null,o=!1,a=null;function c(e,t,r){for(var n,i,s,o,c,l,u,h,d,f,p,g,y,m=r.length();m>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=((i=t[c-15])>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[c]=n+t[c-7]+i+t[c-16]|0;for(l=e.h0,u=e.h1,h=e.h2,d=e.h3,f=e.h4,p=e.h5,g=e.h6,y=e.h7,c=0;c<64;++c)s=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),o=l&u|h&(l^u),n=y+((f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7))+(g^f&(p^g))+a[c]+t[c],y=g,g=p,p=f,f=d+n>>>0,d=h,h=u,u=l,l=n+(i=s+o)>>>0;e.h0=e.h0+l|0,e.h1=e.h1+u|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+f|0,e.h5=e.h5+p|0,e.h6=e.h6+g|0,e.h7=e.h7+y|0,m-=64}}},4770:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=i;var s=n.sha384=n.sha512.sha384=n.sha512.sha384||{};s.create=function(){return i.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=s,n.sha512.sha256=n.sha512.sha256||{create:function(){return i.create("SHA-512/256")}},n.md["sha512/256"]=n.md.algorithms["sha512/256"]=n.sha512.sha256,n.sha512.sha224=n.sha512.sha224||{create:function(){return i.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,i.create=function(e){if(a||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),128),c=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],(l={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],l["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],l["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],l["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],a=!0),"undefined"===typeof e&&(e="SHA-512"),!(e in l))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=l[e],r=null,i=n.util.createBuffer(),s=new Array(80),h=0;h<80;++h)s[h]=new Array(2);var d=64;switch(e){case"SHA-384":d=48;break;case"SHA-512/256":d=32;break;case"SHA-512/224":d=28}var f={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:d,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){f.messageLength=0,f.fullMessageLength=f.messageLength128=[];for(var e=f.messageLengthSize/4,s=0;s>>0,o>>>0];for(var a=f.fullMessageLength.length-1;a>=0;--a)f.fullMessageLength[a]+=o[1],o[1]=o[0]+(f.fullMessageLength[a]/4294967296>>>0),f.fullMessageLength[a]=f.fullMessageLength[a]>>>0,o[0]=o[1]/4294967296>>>0;return i.putBytes(e),u(r,s,i),(i.read>2048||0===i.length())&&i.compact(),f},f.digest=function(){var t=n.util.createBuffer();t.putBytes(i.bytes());var a,c=f.fullMessageLength[f.fullMessageLength.length-1]+f.messageLengthSize&f.blockLength-1;t.putBytes(o.substr(0,f.blockLength-c));for(var l=8*f.fullMessageLength[0],h=0;h>>0,t.putInt32(l>>>0),l=a>>>0;t.putInt32(l);var d=new Array(r.length);for(h=0;h=128;){for(P=0;P<16;++P)t[P][0]=r.getInt32()>>>0,t[P][1]=r.getInt32()>>>0;for(;P<80;++P)n=(((N=(L=t[P-2])[0])>>>19|(D=L[1])<<13)^(D>>>29|N<<3)^N>>>6)>>>0,i=((N<<13|D>>>19)^(D<<3|N>>>29)^(N<<26|D>>>6))>>>0,s=(((N=(B=t[P-15])[0])>>>1|(D=B[1])<<31)^(N>>>8|D<<24)^N>>>7)>>>0,o=((N<<31|D>>>1)^(N<<24|D>>>8)^(N<<25|D>>>7))>>>0,O=t[P-7],x=t[P-16],D=i+O[1]+o+x[1],t[P][0]=n+O[0]+s+x[0]+(D/4294967296>>>0)>>>0,t[P][1]=D>>>0;for(p=e[0][0],g=e[0][1],y=e[1][0],m=e[1][1],v=e[2][0],w=e[2][1],b=e[3][0],E=e[3][1],S=e[4][0],_=e[4][1],I=e[5][0],A=e[5][1],C=e[6][0],T=e[6][1],R=e[7][0],k=e[7][1],P=0;P<80;++P)u=((S>>>14|_<<18)^(S>>>18|_<<14)^(_>>>9|S<<23))>>>0,h=(C^S&(I^C))>>>0,a=((p>>>28|g<<4)^(g>>>2|p<<30)^(g>>>7|p<<25))>>>0,l=((p<<4|g>>>28)^(g<<30|p>>>2)^(g<<25|p>>>7))>>>0,d=(p&y|v&(p^y))>>>0,f=(g&m|w&(g^m))>>>0,D=k+(((S<<18|_>>>14)^(S<<14|_>>>18)^(_<<23|S>>>9))>>>0)+((T^_&(A^T))>>>0)+c[P][1]+t[P][1],n=R+u+h+c[P][0]+t[P][0]+(D/4294967296>>>0)>>>0,i=D>>>0,s=a+d+((D=l+f)/4294967296>>>0)>>>0,o=D>>>0,R=C,k=T,C=I,T=A,I=S,A=_,S=b+n+((D=E+i)/4294967296>>>0)>>>0,_=D>>>0,b=v,E=w,v=y,w=m,y=p,m=g,p=n+s+((D=i+o)/4294967296>>>0)>>>0,g=D>>>0;D=e[0][1]+g,e[0][0]=e[0][0]+p+(D/4294967296>>>0)>>>0,e[0][1]=D>>>0,D=e[1][1]+m,e[1][0]=e[1][0]+y+(D/4294967296>>>0)>>>0,e[1][1]=D>>>0,D=e[2][1]+w,e[2][0]=e[2][0]+v+(D/4294967296>>>0)>>>0,e[2][1]=D>>>0,D=e[3][1]+E,e[3][0]=e[3][0]+b+(D/4294967296>>>0)>>>0,e[3][1]=D>>>0,D=e[4][1]+_,e[4][0]=e[4][0]+S+(D/4294967296>>>0)>>>0,e[4][1]=D>>>0,D=e[5][1]+A,e[5][0]=e[5][0]+I+(D/4294967296>>>0)>>>0,e[5][1]=D>>>0,D=e[6][1]+T,e[6][0]=e[6][0]+C+(D/4294967296>>>0)>>>0,e[6][1]=D>>>0,D=e[7][1]+k,e[7][0]=e[7][0]+R+(D/4294967296>>>0)>>>0,e[7][1]=D>>>0,M-=128}}},3877:(e,t,r)=>{var n=r(392),i=r(5754),s=e.exports=n.util=n.util||{};function o(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"===typeof e)this.data=e;else if(s.isArrayBuffer(e)||s.isArrayBufferView(e))if("undefined"!==typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(n){for(var r=0;r15?(r=Date.now(),o(e)):(t.push(e),1===t.length&&i.setAttribute("a",n=!n))}}s.nextTick=s.setImmediate}(),s.isNodejs="undefined"!==typeof process&&process.versions&&process.versions.node,s.globalScope=s.isNodejs?r.g:"undefined"===typeof self?window:self,s.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},s.isArrayBuffer=function(e){return"undefined"!==typeof ArrayBuffer&&e instanceof ArrayBuffer},s.isArrayBufferView=function(e){return e&&s.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},s.ByteBuffer=a,s.ByteStringBuffer=a;s.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},s.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},s.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},s.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},s.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},s.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},s.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(s.encodeUtf8(e))},s.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},s.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},s.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},s.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},s.ByteStringBuffer.prototype.putInt=function(e,t){o(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},s.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},s.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},s.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},s.ByteStringBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},s.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},s.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},s.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},s.ByteStringBuffer.prototype.copy=function(){var e=s.createBuffer(this.data);return e.read=this.read,e},s.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},s.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},s.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},s.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},s.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},s.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},s.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},s.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},s.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},s.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},s.DataBuffer.prototype.putInt=function(e,t){o(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},s.DataBuffer.prototype.putSignedInt=function(e,t){return o(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},s.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},s.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},s.DataBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},s.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},s.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},s.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},s.DataBuffer.prototype.copy=function(){return new s.DataBuffer(this)},s.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},s.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},s.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},s.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},s.xorBytes=function(e,t,r){for(var n="",i="",s="",o=0,a=0;r>0;--r,++o)i=e.charCodeAt(o)^t.charCodeAt(o),a>=10&&(n+=s,s="",a=0),s+=String.fromCharCode(i),++a;return n+=s},s.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],u="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";s.encode64=function(e,t){for(var r,n,i,s="",o="",a=0;a>2),s+=c.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":(s+=c.charAt((15&n)<<2|i>>6),s+=isNaN(i)?"=":c.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+=s},s.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,i,s="",o=0;o>4),64!==n&&(s+=String.fromCharCode((15&r)<<4|n>>2),64!==i&&(s+=String.fromCharCode((3&n)<<6|i)));return s},s.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},s.decodeUtf8=function(e){return decodeURIComponent(escape(e))},s.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:i.encode,decode:i.decode}},s.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},s.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s>2),s+=c.charAt((3&r)<<4|n>>4),isNaN(n)?s+="==":(s+=c.charAt((15&n)<<2|i>>6),s+=isNaN(i)?"=":c.charAt(63&i)),t&&s.length>t&&(o+=s.substr(0,t)+"\r\n",s=s.substr(t));return o+=s},s.binary.base64.decode=function(e,t,r){var n,i,s,o,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,u=r=r||0;c>4,64!==s&&(a[u++]=(15&i)<<4|s>>2,64!==o&&(a[u++]=(3&s)<<6|o));return t?u-r:a.subarray(0,u)},s.binary.base58.encode=function(e,t){return s.binary.baseN.encode(e,u,t)},s.binary.base58.decode=function(e,t){return s.binary.baseN.decode(e,u,t)},s.text={utf8:{},utf16:{}},s.text.utf8.encode=function(e,t,r){e=s.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,o=0;o0&&s.push(r),o=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":s.push("%");break;default:s.push("<%"+a+"?>")}}return s.push(e.substring(o)),s.join("")},s.formatNumber=function(e,t,r,n){var i=e,s=isNaN(t=Math.abs(t))?2:t,o=void 0===r?",":r,a=void 0===n?".":n,c=i<0?"-":"",l=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",u=l.length>3?l.length%3:0;return c+(u?l.substr(0,u)+a:"")+l.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+a)+(s?o+Math.abs(i-l).toFixed(s).slice(2):"")},s.formatSize=function(e){return e=e>=1073741824?s.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?s.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?s.formatNumber(e/1024,0)+" KiB":s.formatNumber(e,0)+" bytes"},s.bytesFromIP=function(e){return-1!==e.indexOf(".")?s.bytesFromIPv4(e):-1!==e.indexOf(":")?s.bytesFromIPv6(e):null},s.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=s.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(o)}if(r.length>0){var l=r[n];l.end-l.start>0&&(t.splice(l.start,l.end-l.start+1,""),0===l.start&&t.unshift(""),7===l.end&&t.push(""))}return t.join(":")},s.estimateCores=function(e,t){if("function"===typeof e&&(t=e,e={}),e=e||{},"cores"in s&&!e.update)return t(null,s.cores);if("undefined"!==typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return s.cores=navigator.hardwareConcurrency,t(null,s.cores);if("undefined"===typeof Worker)return s.cores=1,t(null,s.cores);if("undefined"===typeof Blob)return s.cores=2,t(null,s.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()a.st&&i.sti.st&&a.st{var n=r(392);r(8605),r(5049),r(1400),r(29),r(1746),r(2886),r(6193),r(325),r(5493),r(3877);var i=n.asn1,s=e.exports=n.pki=n.pki||{},o=s.oids,a={};a.CN=o.commonName,a.commonName="CN",a.C=o.countryName,a.countryName="C",a.L=o.localityName,a.localityName="L",a.ST=o.stateOrProvinceName,a.stateOrProvinceName="ST",a.O=o.organizationName,a.organizationName="O",a.OU=o.organizationalUnitName,a.organizationalUnitName="OU",a.E=o.emailAddress,a.emailAddress="E";var c=n.pki.rsa.publicKeyValidator,l={name:"Certificate",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:i.Class.UNIVERSAL,type:i.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:i.Class.UNIVERSAL,type:i.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:i.Class.UNIVERSAL,type:i.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:i.Class.UNIVERSAL,type:i.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},c,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:i.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:i.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},u={name:"rsapss",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:i.Class.UNIVERSAL,type:i.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:i.Class.UNIVERSAL,type:i.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:i.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:i.Class.UNIVERSAL,type:i.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:i.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:i.Class.UNIVERSAL,type:i.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},h={name:"CertificationRequestInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},c,{name:"CertificationRequestInfo.attributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0}]}]}]},d={name:"CertificationRequest",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[h,{name:"CertificationRequest.signatureAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};function f(e,t){"string"===typeof t&&(t={shortName:t});for(var r,n=null,i=0;null===n&&i128)throw new Error('Invalid "nsComment" content.');e.value=i.create(i.Class.UNIVERSAL,i.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&t.cert){var f=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=f.toHex(),e.value=i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,f.getBytes())}else if("authorityKeyIdentifier"===e.name&&t.cert){e.value=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);u=e.value.value;if(e.keyIdentifier){var p=!0===e.keyIdentifier?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;u.push(i.create(i.Class.CONTEXT_SPECIFIC,0,!1,p))}if(e.authorityCertIssuer){var g=[i.create(i.Class.CONTEXT_SPECIFIC,4,!0,[m(!0===e.authorityCertIssuer?t.cert.issuer:e.authorityCertIssuer)])];u.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,g))}if(e.serialNumber){var y=n.util.hexToBytes(!0===e.serialNumber?t.cert.serialNumber:e.serialNumber);u.push(i.create(i.Class.CONTEXT_SPECIFIC,2,!1,y))}}else if("cRLDistributionPoints"===e.name){e.value=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);u=e.value.value;var v,w=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]),b=i.create(i.Class.CONTEXT_SPECIFIC,0,!0,[]);for(d=0;d2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(h.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(c.validity.notBefore=h[0],c.validity.notAfter=h[1],c.tbsCertificate=r.tbsCertificate,t){c.md=g({signatureOid:c.signatureOid,type:"certificate"});var d=i.toDer(c.tbsCertificate);c.md.update(d.getBytes())}var y=n.md.sha1.create(),m=i.toDer(r.certIssuer);y.update(m.getBytes()),c.issuer.getField=function(e){return f(c.issuer,e)},c.issuer.addField=function(e){v([e]),c.issuer.attributes.push(e)},c.issuer.attributes=s.RDNAttributesAsArray(r.certIssuer),r.certIssuerUniqueId&&(c.issuer.uniqueId=r.certIssuerUniqueId),c.issuer.hash=y.digest().toHex();var w=n.md.sha1.create(),b=i.toDer(r.certSubject);return w.update(b.getBytes()),c.subject.getField=function(e){return f(c.subject,e)},c.subject.addField=function(e){v([e]),c.subject.attributes.push(e)},c.subject.attributes=s.RDNAttributesAsArray(r.certSubject),r.certSubjectUniqueId&&(c.subject.uniqueId=r.certSubjectUniqueId),c.subject.hash=w.digest().toHex(),r.certExtensions?c.extensions=s.certificateExtensionsFromAsn1(r.certExtensions):c.extensions=[],c.publicKey=s.publicKeyFromAsn1(r.subjectPublicKeyInfo),c},s.certificateExtensionsFromAsn1=function(e){for(var t=[],r=0;r1&&(r=c.value.charCodeAt(1),s=c.value.length>2?c.value.charCodeAt(2):0),t.digitalSignature=128===(128&r),t.nonRepudiation=64===(64&r),t.keyEncipherment=32===(32&r),t.dataEncipherment=16===(16&r),t.keyAgreement=8===(8&r),t.keyCertSign=4===(4&r),t.cRLSign=2===(2&r),t.encipherOnly=1===(1&r),t.decipherOnly=128===(128&s)}else if("basicConstraints"===t.name){(c=i.fromDer(t.value)).value.length>0&&c.value[0].type===i.Type.BOOLEAN?t.cA=0!==c.value[0].value.charCodeAt(0):t.cA=!1;var a=null;c.value.length>0&&c.value[0].type===i.Type.INTEGER?a=c.value[0].value:c.value.length>1&&(a=c.value[1].value),null!==a&&(t.pathLenConstraint=i.derToInteger(a))}else if("extKeyUsage"===t.name)for(var c=i.fromDer(t.value),l=0;l1&&(r=c.value.charCodeAt(1)),t.client=128===(128&r),t.server=64===(64&r),t.email=32===(32&r),t.objsign=16===(16&r),t.reserved=8===(8&r),t.sslCA=4===(4&r),t.emailCA=2===(2&r),t.objCA=1===(1&r)}else if("subjectAltName"===t.name||"issuerAltName"===t.name){var h;t.altNames=[];c=i.fromDer(t.value);for(var d=0;d=S&&e<_?i.create(i.Class.UNIVERSAL,i.Type.UTCTIME,!1,i.dateToUtcTime(e)):i.create(i.Class.UNIVERSAL,i.Type.GENERALIZEDTIME,!1,i.dateToGeneralizedTime(e))}s.getTBSCertificate=function(e){var t=I(e.validity.notBefore),r=I(e.validity.notAfter),o=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.CONTEXT_SPECIFIC,0,!0,[i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,i.integerToDer(e.version).getBytes())]),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,n.util.hexToBytes(e.serialNumber)),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.siginfo.algorithmOid).getBytes()),b(e.siginfo.algorithmOid,e.siginfo.parameters)]),m(e.issuer),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[t,r]),m(e.subject),s.publicKeyToAsn1(e.publicKey)]);return e.issuer.uniqueId&&o.value.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,[i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)])),e.subject.uniqueId&&o.value.push(i.create(i.Class.CONTEXT_SPECIFIC,2,!0,[i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.subject.uniqueId)])),e.extensions.length>0&&o.value.push(s.certificateExtensionsToAsn1(e.extensions)),o},s.getCertificationRequestInfo=function(e){return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,i.integerToDer(e.version).getBytes()),m(e.subject),s.publicKeyToAsn1(e.publicKey),E(e)])},s.distinguishedNameToAsn1=function(e){return m(e)},s.certificateToAsn1=function(e){var t=e.tbsCertificate||s.getTBSCertificate(e);return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[t,i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.signatureOid).getBytes()),b(e.signatureOid,e.signatureParameters)]),i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},s.certificateExtensionsToAsn1=function(e){var t=i.create(i.Class.CONTEXT_SPECIFIC,3,!0,[]),r=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);t.value.push(r);for(var n=0;nu.validity.notAfter)&&(c={message:"Certificate is not valid yet or has expired.",error:s.certificateError.certificate_expired,notBefore:u.validity.notBefore,notAfter:u.validity.notAfter,now:o}),null===c){if(null===(h=t[0]||e.getIssuer(u))&&u.isIssuer(u)&&(d=!0,h=u),h){var f=h;n.util.isArray(f)||(f=[f]);for(var p=!1;!p&&f.length>0;){h=f.shift();try{p=h.verify(u)}catch(S){}}p||(c={message:"Certificate signature is invalid.",error:s.certificateError.bad_certificate})}null!==c||h&&!d||e.hasCertificate(u)||(c={message:"Certificate is not trusted.",error:s.certificateError.unknown_ca})}if(null===c&&h&&!u.isIssuer(h)&&(c={message:"Certificate issuer is invalid.",error:s.certificateError.bad_certificate}),null===c)for(var g={keyUsage:!0,basicConstraints:!0},y=0;null===c&&yv.pathLenConstraint&&(c={message:"Certificate basicConstraints pathLenConstraint violated.",error:s.certificateError.bad_certificate})}var b=null===c||c.error,E=r.verify?r.verify(b,l,i):b;if(!0!==E)throw!0===b&&(c={message:"The application rejected the certificate.",error:s.certificateError.bad_certificate}),(E||0===E)&&("object"!==typeof E||n.util.isArray(E)?"string"===typeof E&&(c.error=E):(E.message&&(c.message=E.message),E.error&&(c.error=E.error))),c;c=null,a=!1,++l}while(t.length>0);return!0}},9879:(e,t,r)=>{const n=r(5125),i=r(2673);e.exports=class{constructor(){this._buffer=new n,this._waitingConsumers=new n}push(e){const{promise:t,resolve:r}=i();return this._buffer.push({chunk:e,resolve:r}),this._consume(),t}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){const e=this._waitingConsumers.shift(),t=this._buffer.shift();e.resolve(t.chunk),t.resolve()}}shift(){const{promise:e,resolve:t}=i();return this._waitingConsumers.push({resolve:t}),this._consume(),e}isEmpty(){return this._buffer.isEmpty()}}},2673:e=>{"use strict";e.exports=()=>{const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}},3931:(e,t,r)=>{"use strict";e.exports=r(3794).default},3794:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(7922),s=n(r(8974)),o=n(r(2795)),a=r(7201),c=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new i.Netmask(e)));function l(e){return/^::$/.test(e)||/^::1$/.test(e)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}t.default=e=>{if((0,a.isValid)(e)){const t=(0,a.parse)(e);if("ipv4"===t.kind())return function(e){for(let t of c)if(t.contains(e))return!0;return!1}(t.toNormalizedString());if("ipv6"===t.kind())return l(e)}else if((0,o.default)(e)&&s.default.v6().test(e))return l(e)}},5368:(e,t,r)=>{"use strict";e.exports=r(8154)},1427:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},7276:(e,t,r)=>{"use strict";var n=t,i=r(222),s=r(2440);function o(e,t,r,n){if(t.resolvedType)if(t.resolvedType instanceof i){e("switch(d%s){",n);for(var s=t.resolvedType.values,o=Object.keys(s),a=0;a>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":c=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,c)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,c?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof i?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var s=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":s=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,s?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=s.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n{"use strict";e.exports=function(e){var t=s.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter((function(e){return e.map})).length?",k,value":""))("while(r.pos>>3){");for(var r=0;r>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===i.basic[c]?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",c),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==i.long[a.keyType]?t('%s[typeof k==="object"?util.longToHash(k):k]=value',l):t("%s[k]=value",l)):a.repeated?(t("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==i.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos{"use strict";e.exports=function(e){for(var t,r=s.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(s.compareFieldsById),c=0;c>>0,8|i.mapKey[l.keyType],l.keyType),void 0===d?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==i.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?o(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?o(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(222),i=r(8517),s=r(2440);function o(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},222:(e,t,r)=>{"use strict";e.exports=o;var n=r(5154);((o.prototype=Object.create(n.prototype)).constructor=o).className="Enum";var i=r(3452),s=r(2440);function o(e,t,r,i,s,o){if(n.call(this,e,r),t&&"object"!==typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=i,this.comments=s||{},this.valuesOptions=o,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c{"use strict";e.exports=l;var n=r(5154);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var i,s=r(222),o=r(8517),a=r(2440),c=/^required|optional|repeated$/;function l(e,t,r,i,s,l,u){if(a.isObject(i)?(u=s,l=i,i=s=void 0):a.isObject(s)&&(u=l,l=s,s=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==i&&!c.test(i=i.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==s&&!a.isString(s))throw TypeError("extend must be a string");"proto3_optional"===i&&(i="optional"),this.rule=i&&"optional"!==i?i:void 0,this.type=r,this.id=t,this.extend=s||void 0,this.required="required"===i,this.optional=!this.required,this.repeated="repeated"===i,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==o.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=o.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof i?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"===typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof s)||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"===typeof this.typeDefault){var e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof i&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.d=function(e,t,r,n){return"function"===typeof t?t=a.decorateType(t).name:t&&"object"===typeof t&&(t=a.decorateEnum(t).name),function(i,s){a.decorateType(i.constructor).add(new l(s,e,t,r,{default:n}))}},l._configure=function(e){i=e}},4582:(e,t,r)=>{"use strict";var n=e.exports=r(4722);n.build="light",n.load=function(e,t,r){return"function"===typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(6886),n.decoder=r(2715),n.verifier=r(709),n.converter=r(7276),n.ReflectionObject=r(5154),n.Namespace=r(3452),n.Root=r(8622),n.Enum=r(222),n.Type=r(8716),n.Field=r(6734),n.OneOf=r(9794),n.MapField=r(4479),n.Service=r(4173),n.Method=r(4865),n.Message=r(4486),n.wrappers=r(9025),n.types=r(8517),n.util=r(2440),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},4722:(e,t,r)=>{"use strict";var n=t;function i(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(7063),n.BufferWriter=r(2815),n.Reader=r(6216),n.BufferReader=r(3557),n.util=r(3097),n.rpc=r(9994),n.roots=r(7907),n.configure=i,i()},8154:(e,t,r)=>{"use strict";var n=e.exports=r(4582);n.build="full",n.tokenize=r(3077),n.parse=r(7781),n.common=r(1427),n.Root._configure(n.Type,n.parse,n.common)},4479:(e,t,r)=>{"use strict";e.exports=o;var n=r(6734);((o.prototype=Object.create(n.prototype)).constructor=o).className="MapField";var i=r(8517),s=r(2440);function o(e,t,r,i,o,a){if(n.call(this,e,t,i,void 0,void 0,o,a),!s.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}o.fromJSON=function(e,t){return new o(e,t.id,t.keyType,t.type,t.options,t.comment)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===i.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},o.d=function(e,t,r){return"function"===typeof r?r=s.decorateType(r).name:r&&"object"===typeof r&&(r=s.decorateEnum(r).name),function(n,i){s.decorateType(n.constructor).add(new o(i,e,t,r))}}},4486:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e){if(e)for(var t=Object.keys(e),r=0;r{"use strict";e.exports=s;var n=r(5154);((s.prototype=Object.create(n.prototype)).constructor=s).className="Method";var i=r(2440);function s(e,t,r,s,o,a,c,l,u){if(i.isObject(o)?(c=o,o=a=void 0):i.isObject(a)&&(c=a,a=void 0),void 0!==t&&!i.isString(t))throw TypeError("type must be a string");if(!i.isString(r))throw TypeError("requestType must be a string");if(!i.isString(s))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!o||void 0,this.responseType=s,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}s.fromJSON=function(e,t){return new s(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},s.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},3452:(e,t,r)=>{"use strict";e.exports=h;var n=r(5154);((h.prototype=Object.create(n.prototype)).constructor=h).className="Namespace";var i,s,o,a=r(6734),c=r(2440),l=r(9794);function u(e,t){if(e&&e.length){for(var r={},n=0;nt)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r0;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof h))throw Error("path conflicts with non-namespace objects")}else r.add(r=new h(n))}return t&&r.addJSON(t),r},h.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t-1)return n}else if(n instanceof h&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var i=0;i{"use strict";e.exports=s,s.className="ReflectionObject";var n,i=r(2440);function s(e,t){if(!i.isString(e))throw TypeError("name must be a string");if(t&&!i.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(s.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),s.prototype.toJSON=function(){throw Error()},s.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof n&&t._handleAdd(this)},s.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},s.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},s.prototype.getOption=function(e){if(this.options)return this.options[e]},s.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},s.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var s=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(s){var o=s[e];i.setProperty(o,r,t)}else(s={})[e]=i.setProperty({},r,t),n.push(s)}else{var a={};a[e]=t,n.push(a)}return this},s.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n{"use strict";e.exports=o;var n=r(5154);((o.prototype=Object.create(n.prototype)).constructor=o).className="OneOf";var i=r(6734),s=r(2440);function o(e,t,r,i){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=i}function a(e){if(e.parent)for(var t=0;t-1&&this.oneof.splice(t,1),e.partOf=null,this},o.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t{"use strict";e.exports=I,I.filename=null,I.defaults={keepCase:!1};var n=r(3077),i=r(8622),s=r(8716),o=r(6734),a=r(4479),c=r(9794),l=r(222),u=r(4173),h=r(4865),d=r(8517),f=r(2440),p=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,m=/^-?0[x][0-9a-fA-F]+$/,v=/^0[0-7]+$/,w=/^-?0[0-7]+$/,b=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,_=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function I(e,t,r){t instanceof i||(r=t,t=new i),r||(r=I.defaults);var A,C,T,R,k,P=r.preferTrailingComment||!1,N=n(e,r.alternateCommentMode||!1),D=N.next,L=N.push,O=N.peek,B=N.skip,x=N.cmnt,M=!0,U=!1,F=t,V=r.keepCase?function(e){return e}:f.camelCase;function K(e,t,r){var n=I.filename;return r||(I.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+N.line+")")}function j(){var e,t=[];do{if('"'!==(e=D())&&"'"!==e)throw K(e);t.push(D()),B(e),e=O()}while('"'===e||"'"===e);return t.join("")}function z(e){var t=D();switch(t){case"'":case'"':return L(t),j();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e,t){var r=1;"-"===e.charAt(0)&&(r=-1,e=e.substring(1));switch(e){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(p.test(e))return r*parseInt(e,10);if(y.test(e))return r*parseInt(e,16);if(v.test(e))return r*parseInt(e,8);if(b.test(e))return r*parseFloat(e);throw K(e,"number",t)}(t,!0)}catch(r){if(e&&S.test(t))return t;throw K(t,"value")}}function q(e,t){var r,n;do{!t||'"'!==(r=O())&&"'"!==r?e.push([n=H(D()),B("to",!0)?H(D()):n]):e.push(j())}while(B(",",!0));B(";")}function H(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw K(e,"id");if(g.test(e))return parseInt(e,10);if(m.test(e))return parseInt(e,16);if(w.test(e))return parseInt(e,8);throw K(e,"id")}function G(){if(void 0!==A)throw K("package");if(A=D(),!S.test(A))throw K(A,"name");F=F.define(A),B(";")}function W(){var e,t=O();switch(t){case"weak":e=T||(T=[]),D();break;case"public":D();default:e=C||(C=[])}t=j(),B(";"),e.push(t)}function Q(){if(B("="),R=j(),!(U="proto3"===R)&&"proto2"!==R)throw K(R,"syntax");B(";")}function Y(e,t){switch(t){case"option":return ee(e,t),B(";"),!0;case"message":return $(e,t),!0;case"enum":return Z(e,t),!0;case"service":return function(e,t){if(!E.test(t=D()))throw K(t,"service name");var r=new u(t);X(r,(function(e){if(!Y(r,e)){if("rpc"!==e)throw K(e);!function(e,t){var r=x(),n=t;if(!E.test(t=D()))throw K(t,"name");var i,s,o,a,c=t;B("("),B("stream",!0)&&(s=!0);if(!S.test(t=D()))throw K(t);i=t,B(")"),B("returns"),B("("),B("stream",!0)&&(a=!0);if(!S.test(t=D()))throw K(t);o=t,B(")");var l=new h(c,n,i,o,s,a);l.comment=r,X(l,(function(e){if("option"!==e)throw K(e);ee(l,e),B(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=D()))throw K(t,"reference");var r=t;X(null,(function(t){switch(t){case"required":case"repeated":J(e,t,r);break;case"optional":J(e,U?"proto3_optional":"optional",r);break;default:if(!U||!S.test(t))throw K(t);L(t),J(e,"optional",r)}}))}(e,t),!0}return!1}function X(e,t,r){var n=N.line;if(e&&("string"!==typeof e.comment&&(e.comment=x()),e.filename=I.filename),B("{",!0)){for(var i;"}"!==(i=D());)t(i);B(";",!0)}else r&&r(),B(";"),e&&("string"!==typeof e.comment||P)&&(e.comment=x(n)||e.comment)}function $(e,t){if(!E.test(t=D()))throw K(t,"type name");var r=new s(t);X(r,(function(e){if(!Y(r,e))switch(e){case"map":!function(e){B("<");var t=D();if(void 0===d.mapKey[t])throw K(t,"type");B(",");var r=D();if(!S.test(r))throw K(r,"type");B(">");var n=D();if(!E.test(n))throw K(n,"name");B("=");var i=new a(V(n),H(D()),t,r);X(i,(function(e){if("option"!==e)throw K(e);ee(i,e),B(";")}),(function(){ne(i)})),e.add(i)}(r);break;case"required":case"repeated":J(r,e);break;case"optional":J(r,U?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=D()))throw K(t,"name");var r=new c(V(t));X(r,(function(e){"option"===e?(ee(r,e),B(";")):(L(e),J(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":q(r.extensions||(r.extensions=[]));break;case"reserved":q(r.reserved||(r.reserved=[]),!0);break;default:if(!U||!S.test(e))throw K(e);L(e),J(r,"optional")}})),e.add(r)}function J(e,t,r){var n=D();if("group"!==n){if(!S.test(n))throw K(n,"type");var i=D();if(!E.test(i))throw K(i,"name");i=V(i),B("=");var a=new o(i,H(D()),n,t,r);if(X(a,(function(e){if("option"!==e)throw K(e);ee(a,e),B(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+i);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);U||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=D();if(!E.test(r))throw K(r,"name");var n=f.lcFirst(r);r===n&&(r=f.ucFirst(r));B("=");var i=H(D()),a=new s(r);a.group=!0;var c=new o(n,i,r,t);c.filename=I.filename,X(a,(function(e){switch(e){case"option":ee(a,e),B(";");break;case"required":case"repeated":J(a,e);break;case"optional":J(a,U?"proto3_optional":"optional");break;case"message":$(a,e);break;case"enum":Z(a,e);break;default:throw K(e)}})),e.add(a).add(c)}(e,t)}function Z(e,t){if(!E.test(t=D()))throw K(t,"name");var r=new l(t);X(r,(function(e){switch(e){case"option":ee(r,e),B(";");break;case"reserved":q(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw K(t,"name");B("=");var r=H(D(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(n,(function(e){if("option"!==e)throw K(e);ee(n,e),B(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=B("(",!0);if(!S.test(t=D()))throw K(t,"name");var n,i=t,s=i;r&&(B(")"),s=i="("+i+")",t=O(),_.test(t)&&(n=t.slice(1),i+=t,D())),B("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,s,te(e,i),n)}function te(e,t){if(B("{",!0)){for(var r={};!B("}",!0);){if(!E.test(k=D()))throw K(k,"name");var n,i=k;if(B(":",!0),"{"===O())n=te(e,t+"."+k);else if("["===O()){var s;if(n=[],B("[",!0)){do{s=z(!0),n.push(s)}while(B(",",!0));B("]"),"undefined"!==typeof s&&re(e,t+"."+k,s)}}else n=z(!0),re(e,t+"."+k,n);var o=r[i];o&&(n=[].concat(o).concat(n)),r[i]=n,B(",",!0),B(";",!0)}return r}var a=z(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(B("[",!0)){do{ee(e,"option")}while(B(",",!0));B("]")}return e}for(;null!==(k=D());)switch(k){case"package":if(!M)throw K(k);G();break;case"import":if(!M)throw K(k);W();break;case"syntax":if(!M)throw K(k);Q();break;case"option":ee(F,k),B(";");break;default:if(Y(F,k)){M=!1;continue}throw K(k)}return I.filename=null,{package:A,imports:C,weakImports:T,syntax:R,root:t}}},6216:(e,t,r)=>{"use strict";e.exports=c;var n,i=r(3097),s=i.LongBits,o=i.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l="undefined"!==typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},u=function(){return i.Buffer?function(e){return(c.create=function(e){return i.Buffer.isBuffer(e)?new n(e):l(e)})(e)}:l};function h(){var e=new s(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new s(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}c.create=u(),c.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return e}}(),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return d(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|d(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?new this.buf.constructor(0):this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length)},c.prototype.skip=function(e){if("number"===typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!==(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=u(),n._configure();var t=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return h.call(this)[t](!1)},uint64:function(){return h.call(this)[t](!0)},sint64:function(){return h.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},3557:(e,t,r)=>{"use strict";e.exports=s;var n=r(6216);(s.prototype=Object.create(n.prototype)).constructor=s;var i=r(3097);function s(e){n.call(this,e)}s._configure=function(){i.Buffer&&(s.prototype._slice=i.Buffer.prototype.slice)},s.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},s._configure()},8622:(e,t,r)=>{"use strict";e.exports=h;var n=r(3452);((h.prototype=Object.create(n.prototype)).constructor=h).className="Root";var i,s,o,a=r(6734),c=r(222),l=r(9794),u=r(2440);function h(e){n.call(this,"",e),this.deferred=[],this.files=[]}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"===typeof r&&(n=r,r=void 0);var i=this;if(!n)return u.asPromise(e,i,t,r);var a=n===d;function c(e,t){if(n){var r=n;if(n=null,a)throw e;r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in o)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){s.filename=e;var n,o=s(t,i,r),h=0;if(o.imports)for(;h-1))if(i.files.push(e),e in o)a?h(e,o[e]):(++p,setTimeout((function(){--p,h(e,o[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(s){return void(t||c(s))}h(e,r)}else++p,i.fetch(e,(function(r,s){--p,n&&(r?t?p||c(null,i):c(r):h(e,s))}))}var p=0;u.isString(t)&&(t=[t]);for(var g,y=0;y-1&&this.deferred.splice(t,1)}}else if(e instanceof c)f.test(e.name)&&delete e.parent[e.name];else if(e instanceof n){for(var r=0;r{"use strict";e.exports={}},9994:(e,t,r)=>{"use strict";t.Service=r(4281)},4281:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e,t,r){if("function"!==typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function e(t,r,i,s,o){if(!s)throw TypeError("request must be specified");var a=this;if(!o)return n.asPromise(e,a,t,r,i,s);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](s).finish(),(function(e,r){if(e)return a.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof i))try{r=i[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),o(e)}return a.emit("data",r,t),o(null,r)}a.end(!0)}))}catch(c){return a.emit("error",c,t),void setTimeout((function(){o(c)}),0)}else setTimeout((function(){o(Error("already ended"))}),0)},i.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},4173:(e,t,r)=>{"use strict";e.exports=a;var n=r(3452);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var i=r(4865),s=r(2440),o=r(9994);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),s=0;s{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,i=/^ *[*/]+ */,s=/^\s*\*?\/*/,o=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,f=0,p={},g=[],y=null;function m(e){return Error("illegal "+e+" (line "+d+")")}function v(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(o),g=0;g0)return g.shift();if(y)return function(){var t="'"===y?n:r;t.lastIndex=l-1;var i=t.exec(e);if(!i)throw m("string");return l=t.lastIndex,_(y),y=null,u(i[1])}();var i,s,o,f,p,S=0===l;do{if(l===h)return null;for(i=!1;a.test(o=v(l));)if("\n"===o&&(S=!0,++d),++l===h)return null;if("/"===v(l)){if(++l===h)throw m("comment");if("/"===v(l))if(c){if(f=l,p=!1,b(l)){p=!0;do{if((l=E(l))===h)break;if(l++,!S)break}while(b(l))}else l=Math.min(h,E(l)+1);p&&(w(f,l,S),S=!0),d++,i=!0}else{for(p="/"===v(f=l+1);"\n"!==v(++l);)if(l===h)return null;++l,p&&(w(f,l-1,S),S=!0),++d,i=!0}else{if("*"!==(o=v(l)))return"/";f=l+1,p=c||"*"===v(f);do{if("\n"===o&&++d,++l===h)throw m("comment");s=o,o=v(l)}while("*"!==s||"/"!==o);++l,p&&(w(f,l-2,S),S=!0),i=!0}}}while(i);var I=l;if(t.lastIndex=0,!t.test(v(I++)))for(;I{"use strict";e.exports=v;var n=r(3452);((v.prototype=Object.create(n.prototype)).constructor=v).className="Type";var i=r(222),s=r(9794),o=r(6734),a=r(4479),c=r(4173),l=r(4486),u=r(6216),h=r(7063),d=r(2440),f=r(6886),p=r(2715),g=r(709),y=r(7276),m=r(9025);function v(e,t){n.call(this,e,t),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function w(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(v.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t{"use strict";var n=t,i=r(2440),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function o(e,t){var r=0,n={};for(t|=0;r{"use strict";var n,i,s=e.exports=r(3097),o=r(7907);s.codegen=r(3297),s.fetch=r(7635),s.path=r(7468),s.fs=s.inquire("fs"),s.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n0)t[i]=e(t[i]||{},r,n);else{var s=t[i];s&&(n=[].concat(s).concat(n)),t[i]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(s,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(r(8622)))}})},9351:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var s=i.zero=new i(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var o=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(e){if(0===e)return s;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new i(r,n)},i.from=function(e){if("number"===typeof e)return i.fromNumber(e);if(n.isString(e)){if(!n.Long)return i.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):s},i.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;i.fromHash=function(e){return e===o?s:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},3097:function(e,t,r){"use strict";var n=t;function i(e,t,r){for(var n=Object.keys(t),i=0;ie,set:void 0,enumerable:!1,configurable:!0},toString:{value(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}n.asPromise=r(7206),n.base64=r(1),n.EventEmitter=r(7111),n.float=r(802),n.inquire=r(7172),n.utf8=r(3861),n.pool=r(8236),n.LongBits=r(9351),n.isNode=Boolean("undefined"!==typeof r.g&&r.g&&r.g.process&&r.g.process.versions&&r.g.process.versions.node),n.global=n.isNode&&r.g||"undefined"!==typeof window&&window||"undefined"!==typeof self&&self||this,n.emptyArray=Object.freeze?Object.freeze([]):[],n.emptyObject=Object.freeze?Object.freeze({}):{},n.isInteger=Number.isInteger||function(e){return"number"===typeof e&&isFinite(e)&&Math.floor(e)===e},n.isString=function(e){return"string"===typeof e||e instanceof String},n.isObject=function(e){return e&&"object"===typeof e},n.isset=n.isSet=function(e,t){var r=e[t];return!(null==r||!e.hasOwnProperty(t))&&("object"!==typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"===typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"===typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!==typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=i,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=s,n.ProtocolError=s("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r{"use strict";e.exports=function(e){var t=i.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r=e.oneofsArray,n={};r.length&&t("var p={}");for(var c=0;c{"use strict";var n=t,i=r(4486);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var s=this.lookup(n);s&&(e=s.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof i){var o=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),o["@type"]=n,o}return this.toObject(e,t)}}},7063:(e,t,r)=>{"use strict";e.exports=h;var n,i=r(3097),s=i.LongBits,o=i.base64,a=i.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return i.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function f(e,t,r){t[r]=255&e}function p(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function y(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},p.prototype=Object.create(c.prototype),p.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,s.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=s.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=s.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(f,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(y,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=s.from(e);return this._push(y,4,t.lo)._push(y,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(i.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(i.float.writeDoubleLE,8,e)};var m=i.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(f,1,0);if(i.isString(e)){var r=h.alloc(t=o.length(e));o.decode(e,r,0),e=r}return this.uint32(t)._push(m,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(f,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},2815:(e,t,r)=>{"use strict";e.exports=s;var n=r(7063);(s.prototype=Object.create(n.prototype)).constructor=s;var i=r(3097);function s(){n.call(this)}function o(e,t,r){e.length<40?i.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}s._configure=function(){s.alloc=i._Buffer_allocUnsafe,s.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(s.writeBytesBuffer,t,e),this},s.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},s._configure()},4463:(e,t,r)=>{"use strict";var n=r(2791),i=r(5296);function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r
= it.Source | (() => it.Source) | it.Duplex\nexport type Transform = it.Transform | it.Duplex\nexport type Sink = it.Sink | it.Duplex\n\nexport function pipe (\n first: Source\n): it.Source\n\nexport function pipe (\n first: Source,\n second: Sink\n): B\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Sink\n): C\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Sink\n): D\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Sink\n): E\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Sink\n): F\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Sink\n): G\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Sink\n): H\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Sink\n): I\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Transform,\n tenth: Sink\n): J\n\nexport function pipe (first: any, ...rest: any[]): any {\n // Duplex at start: wrap in function and return duplex source\n if (isDuplex(first)) {\n const duplex = first\n first = () => duplex.source\n // Iterable at start: wrap in function\n } else if (isIterable(first)) {\n const source = first\n first = () => source\n }\n\n const fns = [first, ...rest]\n\n if (fns.length > 1) {\n // Duplex at end: use duplex sink\n if (isDuplex(fns[fns.length - 1])) {\n fns[fns.length - 1] = fns[fns.length - 1].sink\n }\n }\n\n if (fns.length > 2) {\n // Duplex in the middle, consume source with duplex sink and return duplex source\n for (let i = 1; i < fns.length - 1; i++) {\n if (isDuplex(fns[i])) {\n fns[i] = duplexPipelineFn(fns[i])\n }\n }\n }\n\n return rawPipe(...fns)\n}\n","import { Peer } from \"@libp2p/interface-peer-store\";\nimport { Libp2p } from \"libp2p\";\n\n/**\n * Returns a pseudo-random peer that supports the given protocol.\n * Useful for protocols such as store and light push\n */\nexport async function selectRandomPeer(\n peers: Peer[]\n): Promise {\n if (peers.length === 0) return;\n\n const index = Math.round(Math.random() * (peers.length - 1));\n return peers[index];\n}\n\n/**\n * Returns the list of peers that supports the given protocol.\n */\nexport async function getPeersForProtocol(\n libp2p: Libp2p,\n protocols: string[]\n): Promise {\n const peers: Peer[] = [];\n await libp2p.peerStore.forEach((peer) => {\n for (let i = 0; i < protocols.length; i++) {\n if (peer.protocols.includes(protocols[i])) {\n peers.push(peer);\n break;\n }\n }\n });\n return peers;\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport default function accessor (buf: Uint8Array | Uint8ArrayList) {\n if (buf instanceof Uint8Array) {\n return {\n get (index: number) {\n return buf[index]\n },\n\n set (index: number, value: number) {\n buf[index] = value\n }\n }\n }\n\n return {\n get (index: number) {\n return buf.get(index)\n },\n\n set (index: number, value: number) {\n buf.set(index, value)\n }\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\n\nconst TWO_32 = 4294967296\n\nexport class LongBits {\n public hi: number\n public lo: number\n\n constructor (hi: number = 0, lo: number = 0) {\n this.hi = hi\n this.lo = lo\n }\n\n toBigInt (unsigned: boolean): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n zzDecode () {\n const mask = -(this.lo & 1)\n const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n const hi = (this.hi >>> 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n zzEncode () {\n const mask = this.hi >> 31\n const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n const lo = (this.lo << 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n toBytes (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n const access = accessor(buf)\n\n while (this.hi > 0) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0\n this.hi >>>= 7\n }\n\n while (this.lo > 127) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = this.lo >>> 7\n }\n\n access.set(offset++, this.lo)\n }\n\n static fromBigInt (value: bigint) {\n if (value === 0n) {\n return new LongBits()\n }\n\n const negative = value < 0\n\n if (negative) {\n value = -value\n }\n\n let hi = Number(value >> 32n) | 0\n let lo = Number(value - (BigInt(hi) << 32n)) | 0\n\n if (negative) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > TWO_32) {\n lo = 0\n\n if (++hi > TWO_32) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n static fromNumber (value: number) {\n if (value === 0) {\n return new LongBits()\n }\n\n const sign = value < 0\n\n if (sign) {\n value = -value\n }\n\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > 4294967295) {\n lo = 0\n\n if (++hi > 4294967295) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n static fromBytes (buf: Uint8ArrayList | Uint8Array, offset: number) {\n const access = accessor(buf)\n\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits()\n let i = 0\n\n if (buf.length - offset > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0\n bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0\n if (access.get(offset++) < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 1st..3th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (access.get(offset++) & 127) << i * 7) >>> 0\n return bits\n }\n if (buf.length - offset > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n /* istanbul ignore next */\n throw Error('invalid varint encoding')\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\nimport { LongBits } from './long-bits.js'\n\nconst MSB = 0x80\nconst REST = 0x7F\nconst MSBALL = ~REST\nconst INT = Math.pow(2, 31)\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\nexport const unsigned = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array) {\n let offset = 0\n const access = accessor(buf)\n\n while (value >= INT) {\n access.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n\n while ((value & MSBALL) > 0) {\n access.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n\n access.set(offset, value | 0)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0) {\n const access = accessor(buf)\n let value = 4294967295 // optimizer type-hint, tends to deopt otherwise (?!)\n\n value = (access.get(offset) & 127) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 14) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 21) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 15) << 28) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n if ((offset += 5) > buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n return value\n }\n}\n\nexport const signed = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array) {\n if (value < 0) {\n let offset = 0\n const access = accessor(buf)\n const bits = LongBits.fromNumber(value)\n\n while (bits.hi > 0) {\n access.set(offset++, bits.lo & 127 | 128)\n bits.lo = (bits.lo >>> 7 | bits.hi << 25) >>> 0\n bits.hi >>>= 7\n }\n\n while (bits.lo > 127) {\n access.set(offset++, bits.lo & 127 | 128)\n bits.lo = bits.lo >>> 7\n }\n\n access.set(offset++, bits.lo)\n\n return\n }\n\n unsigned.encode(value, buf)\n },\n\n decode (data: Uint8ArrayList | Uint8Array, offset = 0) {\n return unsigned.decode(data, offset) | 0\n }\n}\n\nexport const zigzag = {\n encodingLength (value: number): number {\n value = (value << 1 ^ value >> 31) >>> 0\n return unsigned.encodingLength(value)\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n value = (value << 1 ^ value >> 31) >>> 0\n return unsigned.encode(value, buf)\n },\n\n decode (data: Uint8ArrayList | Uint8Array, offset = 0) {\n const value = unsigned.decode(data, offset)\n return value >>> 1 ^ -(value & 1) | 0\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from './utils/varint.js'\nimport type { Codec } from './codec.js'\n\nexport function decodeMessage (buf: Uint8Array, codec: Codec) {\n // wrap root message\n const prefix = new Uint8Array(unsigned.encodingLength(buf.length))\n unsigned.encode(buf.length, prefix)\n\n return codec.decode(new Uint8ArrayList(prefix, buf), 0)\n}\n","import type { Codec } from './codec.js'\nimport { unsigned } from './utils/varint.js'\n\nexport function encodeMessage (message: T, codec: Codec) {\n // unwrap root message\n const encoded = codec.encode(message)\n const skip = unsigned.encodingLength(unsigned.decode(encoded))\n\n return encoded.slice(skip)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeFunction {\n (value: T): Uint8Array | Uint8ArrayList\n}\n\nexport interface DecodeFunction {\n (buf: Uint8ArrayList, offset: number): T\n}\n\nexport interface EncodingLengthFunction {\n (value: T): number\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n encodingLength: EncodingLengthFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction, encodingLength: EncodingLengthFunction): Codec {\n return {\n name,\n type,\n encode,\n decode,\n encodingLength\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function boolEncodingLength () {\n return 1\n}\n\nconst encode: EncodeFunction = function boolEncode (value) {\n return Uint8Array.from([value ? 1 : 0])\n}\n\nconst decode: DecodeFunction = function boolDecode (buffer, offset) {\n return buffer.get(offset) > 0\n}\n\nexport const bool = createCodec('bool', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function bytesEncodingLength (val) {\n const len = val.byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function bytesEncode (val) {\n const prefix = new Uint8Array(unsigned.encodingLength(val.byteLength))\n\n unsigned.encode(val.byteLength, prefix)\n\n return new Uint8ArrayList(prefix, val)\n}\n\nconst decode: DecodeFunction = function bytesDecode (buf, offset) {\n const byteLength = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(byteLength)\n\n return buf.slice(offset, offset + byteLength)\n}\n\nexport const bytes = createCodec('bytes', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function doubleEncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function doubleEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setFloat64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function doubleDecode (buf, offset) {\n return buf.getFloat64(offset, true)\n}\n\nexport const double = createCodec('double', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","\nimport { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction, Codec } from '../codec.js'\n\nexport function enumeration (v: any): Codec {\n function findValue (val: string | number): number {\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n if (typeof val === 'number') {\n return val\n }\n\n return v[val]\n }\n\n const encodingLength: EncodingLengthFunction = function enumEncodingLength (val) {\n return unsigned.encodingLength(findValue(val))\n }\n\n const encode: EncodeFunction = function enumEncode (val) {\n const enumValue = findValue(val)\n\n const buf = new Uint8Array(unsigned.encodingLength(enumValue))\n unsigned.encode(enumValue, buf)\n\n return buf\n }\n\n const decode: DecodeFunction = function enumDecode (buf, offset) {\n const value = unsigned.decode(buf, offset)\n const strValue = value.toString()\n\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[strValue] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[strValue]\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function fixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function fixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function fixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const fixed32 = createCodec('fixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return 8\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const fixed64 = createCodec('fixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function floatEncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function floatEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(1)))\n buf.setFloat32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function floatDecode (buf, offset) {\n return buf.getFloat32(offset, true)\n}\n\nexport const float = createCodec('float', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { signed } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int32EncodingLength (val) {\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int32Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n signed.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int32Decode (buf, offset) {\n return signed.decode(buf, offset)\n}\n\nexport const int32 = createCodec('int32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\nimport { LongBits } from './long-bits.js'\n\nconst LIMIT = 0x7fn\n\n// https://github.com/joeltg/big-varint/blob/main/src/unsigned.ts\nexport const unsigned = {\n encodingLength (value: bigint): number {\n let i = 0\n for (; value >= 0x80n; i++) {\n value >>= 7n\n }\n return i + 1\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array) {\n const access = accessor(buf)\n\n let offset = 0\n while (LIMIT < value) {\n access.set(offset++, Number(value & LIMIT) | 0x80)\n value >>= 7n\n }\n\n access.set(offset, Number(value))\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(true)\n }\n}\n\nexport const signed = {\n encodingLength (value: bigint): number {\n if (value < 0n) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n if (value < 0n) {\n LongBits.fromBigInt(value).toBytes(buf, offset)\n\n return\n }\n\n return unsigned.encode(value, buf)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(false)\n }\n}\n\nexport const zigzag = {\n encodingLength (value: bigint): number {\n return unsigned.encodingLength(value >= 0 ? value * 2n : value * -2n - 1n)\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n LongBits.fromBigInt(value).zzEncode().toBytes(buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).zzDecode().toBigInt(false)\n }\n}\n","import { signed } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n signed.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return signed.decode(buf, offset) | 0n\n}\n\nexport const int64 = createCodec('int64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction, Codec } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { FieldDefs, FieldDef } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (fieldDefs: FieldDefs): Codec {\n const encodingLength: EncodingLengthFunction = function messageEncodingLength (val: Record) {\n let length = 0\n\n for (const fieldDef of Object.values(fieldDefs)) {\n length += fieldDef.codec.encodingLength(val[fieldDef.name])\n }\n\n return unsigned.encodingLength(length) + length\n }\n\n const encode: EncodeFunction> = function messageEncode (val) {\n const bytes = new Uint8ArrayList()\n\n function encodeValue (value: any, fieldNumber: number, fieldDef: FieldDef) {\n if (value == null) {\n if (fieldDef.optional === true) {\n return\n }\n\n throw new Error(`Non optional field \"${fieldDef.name}\" was ${value === null ? 'null' : 'undefined'}`)\n }\n\n const key = (fieldNumber << 3) | fieldDef.codec.type\n const prefix = new Uint8Array(unsigned.encodingLength(key))\n unsigned.encode(key, prefix)\n const encoded = fieldDef.codec.encode(value)\n\n bytes.append(prefix)\n bytes.append(encoded)\n }\n\n for (const [fieldNumberStr, fieldDef] of Object.entries(fieldDefs)) {\n const fieldNumber = parseInt(fieldNumberStr)\n\n if (fieldDef.repeats === true) {\n if (!Array.isArray(val[fieldDef.name])) {\n throw new Error(`Repeating field \"${fieldDef.name}\" was not an array`)\n }\n\n for (const value of val[fieldDef.name]) {\n encodeValue(value, fieldNumber, fieldDef)\n }\n } else {\n encodeValue(val[fieldDef.name], fieldNumber, fieldDef)\n }\n }\n\n const prefix = new Uint8Array(unsigned.encodingLength(bytes.length))\n unsigned.encode(bytes.length, prefix)\n\n return new Uint8ArrayList(prefix, bytes)\n }\n\n const decode: DecodeFunction = function messageDecode (buffer, offset) {\n const length = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(length)\n const end = offset + length\n const fields: any = {}\n\n while (offset < end) {\n const key = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(key)\n\n const wireType = key & 0x7\n const fieldNumber = key >> 3\n const fieldDef = fieldDefs[fieldNumber]\n let fieldLength = 0\n\n if (wireType === CODEC_TYPES.VARINT) {\n if (fieldDef != null) {\n // use the codec if it is available as this could be a bigint\n const value = fieldDef.codec.decode(buffer, offset)\n fieldLength = fieldDef.codec.encodingLength(value)\n } else {\n const value = unsigned.decode(buffer, offset)\n fieldLength = unsigned.encodingLength(value)\n }\n } else if (wireType === CODEC_TYPES.BIT64) {\n fieldLength = 8\n } else if (wireType === CODEC_TYPES.LENGTH_DELIMITED) {\n const valueLength = unsigned.decode(buffer, offset)\n fieldLength = valueLength + unsigned.encodingLength(valueLength)\n } else if (wireType === CODEC_TYPES.BIT32) {\n fieldLength = 4\n } else if (wireType === CODEC_TYPES.START_GROUP) {\n throw new Error('Unsupported wire type START_GROUP')\n } else if (wireType === CODEC_TYPES.END_GROUP) {\n throw new Error('Unsupported wire type END_GROUP')\n }\n\n if (fieldDef != null) {\n const value = fieldDef.codec.decode(buffer, offset)\n\n if (fieldDef.repeats === true) {\n if (fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n\n fields[fieldDef.name].push(value)\n } else {\n fields[fieldDef.name] = value\n }\n }\n\n offset += fieldLength\n }\n\n // make sure repeated fields have an array if not set\n for (const fieldDef of Object.values(fieldDefs)) {\n if (fieldDef.repeats === true && fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n }\n\n return fields\n }\n\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function sfixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const sfixed32 = createCodec('sfixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed64EncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function sfixed64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const sfixed64 = createCodec('sfixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { zigzag } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sint32EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function svarintEncode (val) {\n const buf = new Uint8Array(encodingLength(val))\n\n zigzag.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function svarintDecode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint32 = createCodec('sint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { zigzag } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n zigzag.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint64 = createCodec('sint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\n\nconst encodingLength: EncodingLengthFunction = function stringEncodingLength (val) {\n const len = uint8ArrayFromString(val).byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function stringEncode (val) {\n const asBuf = uint8ArrayFromString(val)\n const prefix = new Uint8Array(unsigned.encodingLength(asBuf.byteLength))\n\n unsigned.encode(asBuf.length, prefix)\n\n return new Uint8ArrayList(prefix, asBuf)\n}\n\nconst decode: DecodeFunction = function stringDecode (buf, offset) {\n const strLen = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(strLen)\n\n return uint8ArrayToString(buf.slice(offset, offset + strLen))\n}\n\nexport const string = createCodec('string', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint32EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint32Encode (val) {\n // val = val < 0 ? val + 4294967296 : val\n\n const buf = new Uint8Array(encodingLength(val))\n\n unsigned.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function uint32Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n\n // return value > 2147483647 ? value - 4294967296 : value\n}\n\nexport const uint32 = createCodec('uint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint64EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint64Encode (val) {\n const buf = new Uint8Array(unsigned.encodingLength(val))\n\n unsigned.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function uint64Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n}\n\nexport const uint64 = createCodec('uint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n bytes,\n string,\n uint32,\n double,\n sint64,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","import * as secp from \"@noble/secp256k1\";\n\nimport { getSubtle, randomBytes, sha256 } from \"../crypto\";\nimport { concat, hexToBytes } from \"../utils\";\n/**\n * HKDF as implemented in go-ethereum.\n */\nfunction kdf(secret: Uint8Array, outputLength: number): Promise {\n let ctr = 1;\n let written = 0;\n let willBeResult = Promise.resolve(new Uint8Array());\n while (written < outputLength) {\n const counters = new Uint8Array([ctr >> 24, ctr >> 16, ctr >> 8, ctr]);\n const countersSecret = concat(\n [counters, secret],\n counters.length + secret.length\n );\n const willBeHashResult = sha256(countersSecret);\n willBeResult = willBeResult.then((result) =>\n willBeHashResult.then((hashResult) => {\n const _hashResult = new Uint8Array(hashResult);\n return concat(\n [result, _hashResult],\n result.length + _hashResult.length\n );\n })\n );\n written += 32;\n ctr += 1;\n }\n return willBeResult;\n}\n\nfunction aesCtrEncrypt(\n counter: Uint8Array,\n key: ArrayBufferLike,\n data: ArrayBufferLike\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, \"AES-CTR\", false, [\"encrypt\"])\n .then((cryptoKey) =>\n getSubtle().encrypt(\n { name: \"AES-CTR\", counter: counter, length: 128 },\n cryptoKey,\n data\n )\n )\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction aesCtrDecrypt(\n counter: Uint8Array,\n key: ArrayBufferLike,\n data: ArrayBufferLike\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, \"AES-CTR\", false, [\"decrypt\"])\n .then((cryptoKey) =>\n getSubtle().decrypt(\n { name: \"AES-CTR\", counter: counter, length: 128 },\n cryptoKey,\n data\n )\n )\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction hmacSha256Sign(\n key: ArrayBufferLike,\n msg: ArrayBufferLike\n): PromiseLike {\n const algorithm = { name: \"HMAC\", hash: { name: \"SHA-256\" } };\n return getSubtle()\n .importKey(\"raw\", key, algorithm, false, [\"sign\"])\n .then((cryptoKey) => getSubtle().sign(algorithm, cryptoKey, msg))\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction hmacSha256Verify(\n key: ArrayBufferLike,\n msg: ArrayBufferLike,\n sig: ArrayBufferLike\n): Promise {\n const algorithm = { name: \"HMAC\", hash: { name: \"SHA-256\" } };\n const _key = getSubtle().importKey(\"raw\", key, algorithm, false, [\"verify\"]);\n return _key.then((cryptoKey) =>\n getSubtle().verify(algorithm, cryptoKey, sig, msg)\n );\n}\n\n/**\n * Derive shared secret for given private and public keys.\n *\n * @param privateKeyA Sender's private key (32 bytes)\n * @param publicKeyB Recipient's public key (65 bytes)\n * @returns A promise that resolves with the derived shared secret (Px, 32 bytes)\n * @throws Error If arguments are invalid\n */\nfunction derive(privateKeyA: Uint8Array, publicKeyB: Uint8Array): Uint8Array {\n if (privateKeyA.length !== 32) {\n throw new Error(\n `Bad private key, it should be 32 bytes but it's actually ${privateKeyA.length} bytes long`\n );\n } else if (publicKeyB.length !== 65) {\n throw new Error(\n `Bad public key, it should be 65 bytes but it's actually ${publicKeyB.length} bytes long`\n );\n } else if (publicKeyB[0] !== 4) {\n throw new Error(\"Bad public key, a valid public key would begin with 4\");\n } else {\n const px = secp.getSharedSecret(privateKeyA, publicKeyB, true);\n // Remove the compression prefix\n return new Uint8Array(hexToBytes(px).slice(1));\n }\n}\n\n/**\n * Encrypt message for given recipient's public key.\n *\n * @param publicKeyTo Recipient's public key (65 bytes)\n * @param msg The message being encrypted\n * @return A promise that resolves with the ECIES structure serialized\n */\nexport async function encrypt(\n publicKeyTo: Uint8Array,\n msg: Uint8Array\n): Promise {\n const ephemPrivateKey = randomBytes(32);\n\n const sharedPx = await derive(ephemPrivateKey, publicKeyTo);\n\n const hash = await kdf(sharedPx, 32);\n\n const iv = randomBytes(16);\n const encryptionKey = hash.slice(0, 16);\n const cipherText = await aesCtrEncrypt(iv, encryptionKey, msg);\n\n const ivCipherText = concat([iv, cipherText], iv.length + cipherText.length);\n\n const macKey = await sha256(hash.slice(16));\n const hmac = await hmacSha256Sign(macKey, ivCipherText);\n const ephemPublicKey = secp.getPublicKey(ephemPrivateKey, false);\n\n return concat(\n [ephemPublicKey, ivCipherText, hmac],\n ephemPublicKey.length + ivCipherText.length + hmac.length\n );\n}\n\nconst metaLength = 1 + 64 + 16 + 32;\n\n/**\n * Decrypt message using given private key.\n *\n * @param privateKey A 32-byte private key of recipient of the message\n * @param encrypted ECIES serialized structure (result of ECIES encryption)\n * @returns The clear text\n * @throws Error If decryption fails\n */\nexport async function decrypt(\n privateKey: Uint8Array,\n encrypted: Uint8Array\n): Promise {\n if (encrypted.length <= metaLength) {\n throw new Error(\n `Invalid Ciphertext. Data is too small. It should ba at least ${metaLength} bytes`\n );\n } else if (encrypted[0] !== 4) {\n throw new Error(\n `Not a valid ciphertext. It should begin with 4 but actually begin with ${encrypted[0]}`\n );\n } else {\n // deserialize\n const ephemPublicKey = encrypted.slice(0, 65);\n const cipherTextLength = encrypted.length - metaLength;\n const iv = encrypted.slice(65, 65 + 16);\n const cipherAndIv = encrypted.slice(65, 65 + 16 + cipherTextLength);\n const ciphertext = cipherAndIv.slice(16);\n const msgMac = encrypted.slice(65 + 16 + cipherTextLength);\n\n // check HMAC\n const px = derive(privateKey, ephemPublicKey);\n const hash = await kdf(px, 32);\n const [encryptionKey, macKey] = await sha256(hash.slice(16)).then(\n (macKey) => [hash.slice(0, 16), macKey]\n );\n\n if (!(await hmacSha256Verify(macKey, cipherAndIv, msgMac))) {\n throw new Error(\"Incorrect MAC\");\n }\n\n return aesCtrDecrypt(iv, encryptionKey, ciphertext);\n }\n}\n","import * as secp from \"@noble/secp256k1\";\n\nimport { keccak256, randomBytes, sign } from \"../crypto\";\nimport { concat, hexToBytes } from \"../utils\";\n\nimport { Symmetric } from \"./constants\";\nimport * as ecies from \"./ecies\";\nimport * as symmetric from \"./symmetric\";\n\nconst FlagsLength = 1;\nconst FlagMask = 3; // 0011\nconst IsSignedMask = 4; // 0100\nconst PaddingTarget = 256;\nconst SignatureLength = 65;\n\nexport type Signature = {\n signature: Uint8Array;\n publicKey: Uint8Array | undefined;\n};\n\n/**\n * Encode the payload pre-encryption.\n *\n * @internal\n * @param messagePayload: The payload to include in the message\n * @param sigPrivKey: If set, a signature using this private key is added.\n * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}\n * or {@link encryptSymmetric}.\n */\nexport async function clearEncode(\n messagePayload: Uint8Array,\n sigPrivKey?: Uint8Array\n): Promise<{ payload: Uint8Array; sig?: Signature }> {\n let envelope = new Uint8Array([0]); // No flags\n envelope = addPayloadSizeField(envelope, messagePayload);\n envelope = concat([envelope, messagePayload]);\n\n // Calculate padding:\n let rawSize =\n FlagsLength +\n computeSizeOfPayloadSizeField(messagePayload) +\n messagePayload.length;\n\n if (sigPrivKey) {\n rawSize += SignatureLength;\n }\n\n const remainder = rawSize % PaddingTarget;\n const paddingSize = PaddingTarget - remainder;\n const pad = randomBytes(paddingSize);\n\n if (!validateDataIntegrity(pad, paddingSize)) {\n throw new Error(\"failed to generate random padding of size \" + paddingSize);\n }\n\n envelope = concat([envelope, pad]);\n let sig;\n if (sigPrivKey) {\n envelope[0] |= IsSignedMask;\n const hash = keccak256(envelope);\n const bytesSignature = await sign(hash, sigPrivKey);\n envelope = concat([envelope, bytesSignature]);\n sig = {\n signature: bytesSignature,\n publicKey: secp.getPublicKey(sigPrivKey, false),\n };\n }\n\n return { payload: envelope, sig };\n}\n\n/**\n * Decode a decrypted payload.\n *\n * @internal\n */\nexport function clearDecode(\n message: Uint8Array\n): { payload: Uint8Array; sig?: Signature } | undefined {\n const sizeOfPayloadSizeField = getSizeOfPayloadSizeField(message);\n if (sizeOfPayloadSizeField === 0) return;\n\n const payloadSize = getPayloadSize(message, sizeOfPayloadSizeField);\n const payloadStart = 1 + sizeOfPayloadSizeField;\n const payload = message.slice(payloadStart, payloadStart + payloadSize);\n\n const isSigned = isMessageSigned(message);\n\n let sig;\n if (isSigned) {\n const signature = getSignature(message);\n const hash = getHash(message, isSigned);\n const publicKey = ecRecoverPubKey(hash, signature);\n sig = { signature, publicKey };\n }\n\n return { payload, sig };\n}\n\nfunction getSizeOfPayloadSizeField(message: Uint8Array): number {\n const messageDataView = new DataView(message.buffer);\n return messageDataView.getUint8(0) & FlagMask;\n}\n\nfunction getPayloadSize(\n message: Uint8Array,\n sizeOfPayloadSizeField: number\n): number {\n let payloadSizeBytes = message.slice(1, 1 + sizeOfPayloadSizeField);\n // int 32 == 4 bytes\n if (sizeOfPayloadSizeField < 4) {\n // If less than 4 bytes pad right (Little Endian).\n payloadSizeBytes = concat(\n [payloadSizeBytes, new Uint8Array(4 - sizeOfPayloadSizeField)],\n 4\n );\n }\n const payloadSizeDataView = new DataView(payloadSizeBytes.buffer);\n return payloadSizeDataView.getInt32(0, true);\n}\n\nfunction isMessageSigned(message: Uint8Array): boolean {\n const messageDataView = new DataView(message.buffer);\n return (messageDataView.getUint8(0) & IsSignedMask) == IsSignedMask;\n}\n\n/**\n * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n * The data MUST be flags | payload-length | payload | [signature].\n * The returned result can be set to `WakuMessage.payload`.\n *\n * @internal\n */\nexport async function encryptAsymmetric(\n data: Uint8Array,\n publicKey: Uint8Array | string\n): Promise {\n return ecies.encrypt(hexToBytes(publicKey), data);\n}\n\n/**\n * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n * The returned data is expected to be `flags | payload-length | payload | [signature]`.\n *\n * @internal\n */\nexport async function decryptAsymmetric(\n payload: Uint8Array,\n privKey: Uint8Array\n): Promise {\n return ecies.decrypt(privKey, payload);\n}\n\n/**\n * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n *\n * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.\n * @param key The key to use for encryption.\n * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.\n *\n * @internal\n */\nexport async function encryptSymmetric(\n data: Uint8Array,\n key: Uint8Array | string\n): Promise {\n const iv = symmetric.generateIv();\n\n // Returns `cipher | tag`\n const cipher = await symmetric.encrypt(iv, hexToBytes(key), data);\n return concat([cipher, iv]);\n}\n\n/**\n * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n *\n * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.\n * @param key The key to use for decryption.\n * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.\n *\n * @internal\n */\nexport async function decryptSymmetric(\n payload: Uint8Array,\n key: Uint8Array | string\n): Promise {\n const ivStart = payload.length - Symmetric.ivSize;\n const cipher = payload.slice(0, ivStart);\n const iv = payload.slice(ivStart);\n\n return symmetric.decrypt(iv, hexToBytes(key), cipher);\n}\n\n/**\n * Computes the flags & auxiliary-field as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n */\nfunction addPayloadSizeField(msg: Uint8Array, payload: Uint8Array): Uint8Array {\n const fieldSize = computeSizeOfPayloadSizeField(payload);\n let field = new Uint8Array(4);\n const fieldDataView = new DataView(field.buffer);\n fieldDataView.setUint32(0, payload.length, true);\n field = field.slice(0, fieldSize);\n msg = concat([msg, field]);\n msg[0] |= fieldSize;\n return msg;\n}\n\n/**\n * Returns the size of the auxiliary-field which in turns contains the payload size\n */\nfunction computeSizeOfPayloadSizeField(payload: Uint8Array): number {\n let s = 1;\n for (let i = payload.length; i >= 256; i /= 256) {\n s++;\n }\n return s;\n}\n\nfunction validateDataIntegrity(\n value: Uint8Array,\n expectedSize: number\n): boolean {\n if (value.length !== expectedSize) {\n return false;\n }\n\n return expectedSize <= 3 || value.findIndex((i) => i !== 0) !== -1;\n}\n\nfunction getSignature(message: Uint8Array): Uint8Array {\n return message.slice(message.length - SignatureLength, message.length);\n}\n\nfunction getHash(message: Uint8Array, isSigned: boolean): Uint8Array {\n if (isSigned) {\n return keccak256(message.slice(0, message.length - SignatureLength));\n }\n return keccak256(message);\n}\n\nfunction ecRecoverPubKey(\n messageHash: Uint8Array,\n signature: Uint8Array\n): Uint8Array | undefined {\n const recoveryDataView = new DataView(signature.slice(64).buffer);\n const recovery = recoveryDataView.getUint8(0);\n const _signature = secp.Signature.fromCompact(signature.slice(0, 64));\n\n return secp.recoverPublicKey(\n messageHash,\n _signature,\n recovery,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: compressed: false\n false\n );\n}\n","import { getSubtle, randomBytes } from \"../crypto\";\n\nimport { Symmetric } from \"./constants\";\n\nexport async function encrypt(\n iv: Uint8Array,\n key: Uint8Array,\n clearText: Uint8Array\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, Symmetric.algorithm, false, [\"encrypt\"])\n .then((cryptoKey) =>\n getSubtle().encrypt({ iv, ...Symmetric.algorithm }, cryptoKey, clearText)\n )\n .then((cipher) => new Uint8Array(cipher));\n}\n\nexport async function decrypt(\n iv: Uint8Array,\n key: Uint8Array,\n cipherText: Uint8Array\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, Symmetric.algorithm, false, [\"decrypt\"])\n .then((cryptoKey) =>\n getSubtle().decrypt({ iv, ...Symmetric.algorithm }, cryptoKey, cipherText)\n )\n .then((clear) => new Uint8Array(clear));\n}\n\nexport function generateIv(): Uint8Array {\n return randomBytes(Symmetric.ivSize);\n}\n","import debug from \"debug\";\n\nimport * as proto from \"../../proto/message\";\nimport { bytesToUtf8, utf8ToBytes } from \"../utils\";\n\nimport * as version_1 from \"./version_1\";\n\nconst DefaultVersion = 0;\nconst dbg = debug(\"waku:message\");\nconst OneMillion = BigInt(1_000_000);\n\nexport enum DecryptionMethod {\n Asymmetric = \"asymmetric\",\n Symmetric = \"symmetric\",\n}\n\nexport interface Options {\n /**\n * Timestamp to set on the message, defaults to now if not passed.\n */\n timestamp?: Date;\n /**\n * Public Key to use to encrypt the messages using ECIES (Asymmetric Encryption).\n *\n * @throws if both `encPublicKey` and `symKey` are passed\n */\n encPublicKey?: Uint8Array | string;\n /**\n * Key to use to encrypt the messages using AES (Symmetric Encryption).\n *\n * @throws if both `encPublicKey` and `symKey` are passed\n */\n symKey?: Uint8Array | string;\n /**\n * Private key to use to sign the message, either `encPublicKey` or `symKey` must be provided as only\n * encrypted messages are signed.\n */\n sigPrivKey?: Uint8Array;\n}\n\n// TODO: Use this in Options\nexport interface DecryptionParams {\n key: Uint8Array;\n method?: DecryptionMethod;\n contentTopics?: string[];\n}\n\nexport class WakuMessage {\n private constructor(\n public proto: proto.WakuMessage,\n private _signaturePublicKey?: Uint8Array,\n private _signature?: Uint8Array\n ) {}\n\n /**\n * Create Message with an utf-8 string as payload.\n */\n static async fromUtf8String(\n utf8: string,\n contentTopic: string,\n opts?: Options\n ): Promise {\n const payload = utf8ToBytes(utf8);\n return WakuMessage.fromBytes(payload, contentTopic, opts);\n }\n\n /**\n * Create a Waku Message with the given payload.\n *\n * By default, the payload is kept clear (version 0).\n * If `opts.encPublicKey` is passed, the payload is encrypted using\n * asymmetric encryption (version 1).\n *\n * If `opts.sigPrivKey` is passed and version 1 is used, the payload is signed\n * before encryption.\n *\n * @throws if both `opts.encPublicKey` and `opt.symKey` are passed\n */\n static async fromBytes(\n payload: Uint8Array,\n contentTopic: string,\n opts?: Options\n ): Promise {\n const { timestamp, encPublicKey, symKey, sigPrivKey } = Object.assign(\n { timestamp: new Date() },\n opts ? opts : {}\n );\n\n let _payload = payload;\n let version = DefaultVersion;\n let sig;\n\n if (encPublicKey && symKey) {\n throw \"Pass either `encPublicKey` or `symKey`, not both.\";\n }\n\n if (encPublicKey) {\n const enc = await version_1.clearEncode(_payload, sigPrivKey);\n _payload = await version_1.encryptAsymmetric(enc.payload, encPublicKey);\n sig = enc.sig;\n version = 1;\n } else if (symKey) {\n const enc = await version_1.clearEncode(_payload, sigPrivKey);\n _payload = await version_1.encryptSymmetric(enc.payload, symKey);\n sig = enc.sig;\n version = 1;\n }\n\n return new WakuMessage(\n {\n payload: _payload,\n timestampDeprecated: timestamp.valueOf() / 1000,\n // milliseconds 10^-3 to nanoseconds 10^-9\n timestamp: BigInt(timestamp.valueOf()) * OneMillion,\n version,\n contentTopic,\n },\n sig?.publicKey,\n sig?.signature\n );\n }\n\n /**\n * Decode a byte array into Waku Message.\n *\n * @params bytes The message encoded using protobuf as defined in [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/).\n * @params decryptionKeys If the payload is encrypted (version = 1), then the\n * keys are used to attempt decryption of the message. The passed key can either\n * be asymmetric private keys or symmetric keys, both method are tried for each\n * key until the message is decrypted or combinations are run out.\n */\n static async decode(\n bytes: Uint8Array,\n decryptionParams?: DecryptionParams[]\n ): Promise {\n const protoBuf = proto.WakuMessage.decode(bytes);\n\n return WakuMessage.decodeProto(protoBuf, decryptionParams);\n }\n\n /**\n * Decode and decrypt Waku Message Protobuf Object into Waku Message.\n *\n * @params protoBuf The message to decode and decrypt.\n * @params decryptionParams If the payload is encrypted (version = 1), then the\n * keys are used to attempt decryption of the message. The passed key can either\n * be asymmetric private keys or symmetric keys, both method are tried for each\n * key until the message is decrypted or combinations are run out.\n */\n static async decodeProto(\n protoBuf: proto.WakuMessage,\n decryptionParams?: DecryptionParams[]\n ): Promise {\n if (protoBuf.payload === undefined) {\n dbg(\"Payload is undefined\");\n return;\n }\n const payload = protoBuf.payload;\n\n let signaturePublicKey;\n let signature;\n if (protoBuf.version === 1 && protoBuf.payload) {\n if (decryptionParams === undefined) {\n dbg(\"Payload is encrypted but no private keys have been provided.\");\n return;\n }\n\n // Returns a bunch of `undefined` and hopefully one decrypted result\n const allResults = await Promise.all(\n decryptionParams.map(async ({ key, method, contentTopics }) => {\n if (\n !contentTopics ||\n (protoBuf.contentTopic &&\n contentTopics.includes(protoBuf.contentTopic))\n ) {\n switch (method) {\n case DecryptionMethod.Asymmetric:\n try {\n return await version_1.decryptAsymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption despite decryption method being specified\",\n e\n );\n return;\n }\n case DecryptionMethod.Symmetric:\n try {\n return await version_1.decryptSymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption despite decryption method being specified\",\n e\n );\n return;\n }\n default:\n try {\n return await version_1.decryptSymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using symmetric encryption\",\n e\n );\n try {\n return await version_1.decryptAsymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption\",\n e\n );\n return;\n }\n }\n }\n } else {\n // No key available for this content topic\n return;\n }\n })\n );\n\n const isDefined = (dec: Uint8Array | undefined): dec is Uint8Array => {\n return !!dec;\n };\n\n const decodedResults = allResults.filter(isDefined);\n\n if (decodedResults.length === 0) {\n dbg(\"Failed to decrypt payload.\");\n return;\n }\n const dec = decodedResults[0];\n\n const res = await version_1.clearDecode(dec);\n if (!res) {\n dbg(\"Failed to decode payload.\");\n return;\n }\n Object.assign(protoBuf, { payload: res.payload });\n signaturePublicKey = res.sig?.publicKey;\n signature = res.sig?.signature;\n }\n\n return new WakuMessage(protoBuf, signaturePublicKey, signature);\n }\n\n encode(): Uint8Array {\n return proto.WakuMessage.encode(this.proto);\n }\n\n get payloadAsUtf8(): string {\n if (!this.payload) {\n return \"\";\n }\n\n try {\n return bytesToUtf8(this.payload);\n } catch (e) {\n dbg(\"Could not decode byte as UTF-8\", e);\n return \"\";\n }\n }\n\n get payload(): Uint8Array | undefined {\n if (this.proto.payload) {\n return new Uint8Array(this.proto.payload);\n }\n return;\n }\n\n get contentTopic(): string | undefined {\n return this.proto.contentTopic;\n }\n\n get version(): number {\n // TODO: absent value should be replaced by default\n // value of the type by the protobuf decoder\n return this.proto.version ?? 0;\n }\n\n get timestamp(): Date | undefined {\n // In the case we receive a value that is bigger than JS's max number,\n // we catch the error and return undefined.\n try {\n if (this.proto.timestamp) {\n // nanoseconds 10^-9 to milliseconds 10^-3\n const timestamp = this.proto.timestamp / OneMillion;\n return new Date(Number(timestamp));\n }\n\n if (this.proto.timestampDeprecated) {\n return new Date(this.proto.timestampDeprecated * 1000);\n }\n } catch (e) {\n return;\n }\n return;\n }\n\n /**\n * The public key used to sign the message.\n *\n * MAY be present if the message is version 1.\n */\n get signaturePublicKey(): Uint8Array | undefined {\n return this._signaturePublicKey;\n }\n\n /**\n * The signature of the message.\n *\n * MAY be present if the message is version 1.\n */\n get signature(): Uint8Array | undefined {\n return this._signature;\n }\n}\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n string,\n bool,\n bytes,\n uint32,\n double,\n sint64,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface FilterRequest {\n subscribe?: boolean;\n topic?: string;\n contentFilters: FilterRequest.ContentFilter[];\n}\n\nexport namespace FilterRequest {\n export interface ContentFilter {\n contentTopic?: string;\n }\n\n export namespace ContentFilter {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"contentTopic\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 1: { name: \"subscribe\", codec: bool, optional: true },\n 2: { name: \"topic\", codec: string, optional: true },\n 3: {\n name: \"contentFilters\",\n codec: FilterRequest.ContentFilter.codec(),\n repeats: true,\n },\n });\n };\n\n export const encode = (obj: FilterRequest): Uint8Array => {\n return encodeMessage(obj, FilterRequest.codec());\n };\n\n export const decode = (buf: Uint8Array): FilterRequest => {\n return decodeMessage(buf, FilterRequest.codec());\n };\n}\n\nexport interface MessagePush {\n messages: WakuMessage[];\n}\n\nexport namespace MessagePush {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"messages\", codec: WakuMessage.codec(), repeats: true },\n });\n };\n\n export const encode = (obj: MessagePush): Uint8Array => {\n return encodeMessage(obj, MessagePush.codec());\n };\n\n export const decode = (buf: Uint8Array): MessagePush => {\n return decodeMessage(buf, MessagePush.codec());\n };\n}\n\nexport interface FilterRPC {\n requestId?: string;\n request?: FilterRequest;\n push?: MessagePush;\n}\n\nexport namespace FilterRPC {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"requestId\", codec: string, optional: true },\n 2: { name: \"request\", codec: FilterRequest.codec(), optional: true },\n 3: { name: \"push\", codec: MessagePush.codec(), optional: true },\n });\n };\n\n export const encode = (obj: FilterRPC): Uint8Array => {\n return encodeMessage(obj, FilterRPC.codec());\n };\n\n export const decode = (buf: Uint8Array): FilterRPC => {\n return decodeMessage(buf, FilterRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","import { v4 as uuid } from \"uuid\";\n\nimport * as proto from \"../../proto/filter\";\n\nexport type ContentFilter = {\n contentTopic: string;\n};\n\n/**\n * FilterRPC represents a message conforming to the Waku Filter protocol\n */\nexport class FilterRPC {\n public constructor(public proto: proto.FilterRPC) {}\n\n static createRequest(\n topic: string,\n contentFilters: ContentFilter[],\n requestId?: string,\n subscribe = true\n ): FilterRPC {\n return new FilterRPC({\n requestId: requestId || uuid(),\n request: {\n subscribe,\n topic,\n contentFilters,\n },\n push: undefined,\n });\n }\n\n /**\n *\n * @param bytes Uint8Array of bytes from a FilterRPC message\n * @returns FilterRPC\n */\n static decode(bytes: Uint8Array): FilterRPC {\n const res = proto.FilterRPC.decode(bytes);\n return new FilterRPC(res);\n }\n\n /**\n * Encode the current FilterRPC request to bytes\n * @returns Uint8Array\n */\n encode(): Uint8Array {\n return proto.FilterRPC.encode(this.proto);\n }\n\n get push(): proto.MessagePush | undefined {\n return this.proto.push;\n }\n\n get requestId(): string | undefined {\n return this.proto.requestId;\n }\n}\n","import type { Stream } from \"@libp2p/interface-connection\";\nimport type { PeerId } from \"@libp2p/interface-peer-id\";\nimport type { Peer } from \"@libp2p/interface-peer-store\";\nimport type { IncomingStreamData } from \"@libp2p/interface-registrar\";\nimport debug from \"debug\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { WakuMessage as WakuMessageProto } from \"../../proto/message\";\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport { ContentFilter, FilterRPC } from \"./filter_rpc\";\nexport { ContentFilter };\n\nexport const FilterCodec = \"/vac/waku/filter/2.0.0-beta1\";\n\nconst log = debug(\"waku:filter\");\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport type FilterSubscriptionOpts = {\n /**\n * The Pubsub topic for the subscription\n */\n pubsubTopic?: string;\n /**\n * Optionally specify a PeerId for the subscription. If not included, will use a random peer.\n */\n peerId?: PeerId;\n};\n\nexport type FilterCallback = (msg: WakuMessage) => void | Promise;\n\nexport type UnsubscribeFunction = () => Promise;\n\n/**\n * Implements client side of the [Waku v2 Filter protocol](https://rfc.vac.dev/spec/12/).\n *\n * Note this currently only works in NodeJS when the Waku node is listening on a port, see:\n * - https://github.com/status-im/go-waku/issues/245\n * - https://github.com/status-im/nwaku/issues/948\n */\nexport class WakuFilter {\n pubSubTopic: string;\n private subscriptions: Map;\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.subscriptions = new Map();\n this.decryptionKeys = new Map();\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n this.libp2p\n .handle(FilterCodec, this.onRequest.bind(this))\n .catch((e) => log(\"Failed to register filter protocol\", e));\n }\n\n /**\n * @param contentTopics Array of ContentTopics to subscribe to. If empty, no messages will be returned from the filter.\n * @param callback A function that will be called on each message returned by the filter.\n * @param opts The FilterSubscriptionOpts used to narrow which messages are returned, and which peer to connect to.\n * @returns Unsubscribe function that can be used to end the subscription.\n */\n async subscribe(\n callback: FilterCallback,\n contentTopics: string[],\n opts?: FilterSubscriptionOpts\n ): Promise {\n const topic = opts?.pubsubTopic ?? this.pubSubTopic;\n const contentFilters = contentTopics.map((contentTopic) => ({\n contentTopic,\n }));\n const request = FilterRPC.createRequest(\n topic,\n contentFilters,\n undefined,\n true\n );\n\n const requestId = request.requestId;\n if (!requestId)\n throw new Error(\n \"Internal error: createRequest expected to set `requestId`\"\n );\n\n const peer = await this.getPeer(opts?.peerId);\n const stream = await this.newStream(peer);\n\n try {\n const res = await pipe(\n [request.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n\n log(\"response\", res);\n } catch (e) {\n log(\n \"Error subscribing to peer \",\n peer.id.toString(),\n \"for content topics\",\n contentTopics,\n \": \",\n e\n );\n throw e;\n }\n\n this.addCallback(requestId, callback);\n\n return async () => {\n await this.unsubscribe(topic, contentFilters, requestId, peer);\n this.removeCallback(requestId);\n };\n }\n\n private onRequest(streamData: IncomingStreamData): void {\n log(\"Receiving message push\");\n try {\n pipe(streamData.stream, lp.decode(), async (source) => {\n for await (const bytes of source) {\n const res = FilterRPC.decode(bytes.slice());\n if (res.requestId && res.push?.messages?.length) {\n await this.pushMessages(res.requestId, res.push.messages);\n }\n }\n }).then(\n () => {\n log(\"Receiving pipe closed.\");\n },\n (e) => {\n log(\"Error with receiving pipe\", e);\n }\n );\n } catch (e) {\n log(\"Error decoding message\", e);\n }\n }\n\n private async pushMessages(\n requestId: string,\n messages: WakuMessageProto[]\n ): Promise {\n const callback = this.subscriptions.get(requestId);\n if (!callback) {\n log(`No callback registered for request ID ${requestId}`);\n return;\n }\n\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n for (const message of messages) {\n const decoded = await WakuMessage.decodeProto(message, decryptionKeys);\n if (!decoded) {\n log(\"Not able to decode message\");\n continue;\n }\n callback(decoded);\n }\n }\n\n private addCallback(requestId: string, callback: FilterCallback): void {\n this.subscriptions.set(requestId, callback);\n }\n\n private removeCallback(requestId: string): void {\n this.subscriptions.delete(requestId);\n }\n\n private async unsubscribe(\n topic: string,\n contentFilters: ContentFilter[],\n requestId: string,\n peer: Peer\n ): Promise {\n const unsubscribeRequest = FilterRPC.createRequest(\n topic,\n contentFilters,\n requestId,\n false\n );\n\n const stream = await this.newStream(peer);\n try {\n await pipe([unsubscribeRequest.encode()], lp.encode(), stream.sink);\n } catch (e) {\n log(\"Error unsubscribing\", e);\n throw e;\n }\n }\n\n // Should be able to remove any at next libp2p release >0.37.3\n private async newStream(peer: Peer): Promise {\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections) {\n throw new Error(\"Failed to get a connection to the peer\");\n }\n\n // TODO: Appropriate connection selection\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: tsc is confused by the @libp2p/interface-connection type to use\n return connections[0].newStream(FilterCodec);\n }\n\n private async getPeer(peerId?: PeerId): Promise {\n let peer;\n if (peerId) {\n peer = await this.libp2p.peerStore.get(peerId);\n if (!peer) {\n throw new Error(\n `Failed to retrieve connection details for provided peer in peer store: ${peerId.toString()}`\n );\n }\n } else {\n peer = await this.randomPeer();\n if (!peer) {\n throw new Error(\n \"Failed to find known peer that registers waku filter protocol\"\n );\n }\n }\n return peer;\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received in any\n * subsequent { @link subscribe } call. This can either be a private key for\n * asymmetric encryption or a symmetric key. { @link WakuStore } will attempt to\n * decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**\n * Delete a decryption key so that it cannot be used in future { @link subscribe } calls\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n async peers(): Promise {\n return getPeersForProtocol(this.libp2p, [FilterCodec]);\n }\n\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n string,\n bool,\n bytes,\n uint32,\n double,\n sint64,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface PushRequest {\n pubSubTopic?: string;\n message?: WakuMessage;\n}\n\nexport namespace PushRequest {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"pubSubTopic\", codec: string, optional: true },\n 2: { name: \"message\", codec: WakuMessage.codec(), optional: true },\n });\n };\n\n export const encode = (obj: PushRequest): Uint8Array => {\n return encodeMessage(obj, PushRequest.codec());\n };\n\n export const decode = (buf: Uint8Array): PushRequest => {\n return decodeMessage(buf, PushRequest.codec());\n };\n}\n\nexport interface PushResponse {\n isSuccess?: boolean;\n info?: string;\n}\n\nexport namespace PushResponse {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"isSuccess\", codec: bool, optional: true },\n 2: { name: \"info\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: PushResponse): Uint8Array => {\n return encodeMessage(obj, PushResponse.codec());\n };\n\n export const decode = (buf: Uint8Array): PushResponse => {\n return decodeMessage(buf, PushResponse.codec());\n };\n}\n\nexport interface PushRPC {\n requestId?: string;\n request?: PushRequest;\n response?: PushResponse;\n}\n\nexport namespace PushRPC {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"requestId\", codec: string, optional: true },\n 2: { name: \"request\", codec: PushRequest.codec(), optional: true },\n 3: { name: \"response\", codec: PushResponse.codec(), optional: true },\n });\n };\n\n export const encode = (obj: PushRPC): Uint8Array => {\n return encodeMessage(obj, PushRPC.codec());\n };\n\n export const decode = (buf: Uint8Array): PushRPC => {\n return decodeMessage(buf, PushRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","import { v4 as uuid } from \"uuid\";\n\nimport * as proto from \"../../proto/light_push\";\nimport { WakuMessage } from \"../waku_message\";\n\nexport class PushRPC {\n public constructor(public proto: proto.PushRPC) {}\n\n static createRequest(message: WakuMessage, pubSubTopic: string): PushRPC {\n return new PushRPC({\n requestId: uuid(),\n request: {\n message: message.proto,\n pubSubTopic: pubSubTopic,\n },\n response: undefined,\n });\n }\n\n static decode(bytes: Uint8Array): PushRPC {\n const res = proto.PushRPC.decode(bytes);\n return new PushRPC(res);\n }\n\n encode(): Uint8Array {\n return proto.PushRPC.encode(this.proto);\n }\n\n get query(): proto.PushRequest | undefined {\n return this.proto.request;\n }\n\n get response(): proto.PushResponse | undefined {\n return this.proto.response;\n }\n}\n","import type { PeerId } from \"@libp2p/interface-peer-id\";\nimport type { Peer } from \"@libp2p/interface-peer-store\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Libp2p } from \"libp2p\";\n\nimport { PushResponse } from \"../../proto/light_push\";\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { concat } from \"../utils\";\nimport { WakuMessage } from \"../waku_message\";\n\nimport { PushRPC } from \"./push_rpc\";\n\nexport const LightPushCodec = \"/vac/waku/lightpush/2.0.0-beta1\";\nexport { PushResponse };\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport interface PushOptions {\n peerId?: PeerId;\n pubSubTopic?: string;\n}\n\n/**\n * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).\n */\nexport class WakuLightPush {\n pubSubTopic: string;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n }\n\n async push(\n message: WakuMessage,\n opts?: PushOptions\n ): Promise {\n let peer;\n if (opts?.peerId) {\n peer = await this.libp2p.peerStore.get(opts.peerId);\n if (!peer) throw \"Peer is unknown\";\n } else {\n peer = await this.randomPeer();\n }\n if (!peer) throw \"No peer available\";\n if (!peer.protocols.includes(LightPushCodec))\n throw \"Peer does not register waku light push protocol\";\n\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections) throw \"Failed to get a connection to the peer\";\n\n // TODO: Appropriate connection management\n const stream = await connections[0].newStream(LightPushCodec);\n try {\n const pubSubTopic = opts?.pubSubTopic\n ? opts.pubSubTopic\n : this.pubSubTopic;\n const query = PushRPC.createRequest(message, pubSubTopic);\n const res = await pipe(\n [query.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n try {\n const bytes = concat(res);\n const response = PushRPC.decode(bytes).response;\n\n if (!response) {\n console.log(\"No response in PushRPC\");\n return null;\n }\n\n return response;\n } catch (err) {\n console.log(\"Failed to decode push reply\", err);\n }\n } catch (err) {\n console.log(\"Failed to send waku light push request\", err);\n }\n return null;\n }\n\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * light push protocol. Waku may or may not be currently connected to these\n * peers.\n */\n async peers(): Promise {\n return getPeersForProtocol(this.libp2p, [LightPushCodec]);\n }\n\n /**\n * Returns a random peer that supports light push protocol from the address\n * book (`libp2p.peerStore`). Waku may or may not be currently connected to\n * this peer.\n */\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","export const second = 1000;\nexport const minute = 60 * second;\n\n/**\n * RelayCodec is the libp2p identifier for the waku relay protocol\n */\nexport const RelayCodecs = [\n \"/vac/waku/relay/2.0.0-beta2\",\n \"/vac/waku/relay/2.0.0\",\n];\n\nexport const RelayPingContentTopic = \"/relay-ping/1/ping/null\";\n\n/**\n * RelayGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to RelayGossipFactor * (total number of non-mesh peers), or\n * RelayDlazy, whichever is greater.\n */\nexport const RelayGossipFactor = 0.25;\n\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const RelayHeartbeatInitialDelay = 100;\n\n/**\n * RelayHeartbeatInterval controls the time between heartbeats.\n */\nexport const RelayHeartbeatInterval = second;\n\n/**\n * RelayPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to RelayPrunePeers other peers that we\n * know of.\n */\nexport const RelayPrunePeers = 16;\n\n/**\n * RelayPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of RelayPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least RelayPruneBackoff\n * before attempting to re-graft.\n */\nexport const RelayPruneBackoff = minute;\n\n/**\n * RelayFanoutTTL controls how long we keep track of the fanout state. If it's been\n * RelayFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const RelayFanoutTTL = minute;\n\n/**\n * RelayOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every RelayOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const RelayOpportunisticGraftTicks = 60;\n\n/**\n * RelayOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const RelayOpportunisticGraftPeers = 2;\n\n/**\n * RelayMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const RelayMaxIHaveLength = 5000;\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n bytes,\n sint64,\n string,\n enumeration,\n uint64,\n uint32,\n double,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface Index {\n digest?: Uint8Array;\n receivedTime?: bigint;\n senderTime?: bigint;\n pubsubTopic?: string;\n}\n\nexport namespace Index {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"digest\", codec: bytes, optional: true },\n 2: { name: \"receivedTime\", codec: sint64, optional: true },\n 3: { name: \"senderTime\", codec: sint64, optional: true },\n 4: { name: \"pubsubTopic\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: Index): Uint8Array => {\n return encodeMessage(obj, Index.codec());\n };\n\n export const decode = (buf: Uint8Array): Index => {\n return decodeMessage(buf, Index.codec());\n };\n}\n\nexport interface PagingInfo {\n pageSize?: bigint;\n cursor?: Index;\n direction?: PagingInfo.Direction;\n}\n\nexport namespace PagingInfo {\n export enum Direction {\n DIRECTION_BACKWARD_UNSPECIFIED = \"DIRECTION_BACKWARD_UNSPECIFIED\",\n DIRECTION_FORWARD = \"DIRECTION_FORWARD\",\n }\n\n enum __DirectionValues {\n DIRECTION_BACKWARD_UNSPECIFIED = 0,\n DIRECTION_FORWARD = 1,\n }\n\n export namespace Direction {\n export const codec = () => {\n return enumeration(__DirectionValues);\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 1: { name: \"pageSize\", codec: uint64, optional: true },\n 2: { name: \"cursor\", codec: Index.codec(), optional: true },\n 3: {\n name: \"direction\",\n codec: PagingInfo.Direction.codec(),\n optional: true,\n },\n });\n };\n\n export const encode = (obj: PagingInfo): Uint8Array => {\n return encodeMessage(obj, PagingInfo.codec());\n };\n\n export const decode = (buf: Uint8Array): PagingInfo => {\n return decodeMessage(buf, PagingInfo.codec());\n };\n}\n\nexport interface ContentFilter {\n contentTopic?: string;\n}\n\nexport namespace ContentFilter {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"contentTopic\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n}\n\nexport interface HistoryQuery {\n pubSubTopic?: string;\n contentFilters: ContentFilter[];\n pagingInfo?: PagingInfo;\n startTime?: bigint;\n endTime?: bigint;\n}\n\nexport namespace HistoryQuery {\n export const codec = (): Codec => {\n return message({\n 2: { name: \"pubSubTopic\", codec: string, optional: true },\n 3: {\n name: \"contentFilters\",\n codec: ContentFilter.codec(),\n repeats: true,\n },\n 4: { name: \"pagingInfo\", codec: PagingInfo.codec(), optional: true },\n 5: { name: \"startTime\", codec: sint64, optional: true },\n 6: { name: \"endTime\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: HistoryQuery): Uint8Array => {\n return encodeMessage(obj, HistoryQuery.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryQuery => {\n return decodeMessage(buf, HistoryQuery.codec());\n };\n}\n\nexport interface HistoryResponse {\n messages: WakuMessage[];\n pagingInfo?: PagingInfo;\n error?: HistoryResponse.Error;\n}\n\nexport namespace HistoryResponse {\n export enum Error {\n ERROR_NONE_UNSPECIFIED = \"ERROR_NONE_UNSPECIFIED\",\n ERROR_INVALID_CURSOR = \"ERROR_INVALID_CURSOR\",\n }\n\n enum __ErrorValues {\n ERROR_NONE_UNSPECIFIED = 0,\n ERROR_INVALID_CURSOR = 1,\n }\n\n export namespace Error {\n export const codec = () => {\n return enumeration(__ErrorValues);\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 2: { name: \"messages\", codec: WakuMessage.codec(), repeats: true },\n 3: { name: \"pagingInfo\", codec: PagingInfo.codec(), optional: true },\n 4: {\n name: \"error\",\n codec: HistoryResponse.Error.codec(),\n optional: true,\n },\n });\n };\n\n export const encode = (obj: HistoryResponse): Uint8Array => {\n return encodeMessage(obj, HistoryResponse.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryResponse => {\n return decodeMessage(buf, HistoryResponse.codec());\n };\n}\n\nexport interface HistoryRPC {\n requestId?: string;\n query?: HistoryQuery;\n response?: HistoryResponse;\n}\n\nexport namespace HistoryRPC {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"requestId\", codec: string, optional: true },\n 2: { name: \"query\", codec: HistoryQuery.codec(), optional: true },\n 3: { name: \"response\", codec: HistoryResponse.codec(), optional: true },\n });\n };\n\n export const encode = (obj: HistoryRPC): Uint8Array => {\n return encodeMessage(obj, HistoryRPC.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryRPC => {\n return decodeMessage(buf, HistoryRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n bytes,\n double,\n enumeration,\n uint64,\n string,\n uint32,\n sint64,\n} from \"protons-runtime\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface Index {\n digest?: Uint8Array;\n receivedTime?: number;\n senderTime?: number;\n}\n\nexport namespace Index {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"digest\", codec: bytes, optional: true },\n 2: { name: \"receivedTime\", codec: double, optional: true },\n 3: { name: \"senderTime\", codec: double, optional: true },\n });\n };\n\n export const encode = (obj: Index): Uint8Array => {\n return encodeMessage(obj, Index.codec());\n };\n\n export const decode = (buf: Uint8Array): Index => {\n return decodeMessage(buf, Index.codec());\n };\n}\n\nexport interface PagingInfo {\n pageSize?: bigint;\n cursor?: Index;\n direction?: PagingInfo.Direction;\n}\n\nexport namespace PagingInfo {\n export enum Direction {\n DIRECTION_BACKWARD_UNSPECIFIED = \"DIRECTION_BACKWARD_UNSPECIFIED\",\n DIRECTION_FORWARD = \"DIRECTION_FORWARD\",\n }\n\n enum __DirectionValues {\n DIRECTION_BACKWARD_UNSPECIFIED = 0,\n DIRECTION_FORWARD = 1,\n }\n\n export namespace Direction {\n export const codec = () => {\n return enumeration(__DirectionValues);\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 1: { name: \"pageSize\", codec: uint64, optional: true },\n 2: { name: \"cursor\", codec: Index.codec(), optional: true },\n 3: {\n name: \"direction\",\n codec: PagingInfo.Direction.codec(),\n optional: true,\n },\n });\n };\n\n export const encode = (obj: PagingInfo): Uint8Array => {\n return encodeMessage(obj, PagingInfo.codec());\n };\n\n export const decode = (buf: Uint8Array): PagingInfo => {\n return decodeMessage(buf, PagingInfo.codec());\n };\n}\n\nexport interface ContentFilter {\n contentTopic?: string;\n}\n\nexport namespace ContentFilter {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"contentTopic\", codec: string, optional: true },\n });\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n}\n\nexport interface HistoryQuery {\n pubSubTopic?: string;\n contentFilters: ContentFilter[];\n pagingInfo?: PagingInfo;\n startTime?: number;\n endTime?: number;\n}\n\nexport namespace HistoryQuery {\n export const codec = (): Codec => {\n return message({\n 2: { name: \"pubSubTopic\", codec: string, optional: true },\n 3: {\n name: \"contentFilters\",\n codec: ContentFilter.codec(),\n repeats: true,\n },\n 4: { name: \"pagingInfo\", codec: PagingInfo.codec(), optional: true },\n 5: { name: \"startTime\", codec: double, optional: true },\n 6: { name: \"endTime\", codec: double, optional: true },\n });\n };\n\n export const encode = (obj: HistoryQuery): Uint8Array => {\n return encodeMessage(obj, HistoryQuery.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryQuery => {\n return decodeMessage(buf, HistoryQuery.codec());\n };\n}\n\nexport interface HistoryResponse {\n messages: WakuMessage[];\n pagingInfo?: PagingInfo;\n error?: HistoryResponse.Error;\n}\n\nexport namespace HistoryResponse {\n export enum Error {\n ERROR_NONE_UNSPECIFIED = \"ERROR_NONE_UNSPECIFIED\",\n ERROR_INVALID_CURSOR = \"ERROR_INVALID_CURSOR\",\n }\n\n enum __ErrorValues {\n ERROR_NONE_UNSPECIFIED = 0,\n ERROR_INVALID_CURSOR = 1,\n }\n\n export namespace Error {\n export const codec = () => {\n return enumeration(__ErrorValues);\n };\n }\n\n export const codec = (): Codec => {\n return message({\n 2: { name: \"messages\", codec: WakuMessage.codec(), repeats: true },\n 3: { name: \"pagingInfo\", codec: PagingInfo.codec(), optional: true },\n 4: {\n name: \"error\",\n codec: HistoryResponse.Error.codec(),\n optional: true,\n },\n });\n };\n\n export const encode = (obj: HistoryResponse): Uint8Array => {\n return encodeMessage(obj, HistoryResponse.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryResponse => {\n return decodeMessage(buf, HistoryResponse.codec());\n };\n}\n\nexport interface HistoryRPC {\n requestId?: string;\n query?: HistoryQuery;\n response?: HistoryResponse;\n}\n\nexport namespace HistoryRPC {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"requestId\", codec: string, optional: true },\n 2: { name: \"query\", codec: HistoryQuery.codec(), optional: true },\n 3: { name: \"response\", codec: HistoryResponse.codec(), optional: true },\n });\n };\n\n export const encode = (obj: HistoryRPC): Uint8Array => {\n return encodeMessage(obj, HistoryRPC.codec());\n };\n\n export const decode = (buf: Uint8Array): HistoryRPC => {\n return decodeMessage(buf, HistoryRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n export const codec = (): Codec => {\n return message({\n 1: { name: \"payload\", codec: bytes, optional: true },\n 2: { name: \"contentTopic\", codec: string, optional: true },\n 3: { name: \"version\", codec: uint32, optional: true },\n 4: { name: \"timestampDeprecated\", codec: double, optional: true },\n 10: { name: \"timestamp\", codec: sint64, optional: true },\n });\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","export enum StoreCodecs {\n V2Beta3 = \"/vac/waku/store/2.0.0-beta3\",\n V2Beta4 = \"/vac/waku/store/2.0.0-beta4\",\n}\n","import { v4 as uuid } from \"uuid\";\n\nimport * as protoV2Beta3 from \"../../proto/store_v2beta3\";\nimport * as protoV2Beta4 from \"../../proto/store_v2beta4\";\n\nimport { StoreCodecs } from \"./constants\";\n\nconst OneMillion = BigInt(1_000_000);\n\nexport enum PageDirection {\n BACKWARD = \"backward\",\n FORWARD = \"forward\",\n}\n\nexport interface Params {\n contentTopics: string[];\n pubSubTopic: string;\n pageDirection: PageDirection;\n pageSize: number;\n startTime?: Date;\n endTime?: Date;\n cursor?: protoV2Beta3.Index | protoV2Beta4.Index;\n storeCodec?: StoreCodecs;\n}\n\nexport class HistoryRPC {\n private readonly historyRpc:\n | typeof protoV2Beta3.HistoryRPC\n | typeof protoV2Beta4.HistoryRPC;\n\n private constructor(\n public readonly proto: protoV2Beta3.HistoryRPC | protoV2Beta4.HistoryRPC,\n public readonly storeCodec: StoreCodecs\n ) {\n switch (storeCodec) {\n case StoreCodecs.V2Beta3:\n this.historyRpc = protoV2Beta3.HistoryRPC;\n break;\n case StoreCodecs.V2Beta4:\n this.historyRpc = protoV2Beta4.HistoryRPC;\n break;\n default:\n throw `Internal Error: Unexpected store codec value received in constructor: ${storeCodec}`;\n }\n }\n\n get query():\n | protoV2Beta3.HistoryQuery\n | protoV2Beta4.HistoryQuery\n | undefined {\n return this.proto.query;\n }\n\n get response():\n | protoV2Beta3.HistoryResponse\n | protoV2Beta4.HistoryResponse\n | undefined {\n return this.proto.response;\n }\n\n /**\n * Create History Query.\n */\n static createQuery(params: Params): HistoryRPC {\n const storeCodec = params.storeCodec ?? StoreCodecs.V2Beta4;\n\n const contentFilters = params.contentTopics.map((contentTopic) => {\n return { contentTopic };\n });\n\n const direction = directionToProto(params.pageDirection);\n\n switch (storeCodec) {\n case StoreCodecs.V2Beta3:\n // Using function to scope variables\n return ((): HistoryRPC => {\n const pagingInfo = {\n pageSize: BigInt(params.pageSize),\n cursor: params.cursor,\n direction,\n } as protoV2Beta3.PagingInfo;\n\n let startTime, endTime;\n if (params.startTime) startTime = params.startTime.valueOf() / 1000;\n\n if (params.endTime) endTime = params.endTime.valueOf() / 1000;\n\n return new HistoryRPC(\n {\n requestId: uuid(),\n query: {\n pubSubTopic: params.pubSubTopic,\n contentFilters,\n pagingInfo,\n startTime,\n endTime,\n },\n response: undefined,\n },\n storeCodec\n );\n })();\n case StoreCodecs.V2Beta4:\n return ((): HistoryRPC => {\n const pagingInfo = {\n pageSize: BigInt(params.pageSize),\n cursor: params.cursor,\n direction,\n } as protoV2Beta4.PagingInfo;\n\n let startTime, endTime;\n if (params.startTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n startTime = BigInt(params.startTime.valueOf()) * OneMillion;\n }\n\n if (params.endTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n endTime = BigInt(params.endTime.valueOf()) * OneMillion;\n }\n return new HistoryRPC(\n {\n requestId: uuid(),\n query: {\n pubSubTopic: params.pubSubTopic,\n contentFilters,\n pagingInfo,\n startTime,\n endTime,\n },\n response: undefined,\n },\n storeCodec\n );\n })();\n\n default:\n throw `Internal Error: Unexpected store codec value received in createQuery: ${storeCodec}`;\n }\n }\n\n decode(bytes: Uint8Array): HistoryRPC {\n const res = this.historyRpc.decode(bytes);\n return new HistoryRPC(res, this.storeCodec);\n }\n\n encode(): Uint8Array {\n return this.historyRpc.encode(this.proto as any);\n }\n}\n\nfunction directionToProto(\n pageDirection: PageDirection\n): protoV2Beta4.PagingInfo.Direction {\n switch (pageDirection) {\n case PageDirection.BACKWARD:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_BACKWARD_UNSPECIFIED;\n case PageDirection.FORWARD:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_FORWARD;\n default:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_BACKWARD_UNSPECIFIED;\n }\n}\n","import type { PeerId } from \"@libp2p/interface-peer-id\";\nimport { Peer } from \"@libp2p/interface-peer-store\";\nimport debug from \"debug\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Libp2p } from \"libp2p\";\n\nimport * as protoV2Beta4 from \"../../proto/store_v2beta4\";\nimport { HistoryResponse } from \"../../proto/store_v2beta4\";\nimport { DefaultPubSubTopic, StoreCodecs } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { concat, hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport { HistoryRPC, PageDirection } from \"./history_rpc\";\n\nimport Error = HistoryResponse.Error;\n\nconst dbg = debug(\"waku:store\");\n\nexport const DefaultPageSize = 10;\n\nexport { PageDirection, StoreCodecs };\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport interface TimeFilter {\n startTime: Date;\n endTime: Date;\n}\n\nexport interface QueryOptions {\n /**\n * The peer to query. If undefined, a pseudo-random peer is selected from the connected Waku Store peers.\n */\n peerId?: PeerId;\n /**\n * The pubsub topic to pass to the query.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/).\n */\n pubSubTopic?: string;\n /**\n * The direction in which pages are retrieved:\n * - { @link PageDirection.BACKWARD }: Most recent page first.\n * - { @link PageDirection.FORWARD }: Oldest page first.\n *\n * Note: This does not affect the ordering of messages with the page\n * (oldest message is always first).\n *\n * @default { @link PageDirection.BACKWARD }\n */\n pageDirection?: PageDirection;\n /**\n * The number of message per page.\n *\n * @default { @link DefaultPageSize }\n */\n pageSize?: number;\n /**\n * Retrieve messages with a timestamp within the provided values.\n */\n timeFilter?: TimeFilter;\n /**\n * Callback called on pages of stored messages as they are retrieved.\n *\n * Allows for a faster access to the results as it is called as soon as a page\n * is received. Traversal of the pages is done automatically so this function\n * will invoked for each retrieved page.\n *\n * If the call on a page returns `true`, then traversal of the pages is aborted.\n * For example, this can be used for the caller to stop the query after a\n * specific message is found.\n */\n callback?: (messages: WakuMessage[]) => void | boolean;\n /**\n * Keys that will be used to decrypt messages.\n *\n * It can be Asymmetric Private Keys and Symmetric Keys in the same array,\n * all keys will be tried with both methods.\n */\n decryptionKeys?: Array;\n}\n\n/**\n * Implements the [Waku v2 Store protocol](https://rfc.vac.dev/spec/13/).\n *\n * The Waku Store protocol can be used to retrieved historical messages.\n */\nexport class WakuStore {\n pubSubTopic: string;\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n\n this.decryptionKeys = new Map();\n }\n\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n *\n * @param contentTopics The content topics to pass to the query, leave empty to\n * retrieve all messages.\n * @param options Optional parameters.\n *\n * @throws If not able to reach a Waku Store peer to query\n * or if an error is encountered when processing the reply.\n */\n async queryHistory(\n contentTopics: string[],\n options?: QueryOptions\n ): Promise {\n let startTime, endTime;\n\n if (options?.timeFilter) {\n startTime = options.timeFilter.startTime;\n endTime = options.timeFilter.endTime;\n }\n\n const opts = Object.assign(\n {\n pubSubTopic: this.pubSubTopic,\n pageDirection: PageDirection.BACKWARD,\n pageSize: DefaultPageSize,\n },\n options,\n { contentTopics, startTime, endTime }\n );\n\n dbg(\"Querying history with the following options\", {\n peerId: options?.peerId?.toString(),\n ...options,\n });\n\n let peer;\n if (opts.peerId) {\n peer = await this.libp2p.peerStore.get(opts.peerId);\n if (!peer)\n throw `Failed to retrieve connection details for provided peer in peer store: ${opts.peerId.toString()}`;\n } else {\n peer = await this.randomPeer();\n if (!peer)\n throw \"Failed to find known peer that registers waku store protocol\";\n }\n\n let storeCodec = \"\";\n for (const codec of Object.values(StoreCodecs)) {\n if (peer.protocols.includes(codec)) {\n storeCodec = codec;\n // Do not break as we want to keep the last value\n }\n }\n dbg(`Use store codec ${storeCodec}`);\n if (!storeCodec)\n throw `Peer does not register waku store protocol: ${peer.id.toString()}`;\n\n Object.assign(opts, { storeCodec });\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections || !connections.length)\n throw \"Failed to get a connection to the peer\";\n\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n // Add the decryption keys passed to this function against the\n // content topics also passed to this function.\n if (opts.decryptionKeys) {\n opts.decryptionKeys.forEach((key) => {\n decryptionKeys.push({\n key: hexToBytes(key),\n contentTopics: contentTopics.length ? contentTopics : undefined,\n method: undefined,\n });\n });\n }\n\n const messages: WakuMessage[] = [];\n let cursor = undefined;\n while (true) {\n // TODO: Some connection selection logic?\n const stream = await connections[0].newStream(storeCodec);\n const queryOpts = Object.assign(opts, { cursor });\n const historyRpcQuery = HistoryRPC.createQuery(queryOpts);\n dbg(\"Querying store peer\", connections[0].remoteAddr.toString());\n\n const res = await pipe(\n [historyRpcQuery.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n const bytes = concat(res);\n const reply = historyRpcQuery.decode(bytes);\n\n if (!reply.response) {\n dbg(\"No message returned from store: `response` field missing\");\n return messages;\n }\n\n const response = reply.response as protoV2Beta4.HistoryResponse;\n\n if (response.error && response.error !== Error.ERROR_NONE_UNSPECIFIED) {\n throw \"History response contains an Error: \" + response.error;\n }\n\n if (!response.messages || !response.messages.length) {\n // No messages left (or stored)\n dbg(\"No message returned from store: `messages` array empty\");\n return messages;\n }\n\n dbg(\n `${response.messages.length} messages retrieved for pubsub topic ${opts.pubSubTopic}`\n );\n\n const pageMessages: WakuMessage[] = [];\n await Promise.all(\n response.messages.map(async (protoMsg) => {\n const msg = await WakuMessage.decodeProto(protoMsg, decryptionKeys);\n\n if (msg) {\n messages.push(msg);\n pageMessages.push(msg);\n }\n })\n );\n\n let abort = false;\n if (opts.callback) {\n abort = Boolean(opts.callback(pageMessages));\n }\n\n const responsePageSize = response.pagingInfo?.pageSize;\n const queryPageSize = historyRpcQuery.query?.pagingInfo?.pageSize;\n if (\n abort ||\n // Response page size smaller than query, meaning this is the last page\n (responsePageSize && queryPageSize && responsePageSize < queryPageSize)\n ) {\n return messages;\n }\n\n cursor = response.pagingInfo?.cursor;\n if (cursor === undefined) {\n // If the server does not return cursor then there is an issue,\n // Need to abort, or we end up in an infinite loop\n dbg(\"Store response does not contain a cursor, stopping pagination\");\n return messages;\n }\n }\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received in any\n * subsequent { @link queryHistory } call. This can either be a private key for\n * asymmetric encryption or a symmetric key. { @link WakuStore } will attempt to\n * decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**cursorV2Beta4\n * Delete a decryption key that was used to attempt decryption of messages\n * received in subsequent { @link queryHistory } calls.\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * store protocol. Waku may or may not be currently connected to these peers.\n */\n async peers(): Promise {\n const codecs = [];\n for (const codec of Object.values(StoreCodecs)) {\n codecs.push(codec);\n }\n\n return getPeersForProtocol(this.libp2p, codecs);\n }\n\n /**\n * Returns a random peer that supports store protocol from the address\n * book (`libp2p.peerStore`). Waku may or may not be currently connected to\n * this peer.\n */\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","import type { Stream } from \"@libp2p/interface-connection\";\nimport type { PeerId } from \"@libp2p/interface-peer-id\";\nimport { peerIdFromString } from \"@libp2p/peer-id\";\nimport type { Multiaddr } from \"@multiformats/multiaddr\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport debug from \"debug\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { FilterCodec, WakuFilter } from \"./waku_filter\";\nimport { LightPushCodec, WakuLightPush } from \"./waku_light_push\";\nimport { DecryptionMethod, WakuMessage } from \"./waku_message\";\nimport { WakuRelay } from \"./waku_relay\";\nimport { RelayCodecs, RelayPingContentTopic } from \"./waku_relay/constants\";\nimport { StoreCodecs, WakuStore } from \"./waku_store\";\n\nexport const DefaultPingKeepAliveValueSecs = 0;\nexport const DefaultRelayKeepAliveValueSecs = 5 * 60;\n\nconst log = debug(\"waku:waku\");\n\nexport enum Protocols {\n Relay = \"relay\",\n Store = \"store\",\n LightPush = \"lightpush\",\n Filter = \"filter\",\n}\n\nexport interface WakuOptions {\n /**\n * Set keep alive frequency in seconds: Waku will send a `/ipfs/ping/1.0.0`\n * request to each peer after the set number of seconds. Set to 0 to disable.\n *\n * @default {@link DefaultPingKeepAliveValueSecs}\n */\n pingKeepAlive?: number;\n /**\n * Set keep alive frequency in seconds: Waku will send a ping message over\n * relay to each peer after the set number of seconds. Set to 0 to disable.\n *\n * @default {@link DefaultRelayKeepAliveValueSecs}\n */\n relayKeepAlive?: number;\n decryptionKeys?: Array;\n}\n\nexport class Waku {\n public libp2p: Libp2p;\n public relay: WakuRelay;\n public store: WakuStore;\n public filter: WakuFilter;\n public lightPush: WakuLightPush;\n\n private pingKeepAliveTimers: {\n [peer: string]: ReturnType;\n };\n private relayKeepAliveTimers: {\n [peer: string]: ReturnType;\n };\n\n constructor(\n options: WakuOptions,\n libp2p: Libp2p,\n store: WakuStore,\n lightPush: WakuLightPush,\n filter: WakuFilter\n ) {\n this.libp2p = libp2p;\n this.relay = libp2p.pubsub as unknown as WakuRelay;\n this.store = store;\n this.filter = filter;\n this.lightPush = lightPush;\n this.pingKeepAliveTimers = {};\n this.relayKeepAliveTimers = {};\n\n const pingKeepAlive =\n options.pingKeepAlive || DefaultPingKeepAliveValueSecs;\n const relayKeepAlive =\n options.relayKeepAlive || DefaultRelayKeepAliveValueSecs;\n\n libp2p.connectionManager.addEventListener(\"peer:connect\", (evt) => {\n this.startKeepAlive(evt.detail.remotePeer, pingKeepAlive, relayKeepAlive);\n });\n\n /**\n * NOTE: Event is not being emitted on closing nor losing a connection.\n * @see https://github.com/libp2p/js-libp2p/issues/939\n * @see https://github.com/status-im/js-waku/issues/252\n *\n * >This event will be triggered anytime we are disconnected from another peer,\n * >regardless of the circumstances of that disconnection.\n * >If we happen to have multiple connections to a peer,\n * >this event will **only** be triggered when the last connection is closed.\n * @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100\n */\n libp2p.connectionManager.addEventListener(\"peer:disconnect\", (evt) => {\n this.stopKeepAlive(evt.detail.remotePeer);\n });\n\n options?.decryptionKeys?.forEach((key) => {\n this.addDecryptionKey(key);\n });\n }\n\n /**\n * Dials to the provided peer.\n *\n * @param peer The peer to dial\n * @param protocols Waku protocols we expect from the peer; Default to Relay\n */\n async dial(\n peer: PeerId | Multiaddr,\n protocols?: Protocols[]\n ): Promise {\n const _protocols = protocols ?? [Protocols.Relay];\n\n const codecs: string[] = [];\n if (_protocols.includes(Protocols.Relay)) {\n RelayCodecs.forEach((codec) => codecs.push(codec));\n }\n if (_protocols.includes(Protocols.Store)) {\n for (const codec of Object.values(StoreCodecs)) {\n codecs.push(codec);\n }\n }\n if (_protocols.includes(Protocols.LightPush)) {\n codecs.push(LightPushCodec);\n }\n if (_protocols.includes(Protocols.Filter)) {\n codecs.push(FilterCodec);\n }\n\n return this.libp2p.dialProtocol(peer, codecs);\n }\n\n /**\n * Add peer to address book, it will be auto-dialed in the background.\n */\n addPeerToAddressBook(\n peerId: PeerId | string,\n multiaddrs: Multiaddr[] | string[]\n ): void {\n let peer;\n if (typeof peerId === \"string\") {\n peer = peerIdFromString(peerId);\n } else {\n peer = peerId;\n }\n const addresses = multiaddrs.map((addr: Multiaddr | string) => {\n if (typeof addr === \"string\") {\n return multiaddr(addr);\n } else {\n return addr;\n }\n });\n this.libp2p.peerStore.addressBook.set(peer, addresses);\n }\n\n async start(): Promise {\n await this.libp2p.start();\n }\n\n async stop(): Promise {\n this.stopAllKeepAlives();\n await this.libp2p.stop();\n }\n\n isStarted(): boolean {\n return this.libp2p.isStarted();\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received via\n * { @link WakuRelay } and { @link WakuStore }. This can either be a private key for\n * asymmetric encryption or a symmetric key.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.relay.addDecryptionKey(key, options);\n this.store.addDecryptionKey(key, options);\n this.filter.addDecryptionKey(key, options);\n }\n\n /**\n * Delete a decryption key that was used to attempt decryption of messages\n * received via { @link WakuRelay } or { @link WakuStore }.\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.relay.deleteDecryptionKey(key);\n this.store.deleteDecryptionKey(key);\n this.filter.deleteDecryptionKey(key);\n }\n\n /**\n * Return the local multiaddr with peer id on which libp2p is listening.\n *\n * @throws if libp2p is not listening on localhost.\n */\n getLocalMultiaddrWithID(): string {\n const localMultiaddr = this.libp2p\n .getMultiaddrs()\n .find((addr) => addr.toString().match(/127\\.0\\.0\\.1/));\n if (!localMultiaddr || localMultiaddr.toString() === \"\") {\n throw \"Not listening on localhost\";\n }\n return localMultiaddr + \"/p2p/\" + this.libp2p.peerId.toString();\n }\n\n private startKeepAlive(\n peerId: PeerId,\n pingPeriodSecs: number,\n relayPeriodSecs: number\n ): void {\n // Just in case a timer already exist for this peer\n this.stopKeepAlive(peerId);\n\n const peerIdStr = peerId.toString();\n\n if (pingPeriodSecs !== 0) {\n this.pingKeepAliveTimers[peerIdStr] = setInterval(() => {\n this.libp2p.ping(peerId).catch((e) => {\n log(`Ping failed (${peerIdStr})`, e);\n });\n }, pingPeriodSecs * 1000);\n }\n\n if (relayPeriodSecs !== 0) {\n this.relayKeepAliveTimers[peerIdStr] = setInterval(() => {\n WakuMessage.fromBytes(new Uint8Array(), RelayPingContentTopic).then(\n (wakuMsg) => this.relay.send(wakuMsg)\n );\n }, relayPeriodSecs * 1000);\n }\n }\n\n private stopKeepAlive(peerId: PeerId): void {\n const peerIdStr = peerId.toString();\n\n if (this.pingKeepAliveTimers[peerIdStr]) {\n clearInterval(this.pingKeepAliveTimers[peerIdStr]);\n delete this.pingKeepAliveTimers[peerIdStr];\n }\n\n if (this.relayKeepAliveTimers[peerIdStr]) {\n clearInterval(this.relayKeepAliveTimers[peerIdStr]);\n delete this.relayKeepAliveTimers[peerIdStr];\n }\n }\n\n private stopAllKeepAlives(): void {\n for (const timer of [\n ...Object.values(this.pingKeepAliveTimers),\n ...Object.values(this.relayKeepAliveTimers),\n ]) {\n clearInterval(timer);\n }\n\n this.pingKeepAliveTimers = {};\n this.relayKeepAliveTimers = {};\n }\n}\n","import type { GossipSub } from \"@chainsafe/libp2p-gossipsub\";\nimport { Peer, PeerProtocolsChangeData } from \"@libp2p/interface-peer-store\";\nimport debug from \"debug\";\nimport type { Libp2p } from \"libp2p\";\nimport { pEvent } from \"p-event\";\n\nimport { StoreCodecs } from \"./constants\";\nimport { Protocols, Waku } from \"./waku\";\nimport { FilterCodec } from \"./waku_filter\";\nimport { LightPushCodec } from \"./waku_light_push\";\n\nconst log = debug(\"waku:wait-for-remote-peer\");\n\ninterface WakuProtocol {\n libp2p: Libp2p;\n peers: () => Promise;\n}\n\ninterface WakuGossipSubProtocol extends GossipSub {\n getMeshPeers: () => string[];\n}\n\n/**\n * Wait for a remote peer to be ready given the passed protocols.\n * Must be used after attempting to connect to nodes, using {@link index.waku.Waku.dial} or\n * a bootstrap method with {@link index.waku.Waku.constructor}.\n *\n * If the passed protocols is a GossipSub protocol, then it resolves only once\n * a peer is in a mesh, to help ensure that other peers will send and receive\n * message to us.\n *\n * @param waku The Waku Node\n * @param protocols The protocols that need to be enabled by remote peers.\n * @param timeoutMs A timeout value in milliseconds..\n *\n * @returns A promise that **resolves** if all desired protocols are fulfilled by\n * remote nodes, **rejects** if the timeoutMs is reached.\n *\n * @default Remote peer must have Waku Relay enabled and no time out is applied.\n */\nexport async function waitForRemotePeer(\n waku: Waku,\n protocols?: Protocols[],\n timeoutMs?: number\n): Promise {\n protocols = protocols ?? [Protocols.Relay];\n\n if (!waku.isStarted()) return Promise.reject(\"Waku node is not started\");\n\n const promises = [];\n\n if (protocols.includes(Protocols.Relay)) {\n promises.push(waitForGossipSubPeerInMesh(waku.relay));\n }\n\n if (protocols.includes(Protocols.Store)) {\n promises.push(waitForConnectedPeer(waku.store, Object.values(StoreCodecs)));\n }\n\n if (protocols.includes(Protocols.LightPush)) {\n promises.push(waitForConnectedPeer(waku.lightPush, [LightPushCodec]));\n }\n\n if (protocols.includes(Protocols.Filter)) {\n promises.push(waitForConnectedPeer(waku.filter, [FilterCodec]));\n }\n\n if (timeoutMs) {\n await rejectOnTimeout(\n Promise.all(promises),\n timeoutMs,\n \"Timed out waiting for a remote peer.\"\n );\n } else {\n await Promise.all(promises);\n }\n}\n\n/**\n * Wait for a peer with the given protocol to be connected.\n */\nasync function waitForConnectedPeer(\n waku: WakuProtocol,\n codecs: string[]\n): Promise {\n const peers = await waku.peers();\n\n if (peers.length) {\n log(`${codecs} peer found: `, peers[0].id.toString());\n return;\n }\n\n await new Promise((resolve) => {\n const cb = (evt: CustomEvent): void => {\n for (const codec of codecs) {\n if (evt.detail.protocols.includes(codec)) {\n log(\"Resolving for\", codec, evt.detail.protocols);\n waku.libp2p.peerStore.removeEventListener(\"change:protocols\", cb);\n resolve();\n break;\n }\n }\n };\n waku.libp2p.peerStore.addEventListener(\"change:protocols\", cb);\n });\n}\n\n/**\n * Wait for a peer with the given protocol to be connected and in the gossipsub\n * mesh.\n */\nasync function waitForGossipSubPeerInMesh(\n waku: WakuGossipSubProtocol\n): Promise {\n let peers = waku.getMeshPeers();\n\n while (peers.length == 0) {\n await pEvent(waku, \"gossipsub:heartbeat\");\n peers = waku.getMeshPeers();\n }\n}\n\nconst awaitTimeout = (ms: number, rejectReason: string): Promise =>\n new Promise((_resolve, reject) => setTimeout(() => reject(rejectReason), ms));\n\nasync function rejectOnTimeout(\n promise: Promise,\n timeoutMs: number,\n rejectReason: string\n): Promise {\n await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);\n}\n","\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\n","import { concat } from 'uint8arrays'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\ntype Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number, totalLength: number) {\n if (index == null || index < 0 || index >= totalLength) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable {\n private bufs: Uint8Array[]\n public length: number\n\n constructor (...data: Appendable[]) {\n // Define symbol\n Object.defineProperty(this, symbol, { value: true })\n\n this.bufs = []\n this.length = 0\n\n this.appendAll(data)\n }\n\n * [Symbol.iterator] () {\n yield * this.bufs\n }\n\n get byteLength () {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to this Uint8ArrayList\n */\n append (...bufs: Appendable[]) {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.length\n this.bufs = this.bufs.concat(buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number) {\n const res = findBufAndOffset(this.bufs, index, this.length)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number) {\n const res = findBufAndOffset(this.bufs, index, this.length)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n slice (beginInclusive?: number, endExclusive?: number) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n subarray (beginInclusive?: number, endExclusive?: number) {\n const { bufs } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.appendAll(bufs)\n\n return list\n }\n\n _subList (beginInclusive?: number, endExclusive?: number) {\n if (beginInclusive == null && endExclusive == null) {\n return { bufs: this.bufs, length: this.length }\n }\n\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? (this.length > 0 ? this.length : 0)\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (const buf of this.bufs) {\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n const bufInSlice = beginInclusive < bufStart && endExclusive >= bufEnd\n offset = bufEnd\n\n let startIndex: number | undefined\n let endIndex: number | undefined\n\n if (sliceStartInBuf) {\n startIndex = beginInclusive - bufStart\n endIndex = buf.byteLength\n }\n\n if (sliceEndsInBuf) {\n endIndex = endExclusive - bufStart\n\n if (startIndex == null) {\n startIndex = 0\n }\n }\n\n if (bufInSlice) {\n startIndex = 0\n endIndex = buf.byteLength\n }\n\n if (startIndex != null && endIndex != null) {\n bufs.push(buf.subarray(startIndex, endIndex))\n }\n\n if (sliceEndsInBuf) {\n break\n }\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.slice(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = new Uint8Array(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.slice(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = new Uint8Array(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.slice(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = new Uint8Array(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.slice(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = new Uint8Array(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.slice(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = new Uint8Array(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport default function accessor (buf: Uint8Array | Uint8ArrayList) {\n if (buf instanceof Uint8Array) {\n return {\n get (index: number) {\n return buf[index]\n },\n\n set (index: number, value: number) {\n buf[index] = value\n }\n }\n }\n\n return {\n get (index: number) {\n return buf.get(index)\n },\n\n set (index: number, value: number) {\n buf.set(index, value)\n }\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\n\nconst TWO_32 = 4294967296\n\nexport class LongBits {\n public hi: number\n public lo: number\n\n constructor (hi: number = 0, lo: number = 0) {\n this.hi = hi\n this.lo = lo\n }\n\n toBigInt (unsigned: boolean): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n zzDecode () {\n const mask = -(this.lo & 1)\n const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n const hi = (this.hi >>> 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n zzEncode () {\n const mask = this.hi >> 31\n const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n const lo = (this.lo << 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n toBytes (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n const access = accessor(buf)\n\n while (this.hi > 0) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0\n this.hi >>>= 7\n }\n\n while (this.lo > 127) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = this.lo >>> 7\n }\n\n access.set(offset++, this.lo)\n }\n\n static fromBigInt (value: bigint) {\n if (value === 0n) {\n return new LongBits()\n }\n\n const negative = value < 0\n\n if (negative) {\n value = -value\n }\n\n let hi = Number(value >> 32n) | 0\n let lo = Number(value - (BigInt(hi) << 32n)) | 0\n\n if (negative) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > TWO_32) {\n lo = 0\n\n if (++hi > TWO_32) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n static fromNumber (value: number) {\n if (value === 0) {\n return new LongBits()\n }\n\n const sign = value < 0\n\n if (sign) {\n value = -value\n }\n\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > 4294967295) {\n lo = 0\n\n if (++hi > 4294967295) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n static fromBytes (buf: Uint8ArrayList | Uint8Array, offset: number) {\n const access = accessor(buf)\n\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits()\n let i = 0\n\n if (buf.length - offset > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0\n bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0\n if (access.get(offset++) < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 1st..3th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (access.get(offset++) & 127) << i * 7) >>> 0\n return bits\n }\n if (buf.length - offset > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n if (access.get(offset++) < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n /* istanbul ignore next */\n throw Error('invalid varint encoding')\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\nimport { LongBits } from './long-bits.js'\n\nconst MSB = 0x80\nconst REST = 0x7F\nconst MSBALL = ~REST\nconst INT = Math.pow(2, 31)\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\nexport const unsigned = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array) {\n let offset = 0\n const access = accessor(buf)\n\n while (value >= INT) {\n access.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n\n while ((value & MSBALL) > 0) {\n access.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n\n access.set(offset, value | 0)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0) {\n const access = accessor(buf)\n let value = 4294967295 // optimizer type-hint, tends to deopt otherwise (?!)\n\n value = (access.get(offset) & 127) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 14) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 127) << 21) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n value = (value | (access.get(offset) & 15) << 28) >>> 0\n\n if (access.get(offset++) < 128) {\n return value\n }\n\n if ((offset += 5) > buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n return value\n }\n}\n\nexport const signed = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array) {\n if (value < 0) {\n let offset = 0\n const access = accessor(buf)\n const bits = LongBits.fromNumber(value)\n\n while (bits.hi > 0) {\n access.set(offset++, bits.lo & 127 | 128)\n bits.lo = (bits.lo >>> 7 | bits.hi << 25) >>> 0\n bits.hi >>>= 7\n }\n\n while (bits.lo > 127) {\n access.set(offset++, bits.lo & 127 | 128)\n bits.lo = bits.lo >>> 7\n }\n\n access.set(offset++, bits.lo)\n\n return\n }\n\n unsigned.encode(value, buf)\n },\n\n decode (data: Uint8ArrayList | Uint8Array, offset = 0) {\n return unsigned.decode(data, offset) | 0\n }\n}\n\nexport const zigzag = {\n encodingLength (value: number): number {\n value = (value << 1 ^ value >> 31) >>> 0\n return unsigned.encodingLength(value)\n },\n\n encode (value: number, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n value = (value << 1 ^ value >> 31) >>> 0\n return unsigned.encode(value, buf)\n },\n\n decode (data: Uint8ArrayList | Uint8Array, offset = 0) {\n const value = unsigned.decode(data, offset)\n return value >>> 1 ^ -(value & 1) | 0\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from './utils/varint.js'\nimport type { Codec } from './codec.js'\n\nexport function decodeMessage (buf: Uint8Array, codec: Codec) {\n // wrap root message\n const prefix = new Uint8Array(unsigned.encodingLength(buf.length))\n unsigned.encode(buf.length, prefix)\n\n return codec.decode(new Uint8ArrayList(prefix, buf), 0)\n}\n","import type { Codec } from './codec.js'\nimport { unsigned } from './utils/varint.js'\n\nexport function encodeMessage (message: T, codec: Codec) {\n // unwrap root message\n const encoded = codec.encode(message)\n const skip = unsigned.encodingLength(unsigned.decode(encoded))\n\n return encoded.slice(skip)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeFunction {\n (value: T): Uint8Array | Uint8ArrayList\n}\n\nexport interface DecodeFunction {\n (buf: Uint8ArrayList, offset: number): T\n}\n\nexport interface EncodingLengthFunction {\n (value: T): number\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n encodingLength: EncodingLengthFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction, encodingLength: EncodingLengthFunction): Codec {\n return {\n name,\n type,\n encode,\n decode,\n encodingLength\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function boolEncodingLength () {\n return 1\n}\n\nconst encode: EncodeFunction = function boolEncode (value) {\n return Uint8Array.from([value ? 1 : 0])\n}\n\nconst decode: DecodeFunction = function boolDecode (buffer, offset) {\n return buffer.get(offset) > 0\n}\n\nexport const bool = createCodec('bool', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function bytesEncodingLength (val) {\n const len = val.byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function bytesEncode (val) {\n const prefix = new Uint8Array(unsigned.encodingLength(val.byteLength))\n\n unsigned.encode(val.byteLength, prefix)\n\n return new Uint8ArrayList(prefix, val)\n}\n\nconst decode: DecodeFunction = function bytesDecode (buf, offset) {\n const byteLength = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(byteLength)\n\n return buf.slice(offset, offset + byteLength)\n}\n\nexport const bytes = createCodec('bytes', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function doubleEncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function doubleEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setFloat64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function doubleDecode (buf, offset) {\n return buf.getFloat64(offset, true)\n}\n\nexport const double = createCodec('double', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function fixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function fixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function fixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const fixed32 = createCodec('fixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return 8\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const fixed64 = createCodec('fixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function floatEncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function floatEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(1)))\n buf.setFloat32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function floatDecode (buf, offset) {\n return buf.getFloat32(offset, true)\n}\n\nexport const float = createCodec('float', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { signed } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int32EncodingLength (val) {\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int32Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n signed.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int32Decode (buf, offset) {\n return signed.decode(buf, offset)\n}\n\nexport const int32 = createCodec('int32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from './accessor.js'\nimport { LongBits } from './long-bits.js'\n\nconst LIMIT = 0x7fn\n\n// https://github.com/joeltg/big-varint/blob/main/src/unsigned.ts\nexport const unsigned = {\n encodingLength (value: bigint): number {\n let i = 0\n for (; value >= 0x80n; i++) {\n value >>= 7n\n }\n return i + 1\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array) {\n const access = accessor(buf)\n\n let offset = 0\n while (LIMIT < value) {\n access.set(offset++, Number(value & LIMIT) | 0x80)\n value >>= 7n\n }\n\n access.set(offset, Number(value))\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(true)\n }\n}\n\nexport const signed = {\n encodingLength (value: bigint): number {\n if (value < 0n) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n if (value < 0n) {\n LongBits.fromBigInt(value).toBytes(buf, offset)\n\n return\n }\n\n return unsigned.encode(value, buf)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(false)\n }\n}\n\nexport const zigzag = {\n encodingLength (value: bigint): number {\n return unsigned.encodingLength(value >= 0 ? value * 2n : value * -2n - 1n)\n },\n\n encode (value: bigint, buf: Uint8ArrayList | Uint8Array, offset = 0) {\n LongBits.fromBigInt(value).zzEncode().toBytes(buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).zzDecode().toBigInt(false)\n }\n}\n","import { signed } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n signed.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return signed.decode(buf, offset) | 0n\n}\n\nexport const int64 = createCodec('int64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction, Codec } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { FieldDefs, FieldDef } from '../index.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (fieldDefs: FieldDefs): Codec {\n const encodingLength: EncodingLengthFunction = function messageEncodingLength (val: Record) {\n let length = 0\n\n for (const fieldDef of Object.values(fieldDefs)) {\n length += fieldDef.codec.encodingLength(val[fieldDef.name])\n }\n\n return unsigned.encodingLength(length) + length\n }\n\n const encode: EncodeFunction> = function messageEncode (val) {\n const bytes = new Uint8ArrayList()\n\n function encodeValue (value: any, fieldNumber: number, fieldDef: FieldDef) {\n if (value == null) {\n if (fieldDef.optional === true) {\n return\n }\n\n throw new Error(`Non optional field \"${fieldDef.name}\" was ${value === null ? 'null' : 'undefined'}`)\n }\n\n const key = (fieldNumber << 3) | fieldDef.codec.type\n const prefix = new Uint8Array(unsigned.encodingLength(key))\n unsigned.encode(key, prefix)\n const encoded = fieldDef.codec.encode(value)\n\n bytes.append(prefix)\n bytes.append(encoded)\n }\n\n for (const [fieldNumberStr, fieldDef] of Object.entries(fieldDefs)) {\n const fieldNumber = parseInt(fieldNumberStr)\n\n if (fieldDef.repeats === true) {\n if (!Array.isArray(val[fieldDef.name])) {\n throw new Error(`Repeating field \"${fieldDef.name}\" was not an array`)\n }\n\n for (const value of val[fieldDef.name]) {\n encodeValue(value, fieldNumber, fieldDef)\n }\n } else {\n encodeValue(val[fieldDef.name], fieldNumber, fieldDef)\n }\n }\n\n const prefix = new Uint8Array(unsigned.encodingLength(bytes.length))\n unsigned.encode(bytes.length, prefix)\n\n return new Uint8ArrayList(prefix, bytes)\n }\n\n const decode: DecodeFunction = function messageDecode (buffer, offset) {\n const length = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(length)\n const end = offset + length\n const fields: any = {}\n\n while (offset < end) {\n const key = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(key)\n\n const wireType = key & 0x7\n const fieldNumber = key >> 3\n const fieldDef = fieldDefs[fieldNumber]\n let fieldLength = 0\n\n if (wireType === CODEC_TYPES.VARINT) {\n if (fieldDef != null) {\n // use the codec if it is available as this could be a bigint\n const value = fieldDef.codec.decode(buffer, offset)\n fieldLength = fieldDef.codec.encodingLength(value)\n } else {\n const value = unsigned.decode(buffer, offset)\n fieldLength = unsigned.encodingLength(value)\n }\n } else if (wireType === CODEC_TYPES.BIT64) {\n fieldLength = 8\n } else if (wireType === CODEC_TYPES.LENGTH_DELIMITED) {\n const valueLength = unsigned.decode(buffer, offset)\n fieldLength = valueLength + unsigned.encodingLength(valueLength)\n } else if (wireType === CODEC_TYPES.BIT32) {\n fieldLength = 4\n } else if (wireType === CODEC_TYPES.START_GROUP) {\n throw new Error('Unsupported wire type START_GROUP')\n } else if (wireType === CODEC_TYPES.END_GROUP) {\n throw new Error('Unsupported wire type END_GROUP')\n }\n\n if (fieldDef != null) {\n const value = fieldDef.codec.decode(buffer, offset)\n\n if (fieldDef.repeats === true) {\n if (fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n\n fields[fieldDef.name].push(value)\n } else {\n fields[fieldDef.name] = value\n }\n }\n\n offset += fieldLength\n }\n\n // make sure repeated fields have an array if not set\n for (const fieldDef of Object.values(fieldDefs)) {\n if (fieldDef.repeats === true && fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n }\n\n return fields\n }\n\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function sfixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const sfixed32 = createCodec('sfixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed64EncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function sfixed64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const sfixed64 = createCodec('sfixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { zigzag } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sint32EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function svarintEncode (val) {\n const buf = new Uint8Array(encodingLength(val))\n\n zigzag.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function svarintDecode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint32 = createCodec('sint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { zigzag } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n zigzag.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint64 = createCodec('sint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint32EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint32Encode (val) {\n // val = val < 0 ? val + 4294967296 : val\n\n const buf = new Uint8Array(encodingLength(val))\n\n unsigned.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function uint32Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n\n // return value > 2147483647 ? value - 4294967296 : value\n}\n\nexport const uint32 = createCodec('uint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from '../utils/varint.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\n\nconst encodingLength: EncodingLengthFunction = function stringEncodingLength (val) {\n const len = uint8ArrayFromString(val).byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function stringEncode (val) {\n const asBuf = uint8ArrayFromString(val)\n const prefix = new Uint8Array(unsigned.encodingLength(asBuf.byteLength))\n\n unsigned.encode(asBuf.length, prefix)\n\n return new Uint8ArrayList(prefix, asBuf)\n}\n\nconst decode: DecodeFunction = function stringDecode (buf, offset) {\n const strLen = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(strLen)\n\n return uint8ArrayToString(buf.slice(offset, offset + strLen))\n}\n\nexport const string = createCodec('string', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { unsigned } from '../utils/big-varint.js'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint64EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint64Encode (val) {\n const buf = new Uint8Array(unsigned.encodingLength(val))\n\n unsigned.encode(val, buf)\n\n return buf\n}\n\nconst decode: DecodeFunction = function uint64Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n}\n\nexport const uint64 = createCodec('uint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, bytes } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n export const codec = (): Codec => {\n return message({\n 1: { name: 'publicKey', codec: bytes },\n 2: { name: 'payloadType', codec: bytes },\n 3: { name: 'payload', codec: bytes },\n 5: { name: 'signature', codec: bytes }\n })\n }\n\n export const encode = (obj: Envelope): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\n","import errCode from 'err-code'\nimport { concat as uint8arraysConcat } from 'uint8arrays/concat'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport varint from 'varint'\nimport { equals as uint8arraysEquals } from 'uint8arrays/equals'\nimport { codes } from '../errors.js'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\n\nexport interface EnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array) => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\n }\n\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record: Record, peerId: PeerId) => {\n const domain = record.domain\n const payloadType = record.codec\n const payload = record.marshal()\n\n const signData = formatSignaturePayload(domain, payloadType, payload)\n\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\n\n const key = await unmarshalPrivateKey(peerId.privateKey)\n const signature = await key.sign(signData)\n\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\n }\n\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data: Uint8Array, domain: string) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw errCode(new Error('envelope signature is not valid for the given domain'), codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: EnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal () {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload,\n signature: this.signature\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope) {\n return uint8arraysEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return await key.verify(signData, this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array) => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = varint.encode(domainUint8Array.byteLength)\n const payloadTypeLength = varint.encode(payloadType.length)\n const payloadLength = varint.encode(payload.length)\n\n return uint8arraysConcat([\n new Uint8Array(domainLength),\n domainUint8Array,\n new Uint8Array(payloadTypeLength),\n payloadType,\n new Uint8Array(payloadLength),\n payload\n ])\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, bytes, uint64 } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n export const codec = (): Codec => {\n return message({\n 1: { name: 'multiaddr', codec: bytes }\n })\n }\n\n export const encode = (obj: AddressInfo): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n export const codec = (): Codec => {\n return message({\n 1: { name: 'peerId', codec: bytes },\n 2: { name: 'seq', codec: uint64 },\n 3: { name: 'addresses', codec: PeerRecord.AddressInfo.codec(), repeats: true }\n })\n }\n\n export const encode = (obj: PeerRecord): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n","\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1])\n","import { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\n}\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array): PeerRecord => {\n const peerRecord = Protobuf.decode(buf)\n const peerId = peerIdFromBytes(peerRecord.peerId)\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => new Multiaddr(a.multiaddr))\n const seqNumber = peerRecord.seq\n\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\n\n /**\n * Marshal a record to be used in an envelope\n */\n marshal () {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown) {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n","/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals (a: any[], b: any[]) {\n const sort = (a: any, b: any) => a.toString().localeCompare(b.toString())\n return a.length === b.length && b.sort(sort) && a.sort(sort).every((item, index) => b[index].equals(item))\n}\n","import debug from 'debug'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { Key } from 'interface-datastore'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key) => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error: (formatter: any, ...args: any[]) => void\n trace: (formatter: any, ...args: any[]) => void\n enabled: boolean\n}\n\nexport function logger (name: string): Logger {\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace: debug(`${name}:trace`)\n })\n}\n\nexport function disable () {\n debug.disable()\n}\n\nexport function enable (namespaces: string) {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string) {\n return debug.enabled(namespaces)\n}\n","import type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nexport interface IncomingStreamData {\n stream: Stream\n connection: Connection\n}\n\nexport interface StreamHandler {\n (data: IncomingStreamData): void\n}\n\nexport interface StreamHandlerOptions {\n /**\n * How many incoming streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxInboundStreams?: number\n\n /**\n * How many outgoing streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxOutboundStreams?: number\n}\n\nexport interface StreamHandlerRecord {\n handler: StreamHandler\n options: StreamHandlerOptions\n}\n\nexport interface Registrar {\n getProtocols: () => string[]\n handle: (protocol: string, handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n unhandle: (protocol: string) => Promise\n getHandler: (protocol: string) => StreamHandlerRecord\n\n register: (protocol: string, topology: Topology) => Promise\n unregister: (id: string) => void\n getTopologies: (protocol: string) => Topology[]\n}\n\nexport interface onConnectHandler {\n (peerId: PeerId, conn: Connection): void\n}\n\nexport interface onDisconnectHandler {\n (peerId: PeerId, conn?: Connection): void\n}\n\nexport interface TopologyInit {\n /**\n * minimum needed connections\n */\n min?: number\n\n /**\n * maximum needed connections\n */\n max?: number\n onConnect?: onConnectHandler\n onDisconnect?: onDisconnectHandler\n}\n\nexport interface Topology {\n min: number\n max: number\n peers: Set\n\n onConnect: (peerId: PeerId, conn: Connection) => void\n onDisconnect: (peerId: PeerId) => void\n setRegistrar: (registrar: Registrar) => Promise\n}\n\nexport const topologySymbol = Symbol.for('@libp2p/topology')\n\nexport function isTopology (other: any): other is Topology {\n return other != null && Boolean(other[topologySymbol])\n}\n","import { topologySymbol as symbol } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Topology, TopologyInit, onConnectHandler, onDisconnectHandler, Registrar } from '@libp2p/interface-registrar'\n\nconst noop = () => {}\n\nclass TopologyImpl implements Topology {\n public min: number\n public max: number\n\n /**\n * Set of peers that support the protocol\n */\n public peers: Set\n public onConnect: onConnectHandler\n public onDisconnect: onDisconnectHandler\n\n protected registrar: Registrar | undefined\n\n constructor (init: TopologyInit) {\n this.min = init.min ?? 0\n this.max = init.max ?? Infinity\n this.peers = new Set()\n\n this.onConnect = init.onConnect ?? noop\n this.onDisconnect = init.onDisconnect ?? noop\n }\n\n get [Symbol.toStringTag] () {\n return symbol.toString()\n }\n\n get [symbol] () {\n return true\n }\n\n async setRegistrar (registrar: Registrar) {\n this.registrar = registrar\n }\n\n /**\n * Notify about peer disconnected event\n */\n disconnect (peerId: PeerId) {\n this.onDisconnect(peerId)\n }\n}\n\nexport function createTopology (init: TopologyInit): Topology {\n return new TopologyImpl(init)\n}\n","\nexport interface EventCallback { (evt: EventType): void }\nexport interface EventObject { handleEvent: EventCallback }\nexport type EventHandler = EventCallback | EventObject\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n * Adds types to the EventTarget class. Hopefully this won't be necessary forever.\n *\n * https://github.com/microsoft/TypeScript/issues/28357\n * https://github.com/microsoft/TypeScript/issues/43477\n * https://github.com/microsoft/TypeScript/issues/299\n * etc\n */\nexport class EventEmitter extends EventTarget {\n #listeners: Map = new Map()\n\n listenerCount (type: string) {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n}\n\n/**\n * CustomEvent is a standard event but it's not supported by node.\n *\n * Remove this when https://github.com/nodejs/node/issues/40678 is closed.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n */\nclass CustomEventPolyfill extends Event {\n /** Returns any custom data event was created with. Typically used for synthetic events. */\n public detail: T\n\n constructor (message: string, data?: EventInit & { detail: T }) {\n super(message, data)\n // @ts-expect-error could be undefined\n this.detail = data?.detail\n }\n}\n\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill\n",null,null,null,null,null,null,"import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Pushable } from 'it-pushable'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Stream } from '@libp2p/interface-connection'\n\n/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nexport const StrictSign = 'StrictSign'\n\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nexport const StrictNoSign = 'StrictNoSign'\n\nexport type SignaturePolicy = typeof StrictSign | typeof StrictNoSign\n\nexport interface Message {\n from: PeerId\n topic: string\n data: Uint8Array\n sequenceNumber?: bigint\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCMessage {\n from?: Uint8Array\n topic?: string\n data?: Uint8Array\n sequenceNumber?: Uint8Array\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCSubscription {\n subscribe?: boolean\n topic?: string\n}\n\nexport interface PubSubRPC {\n subscriptions: PubSubRPCSubscription[]\n messages: PubSubRPCMessage[]\n}\n\nexport interface PeerStreams extends EventEmitter {\n id: PeerId\n protocol: string\n outboundStream?: Pushable\n inboundStream?: AsyncIterable\n isWritable: boolean\n\n close: () => void\n write: (buf: Uint8Array) => void\n attachInboundStream: (stream: Stream) => AsyncIterable\n attachOutboundStream: (stream: Stream) => Promise>\n}\n\nexport interface PubSubInit {\n enabled?: boolean\n\n multicodecs?: string[]\n\n /**\n * defines how signatures should be handled\n */\n globalSignaturePolicy?: SignaturePolicy\n\n /**\n * if can relay messages not subscribed\n */\n canRelayMessage?: boolean\n\n /**\n * if publish should emit to self, if subscribed\n */\n emitSelf?: boolean\n\n /**\n * handle this many incoming pubsub messages concurrently\n */\n messageProcessingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the pubsub protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the pubsub protocol per-connection\n */\n maxOutboundStreams?: number\n}\n\ninterface Subscription {\n topic: string\n subscribe: boolean\n}\n\nexport interface SubscriptionChangeData {\n peerId: PeerId\n subscriptions: Subscription[]\n}\n\nexport interface PubSubEvents {\n 'subscription-change': CustomEvent\n 'message': CustomEvent\n}\n\nexport interface PublishResult {\n recipients: PeerId[]\n}\n\nexport interface PubSub extends EventEmitter {\n globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n multicodecs: string[]\n\n getPeers: () => PeerId[]\n getTopics: () => string[]\n subscribe: (topic: string) => void\n unsubscribe: (topic: string) => void\n getSubscribers: (topic: string) => PeerId[]\n publish: (topic: string, data: Uint8Array) => Promise\n}\n\nexport interface PeerStreamEvents {\n 'stream:inbound': CustomEvent\n 'stream:outbound': CustomEvent\n 'close': CustomEvent\n}\n",null,null,null,null,null,null,"\n/**\n * Implemented by components that have a lifecycle\n */\nexport interface Startable {\n isStarted: () => boolean\n\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?: () => void | Promise\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?: () => void | Promise\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?: () => void | Promise\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?: () => void | Promise\n}\n\nexport function isStartable (obj: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\nexport async function start (...objs: any[]) {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\nexport async function stop (...objs: any[]) {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n","import errCode from 'err-code'\nimport type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport { isStartable, Startable } from '@libp2p/interfaces/startable'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport type { TransportManager, Upgrader } from '@libp2p/interface-transport'\nimport type { Datastore } from 'interface-datastore'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nexport interface Initializable {\n init: (components: Components) => void\n}\n\nexport function isInitializable (obj: any): obj is Initializable {\n return obj != null && typeof obj.init === 'function'\n}\n\nexport interface ComponentsInit {\n peerId?: PeerId\n addressManager?: AddressManager\n peerStore?: PeerStore\n upgrader?: Upgrader\n metrics?: Metrics\n registrar?: Registrar\n connectionManager?: ConnectionManager\n transportManager?: TransportManager\n connectionGater?: ConnectionGater\n contentRouting?: ContentRouting\n peerRouting?: PeerRouting\n datastore?: Datastore\n connectionProtector?: ConnectionProtector\n dht?: DualDHT\n pubsub?: PubSub\n}\n\nexport class Components implements Startable {\n private peerId?: PeerId\n private addressManager?: AddressManager\n private peerStore?: PeerStore\n private upgrader?: Upgrader\n private metrics?: Metrics\n private registrar?: Registrar\n private connectionManager?: ConnectionManager\n private transportManager?: TransportManager\n private connectionGater?: ConnectionGater\n private contentRouting?: ContentRouting\n private peerRouting?: PeerRouting\n private datastore?: Datastore\n private connectionProtector?: ConnectionProtector\n private dht?: DualDHT\n private pubsub?: PubSub\n private started = false\n\n constructor (init: ComponentsInit = {}) {\n if (init.peerId != null) {\n this.setPeerId(init.peerId)\n }\n\n if (init.addressManager != null) {\n this.setAddressManager(init.addressManager)\n }\n\n if (init.peerStore != null) {\n this.setPeerStore(init.peerStore)\n }\n\n if (init.upgrader != null) {\n this.setUpgrader(init.upgrader)\n }\n\n if (init.metrics != null) {\n this.setMetrics(init.metrics)\n }\n\n if (init.registrar != null) {\n this.setRegistrar(init.registrar)\n }\n\n if (init.connectionManager != null) {\n this.setConnectionManager(init.connectionManager)\n }\n\n if (init.transportManager != null) {\n this.setTransportManager(init.transportManager)\n }\n\n if (init.connectionGater != null) {\n this.setConnectionGater(init.connectionGater)\n }\n\n if (init.contentRouting != null) {\n this.setContentRouting(init.contentRouting)\n }\n\n if (init.peerRouting != null) {\n this.setPeerRouting(init.peerRouting)\n }\n\n if (init.datastore != null) {\n this.setDatastore(init.datastore)\n }\n\n if (init.connectionProtector != null) {\n this.setConnectionProtector(init.connectionProtector)\n }\n\n if (init.dht != null) {\n this.setDHT(init.dht)\n }\n\n if (init.pubsub != null) {\n this.setPubSub(init.pubsub)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async beforeStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStart != null) {\n await startable.beforeStart()\n }\n })\n )\n }\n\n async start () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.start()\n })\n )\n\n this.started = true\n }\n\n async afterStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStart != null) {\n await startable.afterStart()\n }\n })\n )\n }\n\n async beforeStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStop != null) {\n await startable.beforeStop()\n }\n })\n )\n }\n\n async stop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.stop()\n })\n )\n\n this.started = false\n }\n\n async afterStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStop != null) {\n await startable.afterStop()\n }\n })\n )\n }\n\n setPeerId (peerId: PeerId) {\n this.peerId = peerId\n\n return peerId\n }\n\n getPeerId (): PeerId {\n if (this.peerId == null) {\n throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerId\n }\n\n setMetrics (metrics: Metrics) {\n this.metrics = metrics\n\n if (isInitializable(metrics)) {\n metrics.init(this)\n }\n\n return metrics\n }\n\n getMetrics (): Metrics | undefined {\n return this.metrics\n }\n\n setAddressManager (addressManager: AddressManager) {\n this.addressManager = addressManager\n\n if (isInitializable(addressManager)) {\n addressManager.init(this)\n }\n\n return addressManager\n }\n\n getAddressManager (): AddressManager {\n if (this.addressManager == null) {\n throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.addressManager\n }\n\n setPeerStore (peerStore: PeerStore) {\n this.peerStore = peerStore\n\n if (isInitializable(peerStore)) {\n peerStore.init(this)\n }\n\n return peerStore\n }\n\n getPeerStore (): PeerStore {\n if (this.peerStore == null) {\n throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerStore\n }\n\n setUpgrader (upgrader: Upgrader) {\n this.upgrader = upgrader\n\n if (isInitializable(upgrader)) {\n upgrader.init(this)\n }\n\n return upgrader\n }\n\n getUpgrader (): Upgrader {\n if (this.upgrader == null) {\n throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.upgrader\n }\n\n setRegistrar (registrar: Registrar) {\n this.registrar = registrar\n\n if (isInitializable(registrar)) {\n registrar.init(this)\n }\n\n return registrar\n }\n\n getRegistrar (): Registrar {\n if (this.registrar == null) {\n throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.registrar\n }\n\n setConnectionManager (connectionManager: ConnectionManager) {\n this.connectionManager = connectionManager\n\n if (isInitializable(connectionManager)) {\n connectionManager.init(this)\n }\n\n return connectionManager\n }\n\n getConnectionManager (): ConnectionManager {\n if (this.connectionManager == null) {\n throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.connectionManager\n }\n\n setTransportManager (transportManager: TransportManager) {\n this.transportManager = transportManager\n\n if (isInitializable(transportManager)) {\n transportManager.init(this)\n }\n\n return transportManager\n }\n\n getTransportManager (): TransportManager {\n if (this.transportManager == null) {\n throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.transportManager\n }\n\n setConnectionGater (connectionGater: ConnectionGater) {\n this.connectionGater = connectionGater\n\n if (isInitializable(connectionGater)) {\n connectionGater.init(this)\n }\n\n return connectionGater\n }\n\n getConnectionGater (): ConnectionGater {\n if (this.connectionGater == null) {\n throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.connectionGater\n }\n\n setContentRouting (contentRouting: ContentRouting) {\n this.contentRouting = contentRouting\n\n if (isInitializable(contentRouting)) {\n contentRouting.init(this)\n }\n\n return contentRouting\n }\n\n getContentRouting (): ContentRouting {\n if (this.contentRouting == null) {\n throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.contentRouting\n }\n\n setPeerRouting (peerRouting: PeerRouting) {\n this.peerRouting = peerRouting\n\n if (isInitializable(peerRouting)) {\n peerRouting.init(this)\n }\n\n return peerRouting\n }\n\n getPeerRouting (): PeerRouting {\n if (this.peerRouting == null) {\n throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerRouting\n }\n\n setDatastore (datastore: Datastore) {\n this.datastore = datastore\n\n if (isInitializable(datastore)) {\n datastore.init(this)\n }\n\n return datastore\n }\n\n getDatastore (): Datastore {\n if (this.datastore == null) {\n throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.datastore\n }\n\n setConnectionProtector (connectionProtector: ConnectionProtector) {\n this.connectionProtector = connectionProtector\n\n if (isInitializable(connectionProtector)) {\n connectionProtector.init(this)\n }\n\n return connectionProtector\n }\n\n getConnectionProtector (): ConnectionProtector | undefined {\n return this.connectionProtector\n }\n\n setDHT (dht: DualDHT) {\n this.dht = dht\n\n if (isInitializable(dht)) {\n dht.init(this)\n }\n\n return dht\n }\n\n getDHT (): DualDHT {\n if (this.dht == null) {\n throw errCode(new Error('dht not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.dht\n }\n\n setPubSub (pubsub: PubSub) {\n this.pubsub = pubsub\n\n if (isInitializable(pubsub)) {\n pubsub.init(this)\n }\n\n return pubsub\n }\n\n getPubSub (): PubSub {\n if (this.pubsub == null) {\n throw errCode(new Error('pubsub not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.pubsub\n }\n}\n",null,null,null,null,"// @ts-expect-error types are missing\nimport forgePbkdf2 from 'node-forge/lib/pbkdf2.js'\n// @ts-expect-error types are missing\nimport forgeUtil from 'node-forge/lib/util.js'\nimport errcode from 'err-code'\n\n/**\n * Maps an IPFS hash name to its node-forge equivalent.\n *\n * See https://github.com/multiformats/multihash/blob/master/hashtable.csv\n *\n * @private\n */\nconst hashName = {\n sha1: 'sha1',\n 'sha2-256': 'sha256',\n 'sha2-512': 'sha512'\n}\n\n/**\n * Computes the Password-Based Key Derivation Function 2.\n */\nexport default function pbkdf2 (password: string, salt: string, iterations: number, keySize: number, hash: string): string {\n if (hash !== 'sha1' && hash !== 'sha2-256' && hash !== 'sha2-512') {\n const types = Object.keys(hashName).join(' / ')\n throw errcode(new Error(`Hash '${hash}' is unknown or not supported. Must be ${types}`), 'ERR_UNSUPPORTED_HASH_TYPE')\n }\n\n const hasher = hashName[hash]\n const dek = forgePbkdf2(\n password,\n salt,\n iterations,\n keySize,\n hasher\n )\n\n return forgeUtil.encode64(dek, null)\n}\n",null,null,"import { randomBytes } from '@libp2p/crypto'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport type { Message, PubSubRPCMessage } from '@libp2p/interface-pubsub'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { codes } from './errors.js'\nimport errcode from 'err-code'\n\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno (): bigint {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`)\n}\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key: Uint8Array, seqno: bigint) => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16')\n\n const msgId = new Uint8Array(key.length + seqnoBytes.length)\n msgId.set(key, 0)\n msgId.set(seqnoBytes, key.length)\n\n return msgId\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data: Uint8Array) => {\n return sha256.encode(data)\n}\n\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a: Set | number[], b: Set | number[]) => {\n let bHas\n if (Array.isArray(b)) {\n bHas = (val: number) => b.includes(val)\n } else {\n bHas = (val: number) => b.has(val)\n }\n\n for (const val of a) {\n if (bHas(val)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Make everything an array\n */\nexport const ensureArray = function (maybeArray: T | T[]) {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray]\n }\n\n return maybeArray\n}\n\nexport const toMessage = (message: PubSubRPCMessage): Message => {\n if (message.from == null) {\n throw errcode(new Error('RPC message was missing from'), codes.ERR_MISSING_FROM)\n }\n\n if (message.sequenceNumber == null || message.from == null || message.signature == null || message.key == null) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n }\n }\n\n return {\n type: 'signed',\n from: peerIdFromBytes(message.from),\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature,\n key: message.key\n }\n}\n\nexport const toRpcMessage = (message: Message): PubSubRPCMessage => {\n if (message.type === 'signed') {\n return {\n from: message.from.multihash.bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n key: message.key\n }\n }\n\n return {\n data: message.data,\n topic: message.topic\n }\n}\n\nexport const bigIntToBytes = (num: bigint): Uint8Array => {\n let str = num.toString(16)\n\n if (str.length % 2 !== 0) {\n str = `0${str}`\n }\n\n return uint8ArrayFromString(str, 'base16')\n}\n\nexport const bigIntFromBytes = (num: Uint8Array): bigint => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`)\n}\n",null,null,"\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n","import { AbortError } from './abort-error.js'\nimport { getIterator } from 'get-iterator'\nimport type { Duplex, Source, Sink } from 'it-stream-types'\n\nexport interface Options {\n onReturnError?: (err: Error) => void\n onAbort?: (source: Source) => void\n abortMessage?: string\n abortCode?: string\n returnOnAbort?: boolean\n}\n\n// Wrap an iterator to make it abortable, allow cleanup when aborted via onAbort\nexport function abortableSource (source: Source, signal: AbortSignal, options?: Options) {\n const opts: Options = options ?? {}\n const iterator = getIterator(source)\n\n async function * abortable () {\n let nextAbortHandler: (() => void) | null\n const abortHandler = () => {\n if (nextAbortHandler != null) nextAbortHandler()\n }\n\n signal.addEventListener('abort', abortHandler)\n\n while (true) {\n let result: IteratorResult\n try {\n if (signal.aborted) {\n const { abortMessage, abortCode } = opts\n throw new AbortError(abortMessage, abortCode)\n }\n\n const abort = new Promise((resolve, reject) => { // eslint-disable-line no-loop-func\n nextAbortHandler = () => {\n const { abortMessage, abortCode } = opts\n reject(new AbortError(abortMessage, abortCode))\n }\n })\n\n // Race the iterator and the abort signals\n result = await Promise.race([abort, iterator.next()])\n nextAbortHandler = null\n } catch (err: any) {\n signal.removeEventListener('abort', abortHandler)\n\n // Might not have been aborted by a known signal\n const isKnownAborter = err.type === 'aborted' && signal.aborted\n\n if (isKnownAborter && (opts.onAbort != null)) {\n // Do any custom abort handling for the iterator\n await opts.onAbort(source)\n }\n\n // End the iterator if it is a generator\n if (typeof iterator.return === 'function') {\n try {\n const p = iterator.return()\n\n if (p instanceof Promise) { // eslint-disable-line max-depth\n p.catch(err => {\n if (opts.onReturnError != null) {\n opts.onReturnError(err)\n }\n })\n }\n } catch (err: any) {\n if (opts.onReturnError != null) { // eslint-disable-line max-depth\n opts.onReturnError(err)\n }\n }\n }\n\n if (isKnownAborter && opts.returnOnAbort === true) {\n return\n }\n\n throw err\n }\n\n if (result.done === true) {\n break\n }\n\n yield result.value\n }\n\n signal.removeEventListener('abort', abortHandler)\n }\n\n return abortable()\n}\n\nexport function abortableSink (sink: Sink, signal: AbortSignal, options?: Options): Sink {\n return (source: Source) => sink(abortableSource(source, signal, options))\n}\n\nexport function abortableDuplex > (duplex: Duplex, signal: AbortSignal, options?: Options) {\n return {\n sink: abortableSink(duplex.sink, signal, {\n ...options,\n onAbort: undefined\n }),\n source: abortableSource(duplex.source, signal, options)\n }\n}\n\nexport { AbortError }\nexport { abortableSink as abortableTransform }\n","\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator (obj: AsyncIterable): AsyncIterator\nexport function getIterator (obj: AsyncIterator): AsyncIterator\nexport function getIterator (obj: Iterable): Iterator\nexport function getIterator (obj: Iterator): Iterator\nexport function getIterator (obj: any): AsyncIterator | Iterator \nexport function getIterator (obj: any): AsyncIterator | Iterator {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]()\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]()\n }\n if (typeof obj.next === 'function') {\n return obj // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable')\n}\n","import { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\ntype Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number) {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable {\n private bufs: Uint8Array[]\n public length: number\n\n constructor (...data: Appendable[]) {\n // Define symbol\n Object.defineProperty(this, symbol, { value: true })\n\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] () {\n yield * this.bufs\n }\n\n get byteLength () {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]) {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]) {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]) {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number) {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number) {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = bufs\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number) {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: [...this.bufs], length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport default function accessor (buf: Uint8Array | Uint8ArrayList) {\n if (buf instanceof Uint8Array) {\n return {\n get (index: number) {\n return buf[index]\n },\n\n set (index: number, value: number) {\n buf[index] = value\n }\n }\n }\n\n return {\n get (index: number) {\n return buf.get(index)\n },\n\n set (index: number, value: number) {\n buf.set(index, value)\n }\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from 'byte-access'\n\nconst TWO_32 = 4294967296\n\nexport class LongBits {\n public hi: number\n public lo: number\n\n constructor (hi: number = 0, lo: number = 0) {\n this.hi = hi\n this.lo = lo\n }\n\n /**\n * Returns these hi/lo bits as a BigInt\n */\n toBigInt (unsigned?: boolean): bigint {\n if (unsigned === true) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Returns these hi/lo bits as a Number - this may overflow, toBigInt\n * should be preferred\n */\n toNumber (unsigned?: boolean): number {\n return Number(this.toBigInt(unsigned))\n }\n\n /**\n * ZigZag decode a LongBits object\n */\n zzDecode () {\n const mask = -(this.lo & 1)\n const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n const hi = (this.hi >>> 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n /**\n * ZigZag encode a LongBits object\n */\n zzEncode () {\n const mask = this.hi >> 31\n const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n const lo = (this.lo << 1 ^ mask) >>> 0\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Encode a LongBits object as a varint byte array\n */\n toBytes (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n const access = accessor(buf)\n\n while (this.hi > 0) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0\n this.hi >>>= 7\n }\n\n while (this.lo > 127) {\n access.set(offset++, this.lo & 127 | 128)\n this.lo = this.lo >>> 7\n }\n\n access.set(offset++, this.lo)\n }\n\n /**\n * Parse a LongBits object from a BigInt\n */\n static fromBigInt (value: bigint) {\n if (value === 0n) {\n return new LongBits()\n }\n\n const negative = value < 0\n\n if (negative) {\n value = -value\n }\n\n let hi = Number(value >> 32n) | 0\n let lo = Number(value - (BigInt(hi) << 32n)) | 0\n\n if (negative) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > TWO_32) {\n lo = 0\n\n if (++hi > TWO_32) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Parse a LongBits object from a Number\n */\n static fromNumber (value: number) {\n if (value === 0) {\n return new LongBits()\n }\n\n const sign = value < 0\n\n if (sign) {\n value = -value\n }\n\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n\n if (++lo > 4294967295) {\n lo = 0\n\n if (++hi > 4294967295) {\n hi = 0\n }\n }\n }\n\n return new LongBits(hi, lo)\n }\n\n /**\n * Parse a LongBits object from a varint byte array\n */\n static fromBytes (buf: Uint8ArrayList | Uint8Array, offset: number = 0) {\n const access = accessor(buf)\n\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits()\n let i = 0\n\n if (buf.length - offset > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n\n // 5th\n bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0\n bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n\n i = 0\n } else {\n for (; i < 4; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 1st..4th\n bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n if (buf.length - offset > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n } else if (offset < buf.byteLength) {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (offset >= buf.length) {\n throw RangeError(`index out of range: ${offset} > ${buf.length}`)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0\n\n if (access.get(offset++) < 128) {\n return bits\n }\n }\n }\n\n /* istanbul ignore next */\n throw RangeError('invalid varint encoding')\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport { LongBits } from 'longbits'\nimport { allocUnsafe } from 'uint8arrays/alloc'\n\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\nconst N8 = Math.pow(2, 56)\nconst N9 = Math.pow(2, 63)\n\ninterface VarintCodec {\n encodingLength: (value: number) => number\n encode: ((value: number) => Uint8Array) & ((value: number, buf: Uint8Array, offset?: number) => Uint8Array) & ((value: number, buf: Uint8ArrayList, offset?: number) => Uint8ArrayList)\n decode: (buf: Uint8ArrayList | Uint8Array, offset?: number) => number\n}\n\nexport const unsigned: VarintCodec = {\n encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (value < N8) {\n return 8\n }\n\n if (value < N9) {\n return 9\n }\n\n return 10\n },\n\n encode (value: number, buf?: any, offset: number = 0) {\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n if (buf == null) {\n buf = allocUnsafe(unsigned.encodingLength(value))\n }\n\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(true)\n }\n}\n\nexport const signed: VarintCodec = {\n encodingLength (value: number): number {\n if (value < 0) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(signed.encodingLength(value))\n }\n\n if (value < 0) {\n LongBits.fromNumber(value).toBytes(buf, offset)\n\n return buf\n }\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n return LongBits.fromBytes(buf, offset).toNumber(false)\n }\n}\n\nexport const zigzag: VarintCodec = {\n encodingLength (value: number): number {\n return unsigned.encodingLength(value >= 0 ? value * 2 : value * -2 - 1)\n },\n\n // @ts-expect-error\n encode (value: any, buf?: any, offset?: any) {\n value = value >= 0 ? value * 2 : (value * -2) - 1\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0): number {\n const value = unsigned.decode(buf, offset)\n\n return (value & 1) !== 0 ? (value + 1) / -2 : value / 2\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport type { LengthEncoderFunction } from './index.js'\nimport type { Source, Transform } from 'it-stream-types'\nimport { allocUnsafe } from './alloc.js'\n\ninterface EncoderOptions {\n lengthEncoder?: LengthEncoderFunction\n}\n\nconst defaultEncoder: LengthEncoderFunction = (length) => {\n const lengthLength = unsigned.encodingLength(length)\n const lengthBuf = allocUnsafe(lengthLength)\n\n unsigned.encode(length, lengthBuf)\n\n defaultEncoder.bytes = lengthLength\n\n return lengthBuf\n}\ndefaultEncoder.bytes = 0\n\nexport function encode (options?: EncoderOptions): Transform {\n options = options ?? {}\n\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n const encoder = async function * (source: Source): Source {\n for await (const chunk of source) {\n // length + data\n const length = encodeLength(chunk.byteLength)\n\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length\n } else {\n yield * length\n }\n\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk\n } else {\n yield * chunk\n }\n }\n }\n\n return encoder\n}\n\nencode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {\n options = options ?? {}\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n\n return new Uint8ArrayList(\n encodeLength(chunk.byteLength),\n chunk\n )\n}\n","\nexport function alloc (len: number) {\n return new Uint8Array(len)\n}\n\nexport function allocUnsafe (len: number) {\n if (globalThis?.Buffer?.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n","/* eslint max-depth: [\"error\", 6] */\n\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport errCode from 'err-code'\nimport type { LengthDecoderFunction } from './index.js'\nimport type { Reader } from 'it-reader'\nimport type { Source, Transform } from 'it-stream-types'\n\nexport interface ReadState {\n dataLength: number\n}\n\nexport interface DecoderOptions {\n lengthDecoder?: LengthDecoderFunction\n onData?: (data: Uint8ArrayList) => void\n onLength?: (length: number) => void\n maxLengthLength?: number\n maxDataLength?: number\n}\n\nexport interface ReadResult {\n mode: string\n chunk?: Uint8ArrayList\n buffer: Uint8ArrayList\n state?: ReadState\n data?: Uint8ArrayList\n}\n\n// Maximum length of the length section of the message\nexport const MAX_LENGTH_LENGTH = 8 // Varint.encode(Number.MAX_SAFE_INTEGER).length\n// Maximum length of the data section of the message\nexport const MAX_DATA_LENGTH = 1024 * 1024 * 4\n\nenum ReadMode {\n LENGTH,\n DATA\n}\n\nconst defaultDecoder: LengthDecoderFunction = (buf) => {\n const length = unsigned.decode(buf)\n defaultDecoder.bytes = unsigned.encodingLength(length)\n\n return length\n}\ndefaultDecoder.bytes = 0\n\nexport function decode (options?: DecoderOptions): Transform {\n const decoder = async function * (source: Source): Source {\n const buffer = new Uint8ArrayList()\n let mode = ReadMode.LENGTH\n let dataLength = -1\n\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n for await (const buf of source) {\n buffer.append(buf)\n\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer)\n\n if (dataLength < 0) {\n throw errCode(new Error('invalid message length'), 'ERR_INVALID_MSG_LENGTH')\n }\n\n if (dataLength > maxDataLength) {\n throw errCode(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG')\n }\n\n const dataLengthLength = lengthDecoder.bytes\n buffer.consume(dataLengthLength)\n\n if (options?.onLength != null) {\n options.onLength(dataLength)\n }\n\n mode = ReadMode.DATA\n } catch (err: any) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw errCode(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG')\n }\n\n break\n }\n\n throw err\n }\n }\n\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break\n }\n\n const data = buffer.sublist(0, dataLength)\n buffer.consume(dataLength)\n\n if (options?.onData != null) {\n options.onData(data)\n }\n\n yield data\n\n mode = ReadMode.LENGTH\n }\n }\n }\n\n if (buffer.byteLength > 0) {\n throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF')\n }\n }\n\n return decoder\n}\n\n/**\n * @param {*} reader\n * @param {import('./types').DecoderOptions} [options]\n * @returns\n */\ndecode.fromReader = (reader: Reader, options?: DecoderOptions) => {\n let byteLength = 1 // Read single byte chunks until the length is known\n\n const varByteSource = (async function * () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength)\n\n if (done === true) {\n return\n }\n\n if (value != null) {\n yield value\n }\n } catch (err: any) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null }\n }\n throw err\n } finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1\n }\n }\n }())\n\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l: number) => { byteLength = l }\n return decode({\n ...(options ?? {}),\n onLength\n })(varByteSource)\n}\n",null,null,null,"import {\n GossipSub,\n GossipsubMessage,\n GossipsubOpts,\n} from \"@chainsafe/libp2p-gossipsub\";\nimport {\n PeerIdStr,\n TopicStr,\n} from \"@chainsafe/libp2p-gossipsub/dist/src/types\";\nimport { SignaturePolicy } from \"@chainsafe/libp2p-gossipsub/types\";\nimport debug from \"debug\";\n\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport * as constants from \"./constants\";\n\nconst dbg = debug(\"waku:relay\");\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * One and only one pubsub topic is used by Waku. This is used by:\n * - WakuRelay to receive, route and send messages,\n * - WakuLightPush to send messages,\n * - WakuStore to retrieve messages.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n decryptionKeys?: Array;\n}\n\n/**\n * Implements the [Waku v2 Relay protocol](https://rfc.vac.dev/spec/11/).\n * Must be passed as a `pubsub` module to a `Libp2p` instance.\n *\n * @implements {require('libp2p-interfaces/src/pubsub')}\n */\nexport class WakuRelay extends GossipSub {\n pubSubTopic: string;\n public static multicodec: string = constants.RelayCodecs[0];\n\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n /**\n * observers called when receiving new message.\n * Observers under key `\"\"` are always called.\n */\n public observers: {\n [contentTopic: string]: Set<(message: WakuMessage) => void>;\n };\n\n constructor(options?: Partial) {\n options = Object.assign(options ?? {}, {\n // Ensure that no signature is included nor expected in the messages.\n globalSignaturePolicy: SignaturePolicy.StrictNoSign,\n fallbackToFloodsub: false,\n });\n super(options);\n this.multicodecs = constants.RelayCodecs;\n\n this.observers = {};\n this.decryptionKeys = new Map();\n\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n\n options?.decryptionKeys?.forEach((key) => {\n this.addDecryptionKey(key);\n });\n }\n\n /**\n * Mounts the gossipsub protocol onto the libp2p node\n * and subscribes to the default topic.\n *\n * @override\n * @returns {void}\n */\n public async start(): Promise {\n await super.start();\n this.subscribe(this.pubSubTopic);\n }\n\n /**\n * Send Waku message.\n *\n * @param {WakuMessage} message\n * @returns {Promise}\n */\n public async send(message: WakuMessage): Promise {\n const msg = message.encode();\n await this.publish(this.pubSubTopic, msg);\n }\n\n /**\n * Register a decryption key to attempt decryption of received messages.\n * This can either be a private key for asymmetric encryption or a symmetric\n * key. `WakuRelay` will attempt to decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**\n * Delete a decryption key that was used to attempt decryption of received\n * messages.\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n /**\n * Register an observer of new messages received via waku relay\n *\n * @param callback called when a new message is received via waku relay\n * @param contentTopics Content Topics for which the callback with be called,\n * all of them if undefined, [] or [\"\",..] is passed.\n * @returns {void}\n */\n addObserver(\n callback: (message: WakuMessage) => void,\n contentTopics: string[] = []\n ): void {\n if (contentTopics.length === 0) {\n if (!this.observers[\"\"]) {\n this.observers[\"\"] = new Set();\n }\n this.observers[\"\"].add(callback);\n } else {\n contentTopics.forEach((contentTopic) => {\n if (!this.observers[contentTopic]) {\n this.observers[contentTopic] = new Set();\n }\n this.observers[contentTopic].add(callback);\n });\n }\n }\n\n /**\n * Remove an observer of new messages received via waku relay.\n * Useful to ensure the same observer is not registered several time\n * (e.g when loading React components)\n */\n deleteObserver(\n callback: (message: WakuMessage) => void,\n contentTopics: string[] = []\n ): void {\n if (contentTopics.length === 0) {\n if (this.observers[\"\"]) {\n this.observers[\"\"].delete(callback);\n }\n } else {\n contentTopics.forEach((contentTopic) => {\n if (this.observers[contentTopic]) {\n this.observers[contentTopic].delete(callback);\n }\n });\n }\n }\n\n /**\n * Subscribe to a pubsub topic and start emitting Waku messages to observers.\n *\n * @override\n */\n subscribe(pubSubTopic: string): void {\n this.addEventListener(\n \"gossipsub:message\",\n (event: CustomEvent) => {\n if (event.detail.msg.topic === pubSubTopic) {\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n dbg(`Message received on ${pubSubTopic}`);\n WakuMessage.decode(event.detail.msg.data, decryptionKeys)\n .then((wakuMsg) => {\n if (!wakuMsg) {\n dbg(\"Failed to decode Waku Message\");\n return;\n }\n\n if (this.observers[\"\"]) {\n this.observers[\"\"].forEach((callbackFn) => {\n callbackFn(wakuMsg);\n });\n }\n if (wakuMsg.contentTopic) {\n if (this.observers[wakuMsg.contentTopic]) {\n this.observers[wakuMsg.contentTopic].forEach((callbackFn) => {\n callbackFn(wakuMsg);\n });\n }\n }\n })\n .catch((e) => {\n dbg(\"Failed to decode Waku Message\", e);\n });\n }\n }\n );\n\n super.subscribe(pubSubTopic);\n }\n\n getMeshPeers(topic?: TopicStr): PeerIdStr[] {\n return super.getMeshPeers(topic ?? this.pubSubTopic);\n }\n}\n","export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n","import { Reader, reader } from 'it-reader'\nimport { pushable } from 'it-pushable'\nimport defer from 'p-defer'\nimport type { Duplex, Source } from 'it-stream-types'\nimport type { Pushable } from 'it-pushable'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Handshake {\n reader: Reader\n writer: Pushable\n stream: Duplex\n rest: () => Source\n write: (data: TSink) => void\n read: () => Promise\n}\n\n// Convert a duplex stream into a reader and writer and rest stream\nexport function handshake (stream: Duplex): Handshake {\n const writer = pushable() // Write bytes on demand to the sink\n const source = reader(stream.source) // Read bytes on demand from the source\n\n // Waits for a source to be passed to the rest stream's sink\n const sourcePromise = defer>()\n let sinkErr: Error\n\n const sinkPromise = stream.sink((async function * () {\n yield * writer\n const source = await sourcePromise.promise\n yield * source\n })())\n\n sinkPromise.catch(err => {\n sinkErr = err\n })\n\n const rest: Duplex = {\n sink: async source => {\n if (sinkErr != null) {\n return await Promise.reject(sinkErr)\n }\n\n sourcePromise.resolve(source)\n return await sinkPromise\n },\n source\n }\n\n return {\n reader: source,\n writer,\n stream: rest,\n rest: () => writer.end(),\n write: writer.push,\n read: async () => {\n const res = await source.next()\n\n if (res.value != null) {\n return res.value\n }\n }\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport type { Source } from 'it-stream-types'\n\nexport interface Reader extends AsyncGenerator {\n next: (...args: [] | [number | undefined]) => Promise>\n}\n\nexport function reader (source: Source) {\n const reader: Reader = (async function * (): AsyncGenerator {\n // @ts-expect-error first yield in stream is ignored\n let bytes: number | undefined = yield // Allows us to receive 8 when reader.next(8) is called\n let bl = new Uint8ArrayList()\n\n for await (const chunk of source) {\n if (bytes == null) {\n bl.append(chunk)\n bytes = yield bl\n bl = new Uint8ArrayList()\n continue\n }\n\n bl.append(chunk)\n\n while (bl.length >= bytes) {\n const data = bl.sublist(0, bytes)\n bl.consume(bytes)\n bytes = yield data\n\n // If we no longer want a specific byte length, we yield the rest now\n if (bytes == null) {\n if (bl.length > 0) {\n bytes = yield bl\n bl = new Uint8ArrayList()\n }\n break // bytes is null and/or no more buffer to yield\n }\n }\n }\n\n // Consumer wants more bytes but the source has ended and our buffer\n // is not big enough to satisfy.\n if (bytes != null) {\n throw Object.assign(\n new Error(`stream ended before ${bytes} bytes became available`),\n { code: 'ERR_UNDER_READ', buffer: bl }\n )\n }\n })()\n\n void reader.next()\n return reader\n}\n","import { handshake } from 'it-handshake'\nimport * as lp from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\ninterface Decoder {\n (data: Uint8Array | Uint8ArrayList): T\n}\n\ninterface Encoder {\n (data: T): Uint8Array\n}\n\nexport interface ProtobufStream {\n read: (bytes?: number) => Promise\n readLP: () => Promise\n readPB: (proto: { decode: Decoder }) => Promise\n write: (input: Uint8Array | Uint8ArrayList) => void\n writeLP: (input: Uint8Array | Uint8ArrayList) => void\n writePB: (data: Uint8Array | Uint8ArrayList, proto: {encode: Encoder}) => void\n pb: (proto: {encode: Encoder, decode: Decoder }) => {read: () => Promise, write: (d: Uint8Array | Uint8ArrayList) => void}\n\n // return vanilla duplex\n unwrap: () => Duplex\n}\n\nexport interface Opts {\n // encoding opts\n poolSize: number\n minPoolSize: number\n lengthEncoder: lp.LengthEncoderFunction\n\n // decoding opts\n lengthDecoder: lp.LengthDecoderFunction\n maxLengthLength: number\n maxDataLength: number\n}\n\nexport function pbStream (duplex: Duplex, opts = {}): ProtobufStream {\n const shake = handshake(duplex)\n const lpReader = lp.decode.fromReader(\n shake.reader,\n opts\n )\n\n const W: ProtobufStream = {\n read: async (bytes) => {\n // just read\n const { value } = await shake.reader.next(bytes)\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n return value\n },\n readLP: async () => {\n // read, decode\n // @ts-expect-error .next is part of the generator interface\n const { value } = await lpReader.next()\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n return value\n },\n readPB: async (proto) => {\n // readLP, decode\n const value = await W.readLP()\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n // Is this a buffer?\n const buf = value instanceof Uint8Array ? value : value.slice()\n\n return proto.decode(buf)\n },\n write: (data) => {\n // just write\n if (data instanceof Uint8Array) {\n shake.writer.push(data)\n } else {\n shake.writer.push(data.slice())\n }\n },\n writeLP: (data) => {\n // encode, write\n W.write(lp.encode.single(data, opts))\n },\n writePB: (data, proto) => {\n // encode, writeLP\n W.writeLP(proto.encode(data))\n },\n pb: (proto) => {\n return {\n read: async () => await W.readPB(proto),\n write: (d) => W.writePB(d, proto)\n }\n },\n unwrap: () => {\n // returns vanilla duplex again, terminates all reads/writes from this object\n shake.rest()\n return shake.stream\n }\n }\n\n return W\n}\n","import defer from 'p-defer'\nimport type { Source, Duplex } from 'it-stream-types'\n\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair (): Duplex {\n const deferred = defer>()\n let piped = false\n\n return {\n sink: async source => {\n if (piped) {\n throw new Error('already piped')\n }\n\n piped = true\n deferred.resolve(source)\n },\n source: (async function * () {\n const source = await deferred.promise\n\n yield * source\n }())\n }\n}\n","export const NOISE_MSG_MAX_LENGTH_BYTES = 65535\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16\n\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS)\n","import { HKDF } from '@stablelib/hkdf'\nimport * as x25519 from '@stablelib/x25519'\nimport { SHA256, hash } from '@stablelib/sha256'\nimport { ChaCha20Poly1305 } from '@stablelib/chacha20poly1305'\nimport type { bytes32, bytes } from '../@types/basic.js'\nimport type { Hkdf } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport type { ICryptoInterface } from '../crypto.js'\n\nexport const stablelib: ICryptoInterface = {\n hashSHA256 (data: Uint8Array): Uint8Array {\n return hash(data)\n },\n\n getHKDF (ck: bytes32, ikm: Uint8Array): Hkdf {\n const hkdf = new HKDF(SHA256, ikm, ck)\n const okmU8Array = hkdf.expand(96)\n const okm = okmU8Array\n\n const k1 = okm.subarray(0, 32)\n const k2 = okm.subarray(32, 64)\n const k3 = okm.subarray(64, 96)\n\n return [k1, k2, k3]\n },\n\n generateX25519KeyPair (): KeyPair {\n const keypair = x25519.generateKeyPair()\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair {\n const keypair = x25519.generateKeyPairFromSeed(seed)\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519SharedKey (privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array {\n return x25519.sharedKey(privateKey, publicKey)\n },\n\n chaCha20Poly1305Encrypt (plaintext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.seal(nonce, plaintext, ad)\n },\n\n chaCha20Poly1305Decrypt (ciphertext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes | null {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.open(nonce, ciphertext, ad)\n }\n}\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { bytes } from './@types/basic.js'\nimport type { MessageBuffer } from './@types/handshake.js'\nimport type { LengthDecoderFunction, LengthEncoderFunction } from 'it-length-prefixed'\n\nconst allocUnsafe = (len: number): Uint8Array => {\n if (globalThis.Buffer) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n\nexport const uint16BEEncode: LengthEncoderFunction = (value: number) => {\n const target = allocUnsafe(2)\n new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)\n return target\n}\nuint16BEEncode.bytes = 2\n\nexport const uint16BEDecode: LengthDecoderFunction = (data: Uint8Array | Uint8ArrayList): number => {\n if (data.length < 2) throw RangeError('Could not decode int16BE')\n\n if (data instanceof Uint8Array) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false)\n }\n\n return data.getUint16(0)\n}\nuint16BEDecode.bytes = 2\n\n// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)\n\nexport function encode0 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ciphertext], message.ne.length + message.ciphertext.length)\n}\n\nexport function encode1 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ns, message.ciphertext], message.ne.length + message.ns.length + message.ciphertext.length)\n}\n\nexport function encode2 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ns, message.ciphertext], message.ns.length + message.ciphertext.length)\n}\n\nexport function decode0 (input: bytes): MessageBuffer {\n if (input.length < 32) {\n throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ciphertext: input.subarray(32, input.length),\n ns: new Uint8Array(0)\n }\n}\n\nexport function decode1 (input: bytes): MessageBuffer {\n if (input.length < 80) {\n throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ns: input.subarray(32, 80),\n ciphertext: input.subarray(80, input.length)\n }\n}\n\nexport function decode2 (input: bytes): MessageBuffer {\n if (input.length < 48) {\n throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')\n }\n\n return {\n ne: new Uint8Array(0),\n ns: input.subarray(0, 48),\n ciphertext: input.subarray(48, input.length)\n }\n}\n","\nexport function alloc (len: number) {\n return new Uint8Array(len)\n}\n\nexport function allocUnsafe (len: number) {\n if (globalThis?.Buffer?.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeFunction {\n (value: T): Uint8Array | Uint8ArrayList\n}\n\nexport interface DecodeFunction {\n (buf: Uint8ArrayList, offset: number): T\n}\n\nexport interface EncodingLengthFunction {\n (value: T): number\n}\n\nexport interface Codec {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction\n decode: DecodeFunction\n encodingLength: EncodingLengthFunction\n}\n\nexport function createCodec (name: string, type: CODEC_TYPES, encode: EncodeFunction, decode: DecodeFunction, encodingLength: EncodingLengthFunction): Codec {\n return {\n name,\n type,\n encode,\n decode,\n encodingLength\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function boolEncodingLength () {\n return 1\n}\n\nconst encode: EncodeFunction = function boolEncode (value) {\n return Uint8Array.from([value ? 1 : 0])\n}\n\nconst decode: DecodeFunction = function boolDecode (buffer, offset) {\n return buffer.get(offset) > 0\n}\n\nexport const bool = createCodec('bool', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function bytesEncodingLength (val) {\n const len = val.byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function bytesEncode (val) {\n return new Uint8ArrayList(\n unsigned.encode(val.byteLength),\n val\n )\n}\n\nconst decode: DecodeFunction = function bytesDecode (buf, offset) {\n const byteLength = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(byteLength)\n\n return buf.subarray(offset, offset + byteLength)\n}\n\nexport const bytes = createCodec('bytes', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function doubleEncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function doubleEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setFloat64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function doubleDecode (buf, offset) {\n return buf.getFloat64(offset, true)\n}\n\nexport const double = createCodec('double', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function fixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function fixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function fixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const fixed32 = createCodec('fixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return 8\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const fixed64 = createCodec('fixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function floatEncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function floatEncode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(1)))\n buf.setFloat32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function floatDecode (buf, offset) {\n return buf.getFloat32(offset, true)\n}\n\nexport const float = createCodec('float', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { signed } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int32EncodingLength (val) {\n if (val < 0) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int32Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n\n return signed.encode(val, buf)\n}\n\nconst decode: DecodeFunction = function int32Decode (buf, offset) {\n return signed.decode(buf, offset) | 0\n}\n\nexport const int32 = createCodec('int32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import type { Uint8ArrayList } from 'uint8arraylist'\nimport accessor from 'byte-access'\nimport { LongBits } from 'longbits'\nimport { allocUnsafe } from 'uint8arrays/alloc'\n\nconst LIMIT = 0x7fn\n\ninterface BigVarintCodec {\n encodingLength: (value: bigint) => number\n encode: ((value: bigint) => Uint8Array) & ((value: bigint, buf: Uint8Array, offset?: number) => Uint8Array) & ((value: bigint, buf: Uint8ArrayList, offset?: number) => Uint8ArrayList)\n decode: (buf: Uint8ArrayList | Uint8Array, offset?: number) => bigint\n}\n\n// https://github.com/joeltg/big-varint/blob/main/src/unsigned.ts\nexport const unsigned: BigVarintCodec = {\n encodingLength (value: bigint): number {\n let i = 0\n for (; value >= 0x80n; i++) {\n value >>= 7n\n }\n return i + 1\n },\n\n encode (value: any, buf?: any, offset: any = 0) {\n if (buf == null) {\n buf = allocUnsafe(unsigned.encodingLength(value))\n }\n\n const access = accessor(buf)\n\n while (LIMIT < value) {\n access.set(offset++, Number(value & LIMIT) | 0x80)\n value >>= 7n\n }\n\n access.set(offset, Number(value))\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(true)\n }\n}\n\nexport const signed: BigVarintCodec = {\n encodingLength (value: bigint): number {\n if (value < 0n) {\n return 10 // 10 bytes per spec\n }\n\n return unsigned.encodingLength(value)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(signed.encodingLength(value))\n }\n\n if (value < 0n) {\n LongBits.fromBigInt(value).toBytes(buf, offset)\n\n return buf\n }\n\n return unsigned.encode(value, buf, offset)\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).toBigInt(false)\n }\n}\n\nexport const zigzag: BigVarintCodec = {\n encodingLength (value: bigint): number {\n return unsigned.encodingLength(value >= 0 ? value * 2n : value * -2n - 1n)\n },\n\n encode (value: any, buf?: any, offset?: any) {\n if (buf == null) {\n buf = allocUnsafe(zigzag.encodingLength(value))\n }\n\n LongBits.fromBigInt(value).zzEncode().toBytes(buf, offset)\n\n return buf\n },\n\n decode (buf: Uint8ArrayList | Uint8Array, offset = 0) {\n return LongBits.fromBytes(buf, offset).zzDecode().toBigInt(false)\n }\n}\n","import { signed } from 'uint8-varint/big'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n if (val < 0n) {\n return 10 // 10 bytes per spec - https://developers.google.com/protocol-buffers/docs/encoding#signed-ints\n }\n\n return signed.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n const buf = new Uint8Array(encodingLength(val))\n\n return signed.encode(val, buf)\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return signed.decode(buf, offset) | 0n\n}\n\nexport const int64 = createCodec('int64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed32EncodingLength () {\n return 4\n}\n\nconst encode: EncodeFunction = function sfixed32Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setInt32(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed32Decode (buf, offset) {\n return buf.getInt32(offset, true)\n}\n\nexport const sfixed32 = createCodec('sfixed32', CODEC_TYPES.BIT32, encode, decode, encodingLength)\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sfixed64EncodingLength () {\n return 8\n}\n\nconst encode: EncodeFunction = function sfixed64Encode (val) {\n const buf = new Uint8ArrayList(new Uint8Array(encodingLength(val)))\n buf.setBigInt64(0, val, true)\n\n return buf\n}\n\nconst decode: DecodeFunction = function sfixed64Decode (buf, offset) {\n return buf.getBigInt64(offset, true)\n}\n\nexport const sfixed64 = createCodec('sfixed64', CODEC_TYPES.BIT64, encode, decode, encodingLength)\n","import { zigzag } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function sint32EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function svarintEncode (val) {\n return zigzag.encode(val)\n}\n\nconst decode: DecodeFunction = function svarintDecode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint32 = createCodec('sint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { zigzag } from 'uint8-varint/big'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function int64EncodingLength (val) {\n return zigzag.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function int64Encode (val) {\n return zigzag.encode(val)\n}\n\nconst decode: DecodeFunction = function int64Decode (buf, offset) {\n return zigzag.decode(buf, offset)\n}\n\nexport const sint64 = createCodec('sint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from 'uint8-varint'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\n\nconst encodingLength: EncodingLengthFunction = function stringEncodingLength (val) {\n const len = uint8ArrayFromString(val).byteLength\n return unsigned.encodingLength(len) + len\n}\n\nconst encode: EncodeFunction = function stringEncode (val) {\n const asBuf = uint8ArrayFromString(val)\n\n return new Uint8ArrayList(\n unsigned.encode(asBuf.byteLength),\n asBuf\n )\n}\n\nconst decode: DecodeFunction = function stringDecode (buf, offset) {\n const strLen = unsigned.decode(buf, offset)\n offset += unsigned.encodingLength(strLen)\n\n return uint8ArrayToString(buf.subarray(offset, offset + strLen))\n}\n\nexport const string = createCodec('string', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n","import { unsigned } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint32EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint32Encode (val) {\n // val = val < 0 ? val + 4294967296 : val\n\n return unsigned.encode(val)\n}\n\nconst decode: DecodeFunction = function uint32Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n\n // return value > 2147483647 ? value - 4294967296 : value\n}\n\nexport const uint32 = createCodec('uint32', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","import { unsigned } from 'uint8-varint/big'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction } from '../codec.js'\n\nconst encodingLength: EncodingLengthFunction = function uint64EncodingLength (val) {\n return unsigned.encodingLength(val)\n}\n\nconst encode: EncodeFunction = function uint64Encode (val) {\n return unsigned.encode(val)\n}\n\nconst decode: DecodeFunction = function uint64Decode (buf, offset) {\n return unsigned.decode(buf, offset)\n}\n\nexport const uint64 = createCodec('uint64', CODEC_TYPES.VARINT, encode, decode, encodingLength)\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, bytes } from 'protons-runtime'\nimport type { Codec } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport namespace pb {\n export interface NoiseHandshakePayload {\n identityKey: Uint8Array\n identitySig: Uint8Array\n data: Uint8Array\n }\n\n export namespace NoiseHandshakePayload {\n export const codec = (): Codec => {\n return message({\n 1: { name: 'identityKey', codec: bytes },\n 2: { name: 'identitySig', codec: bytes },\n 3: { name: 'data', codec: bytes }\n })\n }\n\n export const encode = (obj: NoiseHandshakePayload): Uint8ArrayList => {\n return encodeMessage(obj, NoiseHandshakePayload.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseHandshakePayload => {\n return decodeMessage(buf, NoiseHandshakePayload.codec())\n }\n }\n}\n","import { unsigned } from 'uint8-varint'\nimport { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, EncodingLengthFunction, Codec } from '../codec.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { FieldDefs, FieldDef } from '../index.js'\nimport { allocUnsafe } from '../utils/alloc.js'\n\nexport interface Factory {\n new (obj: A): T\n}\n\nexport function message (fieldDefs: FieldDefs): Codec {\n const encodingLength: EncodingLengthFunction = function messageEncodingLength (val: Record) {\n let length = 0\n\n for (const fieldDef of Object.values(fieldDefs)) {\n length += fieldDef.codec.encodingLength(val[fieldDef.name])\n }\n\n return unsigned.encodingLength(length) + length\n }\n\n const encode: EncodeFunction> = function messageEncode (val) {\n const bytes = new Uint8ArrayList()\n\n function encodeValue (value: any, fieldNumber: number, fieldDef: FieldDef) {\n if (value == null) {\n if (fieldDef.optional === true) {\n return\n }\n\n throw new Error(`Non optional field \"${fieldDef.name}\" was ${value === null ? 'null' : 'undefined'}`)\n }\n\n const key = (fieldNumber << 3) | fieldDef.codec.type\n const prefix = allocUnsafe(unsigned.encodingLength(key))\n unsigned.encode(key, prefix)\n const encoded = fieldDef.codec.encode(value)\n\n bytes.append(prefix)\n bytes.append(encoded)\n }\n\n for (const [fieldNumberStr, fieldDef] of Object.entries(fieldDefs)) {\n const fieldNumber = parseInt(fieldNumberStr)\n\n if (fieldDef.repeats === true) {\n if (!Array.isArray(val[fieldDef.name])) {\n throw new Error(`Repeating field \"${fieldDef.name}\" was not an array`)\n }\n\n for (const value of val[fieldDef.name]) {\n encodeValue(value, fieldNumber, fieldDef)\n }\n } else {\n encodeValue(val[fieldDef.name], fieldNumber, fieldDef)\n }\n }\n\n const prefix = unsigned.encode(bytes.length)\n\n return new Uint8ArrayList(prefix, bytes)\n }\n\n const decode: DecodeFunction = function messageDecode (buffer, offset) {\n const length = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(length)\n const end = offset + length\n const fields: any = {}\n\n while (offset < end) {\n const key = unsigned.decode(buffer, offset)\n offset += unsigned.encodingLength(key)\n\n const wireType = key & 0x7\n const fieldNumber = key >> 3\n const fieldDef = fieldDefs[fieldNumber]\n let fieldLength = 0\n\n if (wireType === CODEC_TYPES.VARINT) {\n if (fieldDef != null) {\n // use the codec if it is available as this could be a bigint\n const value = fieldDef.codec.decode(buffer, offset)\n fieldLength = fieldDef.codec.encodingLength(value)\n } else {\n const value = unsigned.decode(buffer, offset)\n fieldLength = unsigned.encodingLength(value)\n }\n } else if (wireType === CODEC_TYPES.BIT64) {\n fieldLength = 8\n } else if (wireType === CODEC_TYPES.LENGTH_DELIMITED) {\n const valueLength = unsigned.decode(buffer, offset)\n fieldLength = valueLength + unsigned.encodingLength(valueLength)\n } else if (wireType === CODEC_TYPES.BIT32) {\n fieldLength = 4\n } else if (wireType === CODEC_TYPES.START_GROUP) {\n throw new Error('Unsupported wire type START_GROUP')\n } else if (wireType === CODEC_TYPES.END_GROUP) {\n throw new Error('Unsupported wire type END_GROUP')\n }\n\n if (fieldDef != null) {\n const value = fieldDef.codec.decode(buffer, offset)\n\n if (fieldDef.repeats === true) {\n if (fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n\n fields[fieldDef.name].push(value)\n } else {\n fields[fieldDef.name] = value\n }\n }\n\n offset += fieldLength\n }\n\n // make sure repeated fields have an array if not set\n for (const fieldDef of Object.values(fieldDefs)) {\n if (fieldDef.repeats === true && fields[fieldDef.name] == null) {\n fields[fieldDef.name] = []\n }\n }\n\n return fields\n }\n\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, encodingLength)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from './codec.js'\nimport { unsigned } from 'uint8-varint'\n\nexport function encodeMessage (message: T, codec: Codec): Uint8ArrayList {\n // unwrap root message\n const encoded = codec.encode(message)\n const skip = unsigned.encodingLength(unsigned.decode(encoded))\n\n if (encoded instanceof Uint8Array) {\n return new Uint8ArrayList(encoded.subarray(skip))\n }\n\n return encoded.sublist(skip)\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\nimport type { Codec } from './codec.js'\nimport { allocUnsafe } from './utils/alloc.js'\n\nexport function decodeMessage (buf: Uint8Array | Uint8ArrayList, codec: Codec): T {\n // wrap root message\n const prefix = allocUnsafe(unsigned.encodingLength(buf.byteLength))\n unsigned.encode(buf.byteLength, prefix)\n\n return codec.decode(new Uint8ArrayList(prefix, buf), 0)\n}\n","import { unmarshalPublicKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { bytes } from './@types/basic.js'\nimport { pb } from './proto/payload.js'\n\nconst NoiseHandshakePayloadProto = pb.NoiseHandshakePayload\n\nexport async function getPayload (\n localPeer: PeerId,\n staticPublicKey: bytes,\n earlyData?: bytes\n): Promise {\n const signedPayload = await signPayload(localPeer, getHandshakePayload(staticPublicKey))\n const earlyDataPayload = earlyData ?? new Uint8Array(0)\n\n if (localPeer.publicKey == null) {\n throw new Error('PublicKey was missing from local PeerId')\n }\n\n return createHandshakePayload(\n localPeer.publicKey,\n signedPayload,\n earlyDataPayload\n )\n}\n\nexport function createHandshakePayload (\n libp2pPublicKey: Uint8Array,\n signedPayload: Uint8Array,\n earlyData?: Uint8Array\n): bytes {\n return NoiseHandshakePayloadProto.encode({\n identityKey: libp2pPublicKey,\n identitySig: signedPayload,\n data: earlyData ?? new Uint8Array(0)\n }).subarray()\n}\n\nexport async function signPayload (peerId: PeerId, payload: bytes): Promise {\n if (peerId.privateKey == null) {\n throw new Error('PrivateKey was missing from PeerId')\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return await privateKey.sign(payload)\n}\n\nexport async function getPeerIdFromPayload (payload: pb.NoiseHandshakePayload): Promise {\n return await peerIdFromKeys(payload.identityKey)\n}\n\nexport function decodePayload (payload: bytes|Uint8Array): pb.NoiseHandshakePayload {\n return NoiseHandshakePayloadProto.decode(payload)\n}\n\nexport function getHandshakePayload (publicKey: bytes): bytes {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:')\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length)\n}\n\n/**\n * Verifies signed payload, throws on any irregularities.\n *\n * @param {bytes} noiseStaticKey - owner's noise static key\n * @param {bytes} payload - decoded payload\n * @param {PeerId} remotePeer - owner's libp2p peer ID\n * @returns {Promise} - peer ID of payload owner\n */\nexport async function verifySignedPayload (\n noiseStaticKey: bytes,\n payload: pb.NoiseHandshakePayload,\n remotePeer: PeerId\n): Promise {\n // Unmarshaling from PublicKey protobuf\n const payloadPeerId = await peerIdFromKeys(payload.identityKey)\n if (!payloadPeerId.equals(remotePeer)) {\n throw new Error(\"Peer ID doesn't match libp2p public key.\")\n }\n const generatedPayload = getHandshakePayload(noiseStaticKey)\n\n if (payloadPeerId.publicKey == null) {\n throw new Error('PublicKey was missing from PeerId')\n }\n\n if (payload.identitySig == null) {\n throw new Error('Signature was missing from message')\n }\n\n const publicKey = unmarshalPublicKey(payloadPeerId.publicKey)\n\n const valid = await publicKey.verify(generatedPayload, payload.identitySig)\n\n if (!valid) {\n throw new Error(\"Static key doesn't match to peer that signed payload!\")\n }\n\n return payloadPeerId\n}\n\nexport function isValidPublicKey (pk: bytes): boolean {\n if (!(pk instanceof Uint8Array)) {\n return false\n }\n\n if (pk.length !== 32) {\n return false\n }\n\n return true\n}\n","import { Logger, logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport { DUMP_SESSION_KEYS } from './constants.js'\n\nconst log = logger('libp2p:noise')\n\nexport { log as logger }\n\nlet keyLogger: Logger\nif (DUMP_SESSION_KEYS) {\n keyLogger = log\n} else {\n keyLogger = Object.assign(() => { /* do nothing */ }, {\n enabled: false,\n trace: () => {},\n error: () => {}\n })\n}\n\nexport function logLocalStaticKeys (s: KeyPair): void {\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`)\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`)\n}\n\nexport function logLocalEphemeralKeys (e: KeyPair|undefined): void {\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`)\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`)\n } else {\n keyLogger('Missing local ephemeral keys.')\n }\n}\n\nexport function logRemoteStaticKey (rs: Uint8Array): void {\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs, 'hex')}`)\n}\n\nexport function logRemoteEphemeralKey (re: Uint8Array): void {\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re, 'hex')}`)\n}\n\nexport function logCipherState (session: NoiseSession): void {\n if (session.cs1 && session.cs2) {\n keyLogger(`CIPHER_STATE_1 ${session.cs1.n.getUint64()} ${uint8ArrayToString(session.cs1.k, 'hex')}`)\n keyLogger(`CIPHER_STATE_2 ${session.cs2.n.getUint64()} ${uint8ArrayToString(session.cs2.k, 'hex')}`)\n } else {\n keyLogger('Missing cipher state.')\n }\n}\n","import type { bytes, uint64 } from './@types/basic'\n\nexport const MIN_NONCE = 0\n// For performance reasons, the nonce is represented as a JS `number`\n// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use\n// 4 bytes to store the data for performance reason.\n// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2\n// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.\n// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.\nexport const MAX_NONCE = 0xffffffff\n\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed'\n\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n private n: uint64\n private readonly bytes: bytes\n private readonly view: DataView\n\n constructor (n = MIN_NONCE) {\n this.n = n\n this.bytes = new Uint8Array(12)\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength)\n this.view.setUint32(4, n, true)\n }\n\n increment (): void {\n this.n++\n // Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.\n this.view.setUint32(4, this.n, true)\n }\n\n getBytes (): bytes {\n return this.bytes\n }\n\n getUint64 (): uint64 {\n return this.n\n }\n\n assertValue (): void {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE)\n }\n }\n}\n","import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays'\nimport type { bytes, bytes32 } from '../@types/basic.js'\nimport type { CipherState, MessageBuffer, SymmetricState } from '../@types/handshake.js'\nimport type { ICryptoInterface } from '../crypto.js'\nimport { logger } from '../logger.js'\nimport { Nonce } from '../nonce.js'\n\nexport abstract class AbstractHandshake {\n public crypto: ICryptoInterface\n\n constructor (crypto: ICryptoInterface) {\n this.crypto = crypto\n }\n\n public encryptWithAd (cs: CipherState, ad: Uint8Array, plaintext: Uint8Array): bytes {\n const e = this.encrypt(cs.k, cs.n, ad, plaintext)\n cs.n.increment()\n\n return e\n }\n\n public decryptWithAd (cs: CipherState, ad: Uint8Array, ciphertext: Uint8Array): {plaintext: bytes, valid: boolean} {\n const { plaintext, valid } = this.decrypt(cs.k, cs.n, ad, ciphertext)\n cs.n.increment()\n\n return { plaintext, valid }\n }\n\n // Cipher state related\n protected hasKey (cs: CipherState): boolean {\n return !this.isEmptyKey(cs.k)\n }\n\n protected createEmptyKey (): bytes32 {\n return new Uint8Array(32)\n }\n\n protected isEmptyKey (k: bytes32): boolean {\n const emptyKey = this.createEmptyKey()\n return uint8ArrayEquals(emptyKey, k)\n }\n\n protected encrypt (k: bytes32, n: Nonce, ad: Uint8Array, plaintext: Uint8Array): bytes {\n n.assertValue()\n\n return this.crypto.chaCha20Poly1305Encrypt(plaintext, n.getBytes(), ad, k)\n }\n\n protected encryptAndHash (ss: SymmetricState, plaintext: bytes): bytes {\n let ciphertext\n if (this.hasKey(ss.cs)) {\n ciphertext = this.encryptWithAd(ss.cs, ss.h, plaintext)\n } else {\n ciphertext = plaintext\n }\n\n this.mixHash(ss, ciphertext)\n return ciphertext\n }\n\n protected decrypt (k: bytes32, n: Nonce, ad: bytes, ciphertext: bytes): {plaintext: bytes, valid: boolean} {\n n.assertValue()\n\n const encryptedMessage = this.crypto.chaCha20Poly1305Decrypt(ciphertext, n.getBytes(), ad, k)\n\n if (encryptedMessage) {\n return {\n plaintext: encryptedMessage,\n valid: true\n }\n } else {\n return {\n plaintext: new Uint8Array(0),\n valid: false\n }\n }\n }\n\n protected decryptAndHash (ss: SymmetricState, ciphertext: bytes): {plaintext: bytes, valid: boolean} {\n let plaintext: bytes; let valid = true\n if (this.hasKey(ss.cs)) {\n ({ plaintext, valid } = this.decryptWithAd(ss.cs, ss.h, ciphertext))\n } else {\n plaintext = ciphertext\n }\n\n this.mixHash(ss, ciphertext)\n return { plaintext, valid }\n }\n\n protected dh (privateKey: bytes32, publicKey: bytes32): bytes32 {\n try {\n const derivedU8 = this.crypto.generateX25519SharedKey(privateKey, publicKey)\n\n if (derivedU8.length === 32) {\n return derivedU8\n }\n\n return derivedU8.subarray(0, 32)\n } catch (e) {\n const err = e as Error\n logger(err.message)\n return new Uint8Array(32)\n }\n }\n\n protected mixHash (ss: SymmetricState, data: bytes): void {\n ss.h = this.getHash(ss.h, data)\n }\n\n protected getHash (a: Uint8Array, b: Uint8Array): bytes32 {\n const u = this.crypto.hashSHA256(uint8ArrayConcat([a, b], a.length + b.length))\n return u\n }\n\n protected mixKey (ss: SymmetricState, ikm: bytes32): void {\n const [ck, tempK] = this.crypto.getHKDF(ss.ck, ikm)\n ss.cs = this.initializeKey(tempK)\n ss.ck = ck\n }\n\n protected initializeKey (k: bytes32): CipherState {\n return { k, n: new Nonce() }\n }\n\n // Symmetric state related\n\n protected initializeSymmetric (protocolName: string): SymmetricState {\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8')\n const h = this.hashProtocolName(protocolNameBytes)\n\n const ck = h\n const key = this.createEmptyKey()\n const cs: CipherState = this.initializeKey(key)\n\n return { cs, ck, h }\n }\n\n protected hashProtocolName (protocolName: Uint8Array): bytes32 {\n if (protocolName.length <= 32) {\n const h = new Uint8Array(32)\n h.set(protocolName)\n return h\n } else {\n return this.getHash(protocolName, new Uint8Array(0))\n }\n }\n\n protected split (ss: SymmetricState): {cs1: CipherState, cs2: CipherState} {\n const [tempk1, tempk2] = this.crypto.getHKDF(ss.ck, new Uint8Array(0))\n const cs1 = this.initializeKey(tempk1)\n const cs2 = this.initializeKey(tempk2)\n\n return { cs1, cs2 }\n }\n\n protected writeMessageRegular (cs: CipherState, payload: bytes): MessageBuffer {\n const ciphertext = this.encryptWithAd(cs, new Uint8Array(0), payload)\n const ne = this.createEmptyKey()\n const ns = new Uint8Array(0)\n\n return { ne, ns, ciphertext }\n }\n\n protected readMessageRegular (cs: CipherState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n return this.decryptWithAd(cs, new Uint8Array(0), message.ciphertext)\n }\n}\n","import type { bytes, bytes32 } from '../@types/basic.js'\nimport type { CipherState, HandshakeState, MessageBuffer, NoiseSession } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport { isValidPublicKey } from '../utils.js'\nimport { AbstractHandshake } from './abstract-handshake.js'\n\nexport class IK extends AbstractHandshake {\n public initSession (initiator: boolean, prologue: bytes32, s: KeyPair, rs: bytes32): NoiseSession {\n const psk = this.createEmptyKey()\n\n let hs\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk)\n } else {\n hs = this.initializeResponder(prologue, s, rs, psk)\n }\n\n return {\n hs,\n i: initiator,\n mc: 0\n }\n }\n\n public sendMessage (session: NoiseSession, message: bytes): MessageBuffer {\n let messageBuffer: MessageBuffer\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message)\n } else if (session.mc === 1) {\n const { messageBuffer: mb, h, cs1, cs2 } = this.writeMessageB(session.hs, message)\n messageBuffer = mb\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n } else if (session.mc > 1) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs1, message)\n } else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs2, message)\n }\n } else {\n throw new Error('Session invalid.')\n }\n\n session.mc++\n return messageBuffer\n }\n\n public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n let plaintext = new Uint8Array(0); let valid = false\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message))\n }\n if (session.mc === 1) {\n const { plaintext: pt, valid: v, h, cs1, cs2 } = this.readMessageB(session.hs, message)\n plaintext = pt\n valid = v\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n }\n session.mc++\n return { plaintext, valid }\n }\n\n private writeMessageA (hs: HandshakeState, payload: bytes): MessageBuffer {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.rs))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageB (hs: HandshakeState, payload: bytes): { messageBuffer: MessageBuffer, cs1: CipherState, cs2: CipherState, h: bytes} {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n const ns = this.createEmptyKey()\n const messageBuffer: MessageBuffer = { ne, ns, ciphertext }\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { messageBuffer, cs1, cs2, h: hs.ss.h }\n }\n\n private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.rs))\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n return { plaintext, valid: (valid1 && valid2) }\n }\n\n private readMessageB (hs: HandshakeState, message: MessageBuffer): {h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n if (!hs.e) {\n throw new Error('Handshake state should contain ephemeral key by now.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const { plaintext, valid } = this.decryptAndHash(hs.ss, message.ciphertext)\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, valid, plaintext, cs1, cs2 }\n }\n\n private initializeInitiator (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_IK_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n this.mixHash(ss, rs)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, re, psk }\n }\n\n private initializeResponder (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_IK_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n this.mixHash(ss, s.publicKey)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, re, psk }\n }\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class FailedIKError extends Error {\n public initialMsg: string|Uint8ArrayList|Uint8Array\n\n constructor (initialMsg: string|Uint8ArrayList|Uint8Array, message?: string) {\n super(message)\n\n this.initialMsg = initialMsg\n this.name = 'FailedIKhandshake'\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { CipherState, NoiseSession } from './@types/handshake.js'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { IK } from './handshakes/ik.js'\nimport { decode0, decode1, encode0, encode1 } from './encoder.js'\nimport { FailedIKError } from './errors.js'\nimport {\n logger,\n logLocalStaticKeys,\n logRemoteStaticKey,\n logLocalEphemeralKeys,\n logRemoteEphemeralKey,\n logCipherState\n} from './logger.js'\nimport { decodePayload, getPeerIdFromPayload, verifySignedPayload } from './utils.js'\n\nexport class IKHandshake implements IHandshake {\n public isInitiator: boolean\n public session: NoiseSession\n public remotePeer!: PeerId\n public remoteEarlyData: Uint8Array\n\n private readonly payload: bytes\n private readonly prologue: bytes32\n private readonly staticKeypair: KeyPair\n private readonly connection: ProtobufStream\n private readonly ik: IK\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n remoteStaticKey: bytes,\n remotePeer?: PeerId,\n handshake?: IK\n ) {\n this.isInitiator = isInitiator\n this.payload = payload\n this.prologue = prologue\n this.staticKeypair = staticKeypair\n this.connection = connection\n if (remotePeer) {\n this.remotePeer = remotePeer\n }\n this.ik = handshake ?? new IK(crypto)\n this.session = this.ik.initSession(this.isInitiator, this.prologue, this.staticKeypair, remoteStaticKey)\n this.remoteEarlyData = new Uint8Array()\n }\n\n public async stage0 (): Promise {\n logLocalStaticKeys(this.session.hs.s)\n logRemoteStaticKey(this.session.hs.rs)\n if (this.isInitiator) {\n logger('IK Stage 0 - Initiator sending message...')\n const messageBuffer = this.ik.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode1(messageBuffer))\n logger('IK Stage 0 - Initiator sent message.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger('IK Stage 0 - Responder receiving message...')\n const receivedMsg = await this.connection.readLP()\n try {\n const receivedMessageBuffer = decode1(receivedMsg.slice())\n const { plaintext, valid } = this.ik.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new Error('ik handshake stage 0 decryption validation fail')\n }\n logger('IK Stage 0 - Responder got message, going to verify payload.')\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n logger('IK Stage 0 - Responder successfully verified payload!')\n logRemoteEphemeralKey(this.session.hs.re)\n } catch (e) {\n const err = e as Error\n logger('Responder breaking up with IK handshake in stage 0.')\n\n throw new FailedIKError(receivedMsg.slice(), `Error occurred while verifying initiator's signed payload: ${err.message}`)\n }\n }\n }\n\n public async stage1 (): Promise {\n if (this.isInitiator) {\n logger('IK Stage 1 - Initiator receiving message...')\n const receivedMsg = (await this.connection.readLP()).slice()\n const receivedMessageBuffer = decode0(receivedMsg)\n const { plaintext, valid } = this.ik.recvMessage(this.session, receivedMessageBuffer)\n logger('IK Stage 1 - Initiator got message, going to verify payload.')\n try {\n if (!valid) {\n throw new Error('ik stage 1 decryption validation fail')\n }\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(receivedMessageBuffer.ns.slice(0, 32), decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n logger('IK Stage 1 - Initiator successfully verified payload!')\n logRemoteEphemeralKey(this.session.hs.re)\n } catch (e) {\n const err = e as Error\n logger('Initiator breaking up with IK handshake in stage 1.')\n throw new FailedIKError(receivedMsg, `Error occurred while verifying responder's signed payload: ${err.message}`)\n }\n } else {\n logger('IK Stage 1 - Responder sending message...')\n const messageBuffer = this.ik.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode0(messageBuffer))\n logger('IK Stage 1 - Responder sent message...')\n logLocalEphemeralKeys(this.session.hs.e)\n }\n logCipherState(this.session)\n }\n\n public decrypt (ciphertext: Uint8Array, session: NoiseSession): {plaintext: bytes, valid: boolean} {\n const cs = this.getCS(session, false)\n return this.ik.decryptWithAd(cs, new Uint8Array(0), ciphertext)\n }\n\n public encrypt (plaintext: Uint8Array, session: NoiseSession): bytes {\n const cs = this.getCS(session)\n return this.ik.encryptWithAd(cs, new Uint8Array(0), plaintext)\n }\n\n public getLocalEphemeralKeys (): KeyPair {\n if (!this.session.hs.e) {\n throw new Error('Ephemeral keys do not exist.')\n }\n\n return this.session.hs.e\n }\n\n private getCS (session: NoiseSession, encryption = true): CipherState {\n if (!session.cs1 || !session.cs2) {\n throw new Error('Handshake not completed properly, cipher state does not exist.')\n }\n\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2\n } else {\n return encryption ? session.cs2 : session.cs1\n }\n }\n\n private setRemoteEarlyData (data: Uint8Array|null|undefined): void {\n if (data) {\n this.remoteEarlyData = data\n }\n }\n}\n","\nexport class UnexpectedPeerError extends Error {\n public code: string\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.code = UnexpectedPeerError.code\n }\n\n static get code () {\n return 'ERR_UNEXPECTED_PEER'\n }\n}\n\nexport class InvalidCryptoExchangeError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.code = InvalidCryptoExchangeError.code\n }\n\n static get code () {\n return 'ERR_INVALID_CRYPTO_EXCHANGE'\n }\n}\n\nexport class InvalidCryptoTransmissionError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto transmission') {\n super(message)\n this.code = InvalidCryptoTransmissionError.code\n }\n\n static get code () {\n return 'ERR_INVALID_CRYPTO_TRANSMISSION'\n }\n}\n","import type { bytes32, bytes } from '../@types/basic.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport { isValidPublicKey } from '../utils.js'\nimport type { CipherState, HandshakeState, MessageBuffer, NoiseSession } from '../@types/handshake.js'\nimport { AbstractHandshake } from './abstract-handshake.js'\n\nexport class XX extends AbstractHandshake {\n private initializeInitiator (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private initializeResponder (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private writeMessageA (hs: HandshakeState, payload: bytes, e?: KeyPair): MessageBuffer {\n const ns = new Uint8Array(0)\n\n if (e !== undefined) {\n hs.e = e\n } else {\n hs.e = this.crypto.generateX25519KeyPair()\n }\n\n const ne = hs.e.publicKey\n\n this.mixHash(hs.ss, ne)\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageB (hs: HandshakeState, payload: bytes): MessageBuffer {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageC (hs: HandshakeState, payload: bytes): { messageBuffer: MessageBuffer, cs1: CipherState, cs2: CipherState, h: bytes } {\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n const ne = this.createEmptyKey()\n const messageBuffer: MessageBuffer = { ne, ns, ciphertext }\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, messageBuffer, cs1, cs2 }\n }\n\n private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n return this.decryptAndHash(hs.ss, message.ciphertext)\n }\n\n private readMessageB (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n return { plaintext, valid: (valid1 && valid2) }\n }\n\n private readMessageC (hs: HandshakeState, message: MessageBuffer): {h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState} {\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, plaintext, valid: (valid1 && valid2), cs1, cs2 }\n }\n\n public initSession (initiator: boolean, prologue: bytes32, s: KeyPair): NoiseSession {\n const psk = this.createEmptyKey()\n const rs = new Uint8Array(32) // no static key yet\n let hs\n\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk)\n } else {\n hs = this.initializeResponder(prologue, s, rs, psk)\n }\n\n return {\n hs,\n i: initiator,\n mc: 0\n }\n }\n\n public sendMessage (session: NoiseSession, message: bytes, ephemeral?: KeyPair): MessageBuffer {\n let messageBuffer: MessageBuffer\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message, ephemeral)\n } else if (session.mc === 1) {\n messageBuffer = this.writeMessageB(session.hs, message)\n } else if (session.mc === 2) {\n const { h, messageBuffer: resultingBuffer, cs1, cs2 } = this.writeMessageC(session.hs, message)\n messageBuffer = resultingBuffer\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n } else if (session.mc > 2) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs1, message)\n } else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs2, message)\n }\n } else {\n throw new Error('Session invalid.')\n }\n\n session.mc++\n return messageBuffer\n }\n\n public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n let plaintext: bytes = new Uint8Array(0)\n let valid = false\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message))\n } else if (session.mc === 1) {\n ({ plaintext, valid } = this.readMessageB(session.hs, message))\n } else if (session.mc === 2) {\n const { h, plaintext: resultingPlaintext, valid: resultingValid, cs1, cs2 } = this.readMessageC(session.hs, message)\n plaintext = resultingPlaintext\n valid = resultingValid\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n }\n session.mc++\n return { plaintext, valid }\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { InvalidCryptoExchangeError, UnexpectedPeerError } from '@libp2p/interface-connection-encrypter/errors'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { CipherState, NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { decode0, decode1, decode2, encode0, encode1, encode2 } from './encoder.js'\nimport { XX } from './handshakes/xx.js'\nimport {\n logger,\n logLocalStaticKeys,\n logLocalEphemeralKeys,\n logRemoteEphemeralKey,\n logRemoteStaticKey,\n logCipherState\n} from './logger.js'\nimport {\n decodePayload,\n getPeerIdFromPayload,\n verifySignedPayload\n} from './utils.js'\n\nexport class XXHandshake implements IHandshake {\n public isInitiator: boolean\n public session: NoiseSession\n public remotePeer!: PeerId\n public remoteEarlyData: bytes\n\n protected payload: bytes\n protected connection: ProtobufStream\n protected xx: XX\n protected staticKeypair: KeyPair\n\n private readonly prologue: bytes32\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n remotePeer?: PeerId,\n handshake?: XX\n ) {\n this.isInitiator = isInitiator\n this.payload = payload\n this.prologue = prologue\n this.staticKeypair = staticKeypair\n this.connection = connection\n if (remotePeer) {\n this.remotePeer = remotePeer\n }\n this.xx = handshake ?? new XX(crypto)\n this.session = this.xx.initSession(this.isInitiator, this.prologue, this.staticKeypair)\n this.remoteEarlyData = new Uint8Array(0)\n }\n\n // stage 0\n public async propose (): Promise {\n logLocalStaticKeys(this.session.hs.s)\n if (this.isInitiator) {\n logger('Stage 0 - Initiator starting to send first message.')\n const messageBuffer = this.xx.sendMessage(this.session, new Uint8Array(0))\n this.connection.writeLP(encode0(messageBuffer))\n logger('Stage 0 - Initiator finished sending first message.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger('Stage 0 - Responder waiting to receive first message...')\n const receivedMessageBuffer = decode0((await this.connection.readLP()).subarray())\n const { valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 0 validation fail')\n }\n logger('Stage 0 - Responder received first message.')\n logRemoteEphemeralKey(this.session.hs.re)\n }\n }\n\n // stage 1\n public async exchange (): Promise {\n if (this.isInitiator) {\n logger('Stage 1 - Initiator waiting to receive first message from responder...')\n const receivedMessageBuffer = decode1((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 1 validation fail')\n }\n logger('Stage 1 - Initiator received the message.')\n logRemoteEphemeralKey(this.session.hs.re)\n logRemoteStaticKey(this.session.hs.rs)\n\n logger(\"Initiator going to check remote's signature...\")\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n logger('All good with the signature!')\n } else {\n logger('Stage 1 - Responder sending out first message with signed payload and static key.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode1(messageBuffer))\n logger('Stage 1 - Responder sent the second handshake message with signed payload.')\n logLocalEphemeralKeys(this.session.hs.e)\n }\n }\n\n // stage 2\n public async finish (): Promise {\n if (this.isInitiator) {\n logger('Stage 2 - Initiator sending third handshake message.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode2(messageBuffer))\n logger('Stage 2 - Initiator sent message with signed payload.')\n } else {\n logger('Stage 2 - Responder waiting for third handshake message...')\n const receivedMessageBuffer = decode2((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 2 validation fail')\n }\n logger('Stage 2 - Responder received the message, finished handshake.')\n\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n }\n logCipherState(this.session)\n }\n\n public encrypt (plaintext: Uint8Array, session: NoiseSession): bytes {\n const cs = this.getCS(session)\n\n return this.xx.encryptWithAd(cs, new Uint8Array(0), plaintext)\n }\n\n public decrypt (ciphertext: Uint8Array, session: NoiseSession): {plaintext: bytes, valid: boolean} {\n const cs = this.getCS(session, false)\n\n return this.xx.decryptWithAd(cs, new Uint8Array(0), ciphertext)\n }\n\n public getRemoteStaticKey (): bytes {\n return this.session.hs.rs\n }\n\n private getCS (session: NoiseSession, encryption = true): CipherState {\n if (!session.cs1 || !session.cs2) {\n throw new InvalidCryptoExchangeError('Handshake not completed properly, cipher state does not exist.')\n }\n\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2\n } else {\n return encryption ? session.cs2 : session.cs1\n }\n }\n\n protected setRemoteEarlyData (data: Uint8Array|null|undefined): void {\n if (data) {\n this.remoteEarlyData = data\n }\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport { XXHandshake } from './handshake-xx.js'\nimport type { XX } from './handshakes/xx.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { decode0, decode1 } from './encoder.js'\nimport { logger, logLocalEphemeralKeys, logRemoteEphemeralKey, logRemoteStaticKey } from './logger.js'\nimport { decodePayload, getPeerIdFromPayload, verifySignedPayload } from './utils.js'\n\nexport class XXFallbackHandshake extends XXHandshake {\n private readonly ephemeralKeys?: KeyPair\n private readonly initialMsg: bytes\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n initialMsg: bytes,\n remotePeer?: PeerId,\n ephemeralKeys?: KeyPair,\n handshake?: XX\n ) {\n super(isInitiator, payload, prologue, crypto, staticKeypair, connection, remotePeer, handshake)\n if (ephemeralKeys) {\n this.ephemeralKeys = ephemeralKeys\n }\n this.initialMsg = initialMsg\n }\n\n // stage 0\n // eslint-disable-next-line require-await\n public async propose (): Promise {\n if (this.isInitiator) {\n this.xx.sendMessage(this.session, new Uint8Array(0), this.ephemeralKeys)\n logger('XX Fallback Stage 0 - Initialized state as the first message was sent by initiator.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger('XX Fallback Stage 0 - Responder decoding initial msg from IK.')\n const receivedMessageBuffer = decode0(this.initialMsg)\n const { valid } = this.xx.recvMessage(this.session, {\n ne: receivedMessageBuffer.ne,\n ns: new Uint8Array(0),\n ciphertext: new Uint8Array(0)\n })\n if (!valid) {\n throw new Error('xx fallback stage 0 decryption validation fail')\n }\n logger('XX Fallback Stage 0 - Responder used received message from IK.')\n logRemoteEphemeralKey(this.session.hs.re)\n }\n }\n\n // stage 1\n public async exchange (): Promise {\n if (this.isInitiator) {\n const receivedMessageBuffer = decode1(this.initialMsg)\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new Error('xx fallback stage 1 decryption validation fail')\n }\n logger('XX Fallback Stage 1 - Initiator used received message from IK.')\n logRemoteEphemeralKey(this.session.hs.re)\n logRemoteStaticKey(this.session.hs.rs)\n\n logger(\"Initiator going to check remote's signature...\")\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n } catch (e) {\n const err = e as Error\n throw new Error(`Error occurred while verifying signed payload from responder: ${err.message}`)\n }\n logger('All good with the signature!')\n } else {\n logger('XX Fallback Stage 1 - Responder start')\n await super.exchange()\n logger('XX Fallback Stage 1 - Responder end')\n }\n }\n}\n","\nexport function mapIterable (iter: IterableIterator, map: (val: T) => R): IterableIterator {\n const iterator: IterableIterator = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerMap {\n private readonly map: Map\n\n constructor (map?: PeerMap) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value)\n }\n }\n }\n\n [Symbol.iterator] () {\n return this.entries()\n }\n\n clear () {\n this.map.clear()\n }\n\n delete (peer: PeerId) {\n this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, T], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [peerIdFromString(val[0]), val[1]]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap) => void): void {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T) {\n this.map.set(peer.toString(), value)\n }\n\n keys (): IterableIterator {\n return mapIterable(\n this.map.keys(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n values () {\n return this.map.values()\n }\n\n get size () {\n return this.map.size\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerSet {\n private readonly set: Set\n\n constructor (set?: PeerSet | Iterable) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size () {\n return this.set.size\n }\n\n [Symbol.iterator] () {\n return this.values()\n }\n\n add (peer: PeerId) {\n this.set.add(peer.toString())\n }\n\n clear () {\n this.set.clear()\n }\n\n delete (peer: PeerId) {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const id = peerIdFromString(str)\n\n predicate(id, id, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values () {\n return mapIterable(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as list entries because list entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerList {\n private readonly list: string[]\n\n constructor (list?: PeerList) {\n this.list = []\n\n if (list != null) {\n for (const value of list) {\n this.list.push(value.toString())\n }\n }\n }\n\n [Symbol.iterator] () {\n return mapIterable<[number, string], PeerId>(\n this.list.entries(),\n (val) => {\n return peerIdFromString(val[1])\n }\n )\n }\n\n concat (list: PeerList) {\n const output = new PeerList(this)\n\n for (const value of list) {\n output.push(value)\n }\n\n return output\n }\n\n entries (): IterableIterator<[number, PeerId]> {\n return mapIterable<[number, string], [number, PeerId]>(\n this.list.entries(),\n (val) => {\n return [val[0], peerIdFromString(val[1])]\n }\n )\n }\n\n every (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): boolean {\n return this.list.every((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n filter (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerList {\n const output = new PeerList()\n\n this.list.forEach((str, index) => {\n const peerId = peerIdFromString(str)\n\n if (predicate(peerId, index, this)) {\n output.push(peerId)\n }\n })\n\n return output\n }\n\n find (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerId | undefined {\n const str = this.list.find((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n findIndex (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): number {\n return this.list.findIndex((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n forEach (predicate: (peerId: PeerId, index: number, arr: PeerList) => void): void {\n this.list.forEach((str, index) => {\n predicate(peerIdFromString(str), index, this)\n })\n }\n\n includes (peerId: PeerId): boolean {\n return this.list.includes(peerId.toString())\n }\n\n indexOf (peerId: PeerId): number {\n return this.list.indexOf(peerId.toString())\n }\n\n pop (): PeerId | undefined {\n const str = this.list.pop()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n push (...peerIds: PeerId[]) {\n for (const peerId of peerIds) {\n this.list.push(peerId.toString())\n }\n }\n\n shift (): PeerId | undefined {\n const str = this.list.shift()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n unshift (...peerIds: PeerId[]) {\n let len = this.list.length\n\n for (let i = peerIds.length - 1; i > -1; i--) {\n len = this.list.unshift(peerIds[i].toString())\n }\n\n return len\n }\n\n get length () {\n return this.list.length\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport type { bytes32 } from './@types/basic.js'\n\n/**\n * Storage for static keys of previously connected peers.\n */\nclass Keycache {\n private readonly storage = new PeerMap()\n\n public store (peerId: PeerId, key: bytes32): void {\n this.storage.set(peerId, key)\n }\n\n public load (peerId?: PeerId): bytes32 | null {\n if (!peerId) {\n return null\n }\n return this.storage.get(peerId) ?? null\n }\n\n public resetStorage (): void {\n this.storage.clear()\n }\n}\n\nconst KeyCache = new Keycache()\nexport {\n KeyCache\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport { pbStream, ProtobufStream } from 'it-pb-stream'\nimport { duplexPair } from 'it-pair/duplex'\nimport { pipe } from 'it-pipe'\nimport { encode, decode } from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport type { bytes } from './@types/basic.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { INoiseConnection, KeyPair } from './@types/libp2p.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { stablelib } from './crypto/stablelib.js'\nimport { decryptStream, encryptStream } from './crypto/streaming.js'\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js'\nimport type { FailedIKError } from './errors.js'\nimport { IKHandshake } from './handshake-ik.js'\nimport { XXHandshake } from './handshake-xx.js'\nimport { XXFallbackHandshake } from './handshake-xx-fallback.js'\nimport { KeyCache } from './keycache.js'\nimport { logger } from './logger.js'\nimport { getPayload } from './utils.js'\n\ninterface HandshakeParams {\n connection: ProtobufStream\n isInitiator: boolean\n localPeer: PeerId\n remotePeer?: PeerId\n}\n\nexport class Noise implements INoiseConnection {\n public protocol = '/noise'\n public crypto: ICryptoInterface\n\n private readonly prologue = new Uint8Array(0)\n private readonly staticKeys: KeyPair\n private readonly earlyData?: bytes\n private readonly useNoisePipes: boolean\n\n /**\n * @param {bytes} staticNoiseKey - x25519 private key, reuse for faster handshakes\n * @param {bytes} earlyData\n */\n constructor (staticNoiseKey?: bytes, earlyData?: bytes, crypto: ICryptoInterface = stablelib) {\n this.earlyData = earlyData ?? new Uint8Array(0)\n // disabled until properly specked\n this.useNoisePipes = false\n this.crypto = crypto\n\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKeys = this.crypto.generateX25519KeyPairFromSeed(staticNoiseKey)\n } else {\n this.staticKeys = this.crypto.generateX25519KeyPair()\n }\n }\n\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer\n * @param {any} connection - streaming iterable duplex that will be encrypted\n * @param {PeerId} remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer.\n * @returns {Promise}\n */\n public async secureOutbound (localPeer: PeerId, connection: any, remotePeer: PeerId): Promise {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: true,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remoteEarlyData: handshake.remoteEarlyData,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer.\n * @param {any} connection - streaming iterable duplex that will be encryption.\n * @param {PeerId} remotePeer - optional PeerId of the initiating peer, if known. This may only exist during transport upgrades.\n * @returns {Promise}\n */\n public async secureInbound (localPeer: PeerId, connection: any, remotePeer?: PeerId): Promise {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: false,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remoteEarlyData: handshake.remoteEarlyData,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * If Noise pipes supported, tries IK handshake first with XX as fallback if it fails.\n * If noise pipes disabled or remote peer static key is unknown, use XX.\n *\n * @param {HandshakeParams} params\n */\n private async performHandshake (params: HandshakeParams): Promise {\n const payload = await getPayload(params.localPeer, this.staticKeys.publicKey, this.earlyData)\n let tryIK = this.useNoisePipes\n if (params.isInitiator && KeyCache.load(params.remotePeer) === null) {\n // if we are initiator and remote static key is unknown, don't try IK\n tryIK = false\n }\n // Try IK if acting as responder or initiator that has remote's static key.\n if (tryIK) {\n // Try IK first\n const { remotePeer, connection, isInitiator } = params\n const ikHandshake = new IKHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n // safe to cast as we did checks\n KeyCache.load(params.remotePeer) ?? new Uint8Array(32),\n remotePeer as PeerId\n )\n\n try {\n return await this.performIKHandshake(ikHandshake)\n } catch (e) {\n const err = e as FailedIKError\n\n // IK failed, go to XX fallback\n let ephemeralKeys\n if (params.isInitiator) {\n ephemeralKeys = ikHandshake.getLocalEphemeralKeys()\n }\n return await this.performXXFallbackHandshake(params, payload, err.initialMsg as Uint8Array, ephemeralKeys)\n }\n } else {\n // run XX handshake\n return await this.performXXHandshake(params, payload)\n }\n }\n\n private async performXXFallbackHandshake (\n params: HandshakeParams,\n payload: bytes,\n initialMsg: bytes,\n ephemeralKeys?: KeyPair\n ): Promise {\n const { isInitiator, remotePeer, connection } = params\n const handshake =\n new XXFallbackHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n initialMsg,\n remotePeer,\n ephemeralKeys\n )\n\n try {\n await handshake.propose()\n await handshake.exchange()\n await handshake.finish()\n } catch (e) {\n const err = e as Error\n err.message = `Error occurred during XX Fallback handshake: ${err.message}`\n logger(err)\n throw err\n }\n\n return handshake\n }\n\n private async performXXHandshake (\n params: HandshakeParams,\n payload: bytes\n ): Promise {\n const { isInitiator, remotePeer, connection } = params\n const handshake = new XXHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n remotePeer\n )\n\n try {\n await handshake.propose()\n await handshake.exchange()\n await handshake.finish()\n\n if (this.useNoisePipes && handshake.remotePeer) {\n KeyCache.store(handshake.remotePeer, handshake.getRemoteStaticKey())\n }\n } catch (e: unknown) {\n if (e instanceof Error) {\n e.message = `Error occurred during XX handshake: ${e.message}`\n throw e\n }\n }\n\n return handshake\n }\n\n private async performIKHandshake (\n handshake: IKHandshake\n ): Promise {\n await handshake.stage0()\n await handshake.stage1()\n\n return handshake\n }\n\n private async createSecureConnection (\n connection: ProtobufStream,\n handshake: IHandshake\n ): Promise> {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair()\n const network = connection.unwrap()\n\n await pipe(\n secure, // write to wrapper\n encryptStream(handshake), // data is encrypted\n encode({ lengthEncoder: uint16BEEncode }), // prefix with message length\n network, // send to the remote peer\n decode({ lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake), // decrypt the incoming data\n secure // pipe to the wrapper\n )\n\n return user\n }\n}\n","import { pair } from './index.js'\nimport type { Duplex } from 'it-stream-types'\n\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair (): [Duplex, Duplex] {\n const a = pair()\n const b = pair()\n return [\n {\n source: a.source,\n sink: b.sink\n },\n {\n source: b.source,\n sink: a.sink\n }\n ]\n}\n","import type { Transform } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { IHandshake } from '../@types/handshake-interface.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js'\n\n// Returns generator that encrypts payload from the user\nexport function encryptStream (handshake: IHandshake): Transform {\n return async function * (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG\n if (end > chunk.length) {\n end = chunk.length\n }\n\n const data = handshake.encrypt(chunk.subarray(i, end), handshake.session)\n yield data\n }\n }\n }\n}\n\n// Decrypt received payload to the user\nexport function decryptStream (handshake: IHandshake): Transform {\n return async function * (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES\n if (end > chunk.length) {\n end = chunk.length\n }\n\n const { plaintext: decrypted, valid } = await handshake.decrypt(chunk.subarray(i, end), handshake.session)\n if (!valid) {\n throw new Error('Failed to validate decrypted chunk')\n }\n yield decrypted\n }\n }\n }\n}\n","import { Noise } from './noise.js'\n\nexport * from './crypto.js'\nexport * from './crypto/stablelib.js'\nexport * from './noise.js'\n\n/**\n * Default configuration, it will generate new noise static key and enable noise pipes (IK handshake).\n */\nexport const NOISE = new Noise()\n","export function allocUnsafe (size: number) {\n return new Uint8Array(size)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\ntype INITIATOR_NAME = 'NEW_STREAM' | 'MESSAGE' | 'CLOSE' | 'RESET'\ntype RECEIVER_NAME = 'MESSAGE' | 'CLOSE' | 'RESET'\ntype NAME = 'NEW_STREAM' | 'MESSAGE_INITIATOR' | 'CLOSE_INITIATOR' | 'RESET_INITIATOR' | 'MESSAGE_RECEIVER' | 'CLOSE_RECEIVER' | 'RESET_RECEIVER'\ntype CODE = 0 | 1 | 2 | 3 | 4 | 5 | 6\n\nexport enum MessageTypes {\n NEW_STREAM = 0,\n MESSAGE_RECEIVER = 1,\n MESSAGE_INITIATOR = 2,\n CLOSE_RECEIVER = 3,\n CLOSE_INITIATOR = 4,\n RESET_RECEIVER = 5,\n RESET_INITIATOR = 6\n}\n\nexport const MessageTypeNames: Record = Object.freeze({\n 0: 'NEW_STREAM',\n 1: 'MESSAGE_RECEIVER',\n 2: 'MESSAGE_INITIATOR',\n 3: 'CLOSE_RECEIVER',\n 4: 'CLOSE_INITIATOR',\n 5: 'RESET_RECEIVER',\n 6: 'RESET_INITIATOR'\n})\n\nexport const InitiatorMessageTypes: Record = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n})\n\nexport const ReceiverMessageTypes: Record = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n})\n\nexport interface NewStreamMessage {\n id: number\n type: MessageTypes.NEW_STREAM\n data: Uint8Array | Uint8ArrayList\n}\n\nexport interface MessageReceiverMessage {\n id: number\n type: MessageTypes.MESSAGE_RECEIVER\n data: Uint8Array | Uint8ArrayList\n}\n\nexport interface MessageInitiatorMessage {\n id: number\n type: MessageTypes.MESSAGE_INITIATOR\n data: Uint8Array | Uint8ArrayList\n}\n\nexport interface CloseReceiverMessage {\n id: number\n type: MessageTypes.CLOSE_RECEIVER\n}\n\nexport interface CloseInitiatorMessage {\n id: number\n type: MessageTypes.CLOSE_INITIATOR\n}\n\nexport interface ResetReceiverMessage {\n id: number\n type: MessageTypes.RESET_RECEIVER\n}\n\nexport interface ResetInitiatorMessage {\n id: number\n type: MessageTypes.RESET_INITIATOR\n}\n\nexport type Message = NewStreamMessage | MessageReceiverMessage | MessageInitiatorMessage | CloseReceiverMessage | CloseInitiatorMessage | ResetReceiverMessage | ResetInitiatorMessage\n","import type { Source } from 'it-stream-types'\nimport varint from 'varint'\nimport { allocUnsafe } from './alloc-unsafe.js'\nimport { Message, MessageTypes } from './message-types.js'\n\nconst POOL_SIZE = 10 * 1024\n\nclass Encoder {\n private _pool: Uint8Array\n private _poolOffset: number\n\n constructor () {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n }\n\n /**\n * Encodes the given message and returns it and its header\n */\n write (msg: Message): Uint8Array[] {\n const pool = this._pool\n let offset = this._poolOffset\n\n varint.encode(msg.id << 3 | msg.type, pool, offset)\n offset += varint.encode.bytes\n\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n varint.encode(msg.data.length, pool, offset)\n } else {\n varint.encode(0, pool, offset)\n }\n\n offset += varint.encode.bytes\n\n const header = pool.subarray(this._poolOffset, offset)\n\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n } else {\n this._poolOffset = offset\n }\n\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n return [\n header,\n msg.data instanceof Uint8Array ? msg.data : msg.data.subarray()\n ]\n }\n\n return [\n header\n ]\n }\n}\n\nconst encoder = new Encoder()\n\n/**\n * Encode and yield one or more messages\n */\nexport async function * encode (source: Source) {\n for await (const msg of source) {\n if (Array.isArray(msg)) {\n for (const m of msg) {\n yield * encoder.write(m)\n }\n } else {\n yield * encoder.write(msg)\n }\n }\n}\n","import { MessageTypeNames, MessageTypes } from './message-types.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Source } from 'it-stream-types'\nimport type { Message } from './message-types.js'\n\ninterface MessageHeader {\n id: number\n type: keyof typeof MessageTypeNames\n offset: number\n length: number\n}\n\nclass Decoder {\n private readonly _buffer: Uint8ArrayList\n private _headerInfo: MessageHeader | null\n\n constructor () {\n this._buffer = new Uint8ArrayList()\n this._headerInfo = null\n }\n\n write (chunk: Uint8Array) {\n if (chunk == null || chunk.length === 0) {\n return []\n }\n\n this._buffer.append(chunk)\n const msgs: Message[] = []\n\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer)\n } catch (_) {\n break // We haven't received enough data yet\n }\n }\n\n const { id, type, length, offset } = this._headerInfo\n const bufferedDataLength = this._buffer.length - offset\n\n if (bufferedDataLength < length) {\n break // not enough data yet\n }\n\n const msg: any = {\n id,\n type\n }\n\n if (type === MessageTypes.NEW_STREAM || type === MessageTypes.MESSAGE_INITIATOR || type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = this._buffer.subarray(offset, offset + length)\n }\n\n msgs.push(msg)\n\n this._buffer.consume(offset + length)\n this._headerInfo = null\n }\n\n return msgs\n }\n\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader (data: Uint8ArrayList): MessageHeader {\n const {\n value: h,\n offset\n } = readVarInt(data)\n const {\n value: length,\n offset: end\n } = readVarInt(data, offset)\n\n const type = h & 7\n\n // @ts-expect-error h is a number not a CODE\n if (MessageTypeNames[type] == null) {\n throw new Error(`Invalid type received: ${type}`)\n }\n\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length }\n }\n}\n\nconst MSB = 0x80\nconst REST = 0x7F\n\nfunction readVarInt (buf: Uint8ArrayList, offset: number = 0) {\n let res = 0\n let shift = 0\n let counter = offset\n let b: number\n const l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n offset = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf.get(counter++)\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n offset = counter - offset\n\n return {\n value: res,\n offset\n }\n}\n\n/**\n * Decode a chunk and yield an _array_ of decoded messages\n */\nexport async function * decode (source: Source) {\n const decoder = new Decoder()\n\n for await (const chunk of source) {\n const msgs = decoder.write(chunk)\n\n if (msgs.length > 0) {\n yield msgs\n }\n }\n}\n","import { Message, MessageTypes } from './message-types.js'\nimport type { Source, Transform } from 'it-stream-types'\n\nexport const MAX_MSG_SIZE = 1 << 20 // 1MB\n\n/**\n * Creates an iterable transform that restricts message sizes to\n * the given maximum size.\n */\nexport function restrictSize (max?: number): Transform {\n const maxSize = max ?? MAX_MSG_SIZE\n\n const checkSize = (msg: Message) => {\n if (msg.type !== MessageTypes.NEW_STREAM && msg.type !== MessageTypes.MESSAGE_INITIATOR && msg.type !== MessageTypes.MESSAGE_RECEIVER) {\n return\n }\n\n if (msg.data.byteLength > maxSize) {\n throw Object.assign(new Error('message size too large!'), { code: 'ERR_MSG_TOO_BIG' })\n }\n }\n\n return (source: Source) => {\n return (async function * restrictSize () {\n for await (const msg of source) {\n if (Array.isArray(msg)) {\n msg.forEach(checkSize)\n yield * msg\n } else {\n checkSize(msg)\n yield msg\n }\n }\n })()\n }\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { pushable } from 'it-pushable'\nimport errCode from 'err-code'\nimport { MAX_MSG_SIZE } from './restrict-size.js'\nimport { anySignal } from 'any-signal'\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { logger } from '@libp2p/logger'\nimport type { Message } from './message-types.js'\nimport type { StreamTimeline } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { MplexStream } from './mplex.js'\n\nconst log = logger('libp2p:mplex:stream')\n\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET'\nconst ERR_STREAM_ABORT = 'ERR_STREAM_ABORT'\nconst ERR_SINK_ENDED = 'ERR_SINK_ENDED'\nconst ERR_DOUBLE_SINK = 'ERR_DOUBLE_SINK'\n\nexport interface Options {\n id: number\n send: (msg: Message) => void\n name?: string\n onEnd?: (err?: Error) => void\n type?: 'initiator' | 'receiver'\n maxMsgSize?: number\n}\n\nexport function createStream (options: Options): MplexStream {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options\n\n const abortController = new AbortController()\n const resetController = new AbortController()\n const closeController = new AbortController()\n const Types = type === 'initiator' ? InitiatorMessageTypes : ReceiverMessageTypes\n const externalId = type === 'initiator' ? (`i${id}`) : `r${id}`\n const streamName = `${name == null ? id : name}`\n\n let sourceEnded = false\n let sinkEnded = false\n let sinkSunk = false\n let endErr: Error | undefined\n\n const timeline: StreamTimeline = {\n open: Date.now()\n }\n\n const onSourceEnd = (err?: Error) => {\n if (sourceEnded) {\n return\n }\n\n sourceEnded = true\n log.trace('%s stream %s source end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sinkEnded) {\n stream.stat.timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const onSinkEnd = (err?: Error) => {\n if (sinkEnded) {\n return\n }\n\n sinkEnded = true\n log.trace('%s stream %s sink end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sourceEnded) {\n timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const stream: MplexStream = {\n // Close for both Reading and Writing\n close: () => {\n log.trace('%s stream %s close', type, streamName)\n\n stream.closeRead()\n stream.closeWrite()\n },\n\n // Close for reading\n closeRead: () => {\n log.trace('%s stream %s closeRead', type, streamName)\n\n if (sourceEnded) {\n return\n }\n\n stream.source.end()\n },\n\n // Close for writing\n closeWrite: () => {\n log.trace('%s stream %s closeWrite', type, streamName)\n\n if (sinkEnded) {\n return\n }\n\n closeController.abort()\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n // Close for reading and writing (local error)\n abort: (err: Error) => {\n log.trace('%s stream %s abort', type, streamName, err)\n // End the source with the passed error\n stream.source.end(err)\n abortController.abort()\n onSinkEnd(err)\n },\n\n // Close immediately for reading and writing (remote error)\n reset: () => {\n const err = errCode(new Error('stream reset'), ERR_STREAM_RESET)\n resetController.abort()\n stream.source.end(err)\n onSinkEnd(err)\n },\n\n sink: async (source: Source) => {\n if (sinkSunk) {\n throw errCode(new Error('sink already called on stream'), ERR_DOUBLE_SINK)\n }\n\n sinkSunk = true\n\n if (sinkEnded) {\n throw errCode(new Error('stream closed for writing'), ERR_SINK_ENDED)\n }\n\n source = abortableSource(source, anySignal([\n abortController.signal,\n resetController.signal,\n closeController.signal\n ]))\n\n try {\n if (type === 'initiator') { // If initiator, open a new stream\n send({ id, type: InitiatorMessageTypes.NEW_STREAM, data: uint8ArrayFromString(streamName) })\n }\n\n const uint8ArrayList = new Uint8ArrayList()\n\n for await (const data of source) {\n uint8ArrayList.append(data)\n\n while (uint8ArrayList.length !== 0) {\n if (uint8ArrayList.length <= maxMsgSize) {\n send({ id, type: Types.MESSAGE, data: uint8ArrayList.subarray() })\n uint8ArrayList.consume(uint8ArrayList.length)\n break\n }\n\n const toSend = uint8ArrayList.length - maxMsgSize\n send({ id, type: Types.MESSAGE, data: uint8ArrayList.subarray(0, toSend) })\n uint8ArrayList.consume(toSend)\n }\n }\n } catch (err: any) {\n if (err.type === 'aborted' && err.message === 'The operation was aborted') {\n if (closeController.signal.aborted) {\n return\n }\n\n if (resetController.signal.aborted) {\n err.message = 'stream reset'\n err.code = ERR_STREAM_RESET\n }\n\n if (abortController.signal.aborted) {\n err.message = 'stream aborted'\n err.code = ERR_STREAM_ABORT\n }\n }\n\n // Send no more data if this stream was remotely reset\n if (err.code === ERR_STREAM_RESET) {\n log.trace('%s stream %s reset', type, name)\n } else {\n log.trace('%s stream %s error', type, name, err)\n try {\n send({ id, type: Types.RESET })\n } catch (err) {\n log.trace('%s stream %s error sending reset', type, name, err)\n }\n }\n\n stream.source.end(err)\n onSinkEnd(err)\n return\n }\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n source: pushable({\n onEnd: onSourceEnd\n }),\n\n stat: {\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n timeline\n },\n\n metadata: {},\n\n id: externalId\n }\n\n return stream\n}\n","import type { ComponentMetricsTracker } from '@libp2p/interface-metrics'\n\nexport interface TrackedMapInit {\n metrics: ComponentMetricsTracker\n system?: string\n component: string\n metric: string\n}\n\nclass TrackedMap extends Map {\n private readonly system: string\n private readonly component: string\n private readonly metric: string\n private readonly metrics: ComponentMetricsTracker\n\n constructor (init: TrackedMapInit) {\n super()\n\n const { system, component, metric, metrics } = init\n this.system = system ?? 'libp2p'\n this.component = component\n this.metric = metric\n this.metrics = metrics\n\n this.updateComponentMetric()\n }\n\n set (key: K, value: V) {\n super.set(key, value)\n this.updateComponentMetric()\n return this\n }\n\n delete (key: K) {\n const deleted = super.delete(key)\n this.updateComponentMetric()\n return deleted\n }\n\n clear () {\n super.clear()\n this.updateComponentMetric()\n }\n\n private updateComponentMetric () {\n this.metrics.updateComponentMetric({\n system: this.system,\n component: this.component,\n metric: this.metric,\n value: this.size\n })\n }\n}\n\nexport interface CreateTrackedMapOptions {\n metrics?: ComponentMetricsTracker\n system?: string\n component: string\n metric: string\n}\n\nexport function trackedMap (config: CreateTrackedMapOptions): Map {\n const { system, component, metric, metrics } = config\n let map: Map\n\n if (metrics != null) {\n map = new TrackedMap({ system, component, metric, metrics })\n } else {\n map = new Map()\n }\n\n return map\n}\n","import { pipe } from 'it-pipe'\nimport { Pushable, pushableV } from 'it-pushable'\nimport { abortableSource } from 'abortable-iterator'\nimport { encode } from './encode.js'\nimport { decode } from './decode.js'\nimport { restrictSize } from './restrict-size.js'\nimport { MessageTypes, MessageTypeNames, Message } from './message-types.js'\nimport { createStream } from './stream.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport type { Components } from '@libp2p/components'\nimport type { Sink } from 'it-stream-types'\nimport type { StreamMuxer, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { MplexInit } from './index.js'\nimport anySignal from 'any-signal'\n\nconst log = logger('libp2p:mplex')\n\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4 // 4MB\n\nfunction printMessage (msg: Message) {\n const output: any = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n }\n\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray())\n }\n\n if (msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16')\n }\n\n return output\n}\n\nexport interface MplexStream extends Stream {\n source: Pushable\n}\n\ninterface MplexStreamMuxerInit extends MplexInit, StreamMuxerInit {}\n\nexport class MplexStreamMuxer implements StreamMuxer {\n public protocol = '/mplex/6.7.0'\n\n public sink: Sink\n public source: AsyncIterable\n\n private _streamId: number\n private readonly _streams: { initiators: Map, receivers: Map }\n private readonly _init: MplexStreamMuxerInit\n private readonly _source: { push: (val: Message) => void, end: (err?: Error) => void }\n private readonly closeController: AbortController\n\n constructor (components: Components, init?: MplexStreamMuxerInit) {\n init = init ?? {}\n\n this._streamId = 0\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: trackedMap({ metrics: components.getMetrics(), component: 'mplex', metric: 'initiatorStreams' }),\n /**\n * Stream to ids map\n */\n receivers: trackedMap({ metrics: components.getMetrics(), component: 'mplex', metric: 'receiverStreams' })\n }\n this._init = init\n\n /**\n * An iterable sink\n */\n this.sink = this._createSink()\n\n /**\n * An iterable source\n */\n const source = this._createSource()\n this._source = source\n this.source = source\n\n /**\n * Close controller\n */\n this.closeController = new AbortController()\n }\n\n init (components: Components) {}\n\n /**\n * Returns a Map of streams and their ids\n */\n get streams () {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams: Stream[] = []\n this._streams.initiators.forEach(stream => {\n streams.push(stream)\n })\n this._streams.receivers.forEach(stream => {\n streams.push(stream)\n })\n return streams\n }\n\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream (name?: string): Stream {\n if (this.closeController.signal.aborted) {\n throw new Error('Muxer already closed')\n }\n const id = this._streamId++\n name = name == null ? id.toString() : name.toString()\n const registry = this._streams.initiators\n return this._newStream({ id, name, type: 'initiator', registry })\n }\n\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n close (err?: Error | undefined): void {\n if (this.closeController.signal.aborted) return\n\n if (err != null) {\n this.streams.forEach(s => s.abort(err))\n } else {\n this.streams.forEach(s => s.close())\n }\n this.closeController.abort()\n }\n\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream (options: { id: number, name: string }) {\n const { id, name } = options\n const registry = this._streams.receivers\n return this._newStream({ id, name, type: 'receiver', registry })\n }\n\n _newStream (options: { id: number, name: string, type: 'initiator' | 'receiver', registry: Map }) {\n const { id, name, type, registry } = options\n\n log('new %s stream %s %s', type, id, name)\n\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw errCode(new Error('Too many outbound streams open'), 'ERR_TOO_MANY_OUTBOUND_STREAMS')\n }\n\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`)\n }\n\n const send = (msg: Message) => {\n if (log.enabled) {\n log.trace('%s stream %s send', type, id, printMessage(msg))\n }\n\n if (msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = msg.data instanceof Uint8Array ? msg.data : msg.data.subarray()\n }\n\n this._source.push(msg)\n }\n\n const onEnd = () => {\n log('%s stream %s ended', type, id, name)\n registry.delete(id)\n\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream)\n }\n }\n\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize })\n registry.set(id, stream)\n return stream\n }\n\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink () {\n const sink: Sink = async source => {\n // see: https://github.com/jacobheun/any-signal/pull/18\n const abortSignals = [this.closeController.signal]\n if (this._init.signal != null) {\n abortSignals.push(this._init.signal)\n }\n source = abortableSource(source, anySignal(abortSignals))\n\n try {\n await pipe(\n source,\n decode,\n restrictSize(this._init.maxMsgSize),\n async source => {\n for await (const msg of source) {\n this._handleIncoming(msg)\n }\n }\n )\n\n this._source.end()\n } catch (err: any) {\n log('error in sink', err)\n this._source.end(err) // End the source with an error\n }\n }\n\n return sink\n }\n\n /**\n * Creates a source that restricts outgoing message sizes\n * and varint encodes them\n */\n _createSource () {\n const onEnd = (err?: Error) => {\n this.close(err)\n }\n const source = pushableV({\n objectMode: true,\n onEnd\n })\n\n return Object.assign(encode(source), {\n push: source.push,\n end: source.end,\n return: source.return\n })\n }\n\n _handleIncoming (message: Message) {\n const { id, type } = message\n\n if (log.enabled) {\n log.trace('incoming message', printMessage(message))\n }\n\n // Create a new stream?\n if (message.type === MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n log.error('Too many inbound streams open')\n\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n\n this._source.push({\n id,\n type: MessageTypes.RESET_RECEIVER\n })\n\n return\n }\n\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) })\n\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream)\n }\n\n return\n }\n\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers\n const stream = list.get(id)\n\n if (stream == null) {\n log('missing stream %s', id)\n\n return\n }\n\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE\n\n switch (type) {\n case MessageTypes.MESSAGE_INITIATOR:\n case MessageTypes.MESSAGE_RECEIVER:\n if (stream.source.readableLength > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === MessageTypes.MESSAGE_INITIATOR ? MessageTypes.RESET_RECEIVER : MessageTypes.RESET_INITIATOR\n })\n\n // Inform the stream consumer they are not fast enough\n const error = errCode(new Error('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers'), 'ERR_STREAM_INPUT_BUFFER_FULL')\n stream.abort(error)\n\n return\n }\n\n // We got data from the remote, push it into our local stream\n stream.source.push(message.data.subarray())\n break\n case MessageTypes.CLOSE_INITIATOR:\n case MessageTypes.CLOSE_RECEIVER:\n // We should expect no more data from the remote, stop reading\n stream.closeRead()\n break\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // Stop reading and writing to the stream immediately\n stream.reset()\n break\n default:\n log('unknown message type %s', type)\n }\n }\n}\n","import { Components, Initializable } from '@libp2p/components'\nimport type { StreamMuxer, StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport { MplexStreamMuxer } from './mplex.js'\n\nexport interface MplexInit {\n /**\n * The maximum size of message that can be sent in one go in bytes.\n * Messages larger than this will be split into multiple smaller\n * messages.\n */\n maxMsgSize?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw.\n */\n maxInboundStreams?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw.\n */\n maxOutboundStreams?: number\n\n /**\n * Incoming stream messages are buffered until processed by the stream\n * handler. If the buffer reaches this size in bytes the stream will\n * be reset.\n */\n maxStreamBufferSize?: number\n}\n\nexport class Mplex implements StreamMuxerFactory, Initializable {\n public protocol = '/mplex/6.7.0'\n private readonly _init: MplexInit\n private components: Components = new Components()\n\n constructor (init: MplexInit = {}) {\n this._init = init\n }\n\n init (components: Components): void {\n this.components = components\n }\n\n createStreamMuxer (init: StreamMuxerInit = {}): StreamMuxer {\n return new MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n })\n }\n}\n","/* eslint-env browser */\n\nexport default WebSocket\n","\nimport { EventIterator } from 'event-iterator'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { WebSocket, ErrorEvent, MessageEvent } from 'ws'\n\n// copied from github.com/feross/buffer\n// Some ArrayBuffers are not passing the instanceof check, so we need to do a bit more work :(\nfunction isArrayBuffer (obj: any): obj is ArrayBuffer {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number')\n}\n\nexport interface ConnectedSource extends AsyncIterable {\n connected: () => Promise\n}\n\nexport default (socket: WebSocket): ConnectedSource => {\n socket.binaryType = 'arraybuffer'\n\n const connected = async () => await new Promise((resolve, reject) => {\n if (isConnected) {\n return resolve()\n }\n if (connError != null) {\n return reject(connError)\n }\n\n const cleanUp = (cont: () => void) => {\n socket.removeEventListener('open', onOpen)\n socket.removeEventListener('error', onError)\n cont()\n }\n\n const onOpen = () => cleanUp(resolve)\n const onError = (event: ErrorEvent) => {\n cleanUp(() => reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)))\n }\n\n socket.addEventListener('open', onOpen)\n socket.addEventListener('error', onError)\n })\n\n const source = (async function * () {\n const messages = new EventIterator(\n ({ push, stop, fail }) => {\n const onMessage = (event: MessageEvent) => {\n let data: Uint8Array | null = null\n\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data)\n }\n\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data)\n }\n\n if (event.data instanceof Uint8Array) {\n data = event.data\n }\n\n if (data == null) {\n return\n }\n\n push(data)\n }\n const onError = (event: ErrorEvent) => fail(event.error ?? new Error('Socket error'))\n\n socket.addEventListener('message', onMessage)\n socket.addEventListener('error', onError)\n socket.addEventListener('close', stop)\n\n return () => {\n socket.removeEventListener('message', onMessage)\n socket.removeEventListener('error', onError)\n socket.removeEventListener('close', stop)\n }\n },\n { highWaterMark: Infinity }\n )\n\n await connected()\n\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk\n }\n }())\n\n let isConnected = socket.readyState === 1\n let connError: Error | null\n\n socket.addEventListener('open', () => {\n isConnected = true\n connError = null\n })\n\n socket.addEventListener('close', () => {\n isConnected = false\n connError = null\n })\n\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)\n }\n })\n\n return Object.assign(source, {\n connected\n })\n}\n","import type { ErrorEvent, WebSocket } from 'ws'\n\nexport default (socket: WebSocket) => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed')\n }\n\n // if open, return\n if (socket.readyState === 1) {\n return\n }\n\n return new Promise((resolve, reject) => {\n function cleanup () {\n socket.removeEventListener('open', handleOpen)\n socket.removeEventListener('error', handleErr)\n }\n\n function handleOpen () {\n cleanup()\n resolve()\n }\n\n function handleErr (event: ErrorEvent) {\n cleanup()\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`))\n }\n\n socket.addEventListener('open', handleOpen)\n socket.addEventListener('error', handleErr)\n })\n}\n","import ready from './ready.js'\nimport type { WebSocket } from 'ws'\nimport type { Sink } from 'it-stream-types'\n\nexport interface SinkOptions {\n closeOnEnd?: boolean\n}\n\nexport default (socket: WebSocket, options: SinkOptions) => {\n options = options ?? {}\n options.closeOnEnd = options.closeOnEnd !== false\n\n const sink: Sink> = async source => {\n for await (const data of source) {\n try {\n await ready(socket)\n } catch (err: any) {\n if (err.message === 'socket closed') break\n throw err\n }\n\n socket.send(data)\n }\n\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n return await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve()\n } else {\n const err = Object.assign(new Error('ws error'), { event })\n reject(err)\n }\n })\n\n setTimeout(() => socket.close())\n })\n }\n }\n\n return sink\n}\n","import source from './source.js'\nimport sink from './sink.js'\nimport type WebSocket from './web-socket.js'\nimport type { SinkOptions } from './sink.js'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface DuplexWebSocket extends Duplex> {\n connected: () => Promise\n localAddress?: string\n localPort?: number\n remoteAddress: string\n remotePort: number\n close: () => Promise\n destroy: () => void\n socket: WebSocket\n}\n\nexport interface DuplexWebSocketOptions extends SinkOptions {\n remoteAddress?: string\n remotePort?: number\n}\n\nexport default (socket: WebSocket, options?: DuplexWebSocketOptions): DuplexWebSocket => {\n options = options ?? {}\n\n const connectedSource = source(socket)\n let remoteAddress: string | undefined = options.remoteAddress\n let remotePort: number | undefined = options.remotePort\n\n if (socket.url != null) {\n // only client->server sockets have urls, server->client connections do not\n try {\n const url = new URL(socket.url)\n remoteAddress = url.hostname\n remotePort = parseInt(url.port, 10)\n } catch {}\n }\n\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port')\n }\n\n const duplex: DuplexWebSocket = {\n sink: sink(socket, options),\n source: connectedSource,\n connected: async () => await connectedSource.connected(),\n close: async () => {\n if (socket.readyState === socket.CONNECTING || socket.readyState === socket.OPEN) {\n await new Promise((resolve) => {\n socket.addEventListener('close', () => {\n resolve()\n })\n socket.close()\n })\n }\n },\n destroy: () => {\n if (socket.terminate != null) {\n socket.terminate()\n } else {\n socket.close()\n }\n },\n remoteAddress,\n remotePort,\n socket\n }\n\n return duplex\n}\n","import { relative } from 'iso-url'\n\nconst map = { http: 'ws', https: 'wss' }\nconst def = 'ws'\n\nexport default (url: string, location: string | Partial) => relative(url, location, map, def)\n","// load websocket library if we are not in the browser\nimport WebSocket from './web-socket.js'\nimport duplex from './duplex.js'\nimport wsurl from './ws-url.js'\nimport type { ClientOptions } from 'ws'\nimport type { DuplexWebSocket } from './duplex.js'\nimport type { SinkOptions } from './sink.js'\n\nexport interface WebSocketOptions extends SinkOptions {\n websocket?: ClientOptions\n}\n\nexport function connect (addr: string, opts?: WebSocketOptions): DuplexWebSocket {\n const location = typeof window === 'undefined' ? '' : window.location\n opts = opts ?? {}\n\n const url = wsurl(addr, location.toString())\n const socket = new WebSocket(url, opts.websocket)\n\n return duplex(socket, opts)\n}\n","import { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MultiaddrToUriOpts {\n assumeHttp?: boolean\n}\n\ninterface Reducer { (str: string, content: string, i: number, parts: Part[], opts?: MultiaddrToUriOpts): string }\n\nconst reduceValue: Reducer = (_, v) => v\nconst tcpUri = (str: string, port: string, parts: Part[], opts?: MultiaddrToUriOpts) => {\n // return tcp when explicitly requested\n if ((opts != null) && opts.assumeHttp === false) return `tcp://${str}:${port}`\n // check if tcp is the last protocol in multiaddr\n let protocol = 'tcp'\n let explicitPort = `:${port}`\n const last = parts[parts.length - 1]\n if (last.protocol === 'tcp') {\n // assume http and produce clean urls\n protocol = port === '443' ? 'https' : 'http'\n explicitPort = port === '443' || port === '80' ? '' : explicitPort\n }\n return `${protocol}://${str}${explicitPort}`\n}\n\nconst Reducers: Record = {\n ip4: reduceValue,\n ip6: (str, content, i, parts) => (\n parts.length === 1 && parts[0].protocol === 'ip6'\n ? content\n : `[${content}]`\n ),\n tcp: (str, content, i, parts, opts) => (\n parts.some(p => ['http', 'https', 'ws', 'wss'].includes(p.protocol))\n ? `${str}:${content}`\n : tcpUri(str, content, parts, opts)\n ),\n udp: (str, content) => `udp://${str}:${content}`,\n dnsaddr: reduceValue,\n dns4: reduceValue,\n dns6: reduceValue,\n ipfs: (str, content) => `${str}/ipfs/${content}`,\n p2p: (str, content) => `${str}/p2p/${content}`,\n http: str => `http://${str}`,\n https: str => `https://${str}`,\n ws: str => `ws://${str}`,\n wss: str => `wss://${str}`,\n 'p2p-websocket-star': str => `${str}/p2p-websocket-star`,\n 'p2p-webrtc-star': str => `${str}/p2p-webrtc-star`,\n 'p2p-webrtc-direct': str => `${str}/p2p-webrtc-direct`\n}\n\ninterface Part {\n protocol: string\n content: string\n}\n\nexport function multiaddrToUri (multiaddr: Multiaddr | string | Uint8Array, opts?: MultiaddrToUriOpts) {\n const ma = new Multiaddr(multiaddr)\n const parts = multiaddr.toString().split('/').slice(1)\n return ma\n .tuples()\n .map(tuple => ({\n protocol: parts.shift() ?? '',\n content: (tuple[1] != null) ? parts.shift() ?? '' : ''\n }))\n .reduce((str: string, part: Part, i: number, parts: Part[]) => {\n const reduce = Reducers[part.protocol]\n if (reduce == null) {\n throw new Error(`Unsupported protocol ${part.protocol}`)\n }\n return reduce(str, part.content, i, parts, opts)\n }, '')\n}\n","\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static get code () {\n return 'ABORT_ERR'\n }\n\n static get type () {\n return 'aborted'\n }\n}\n","import detectElectron from 'is-electron'\n\nexport const isEnvWithDom = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\nexport const isElectron = detectElectron()\n\n/**\n * Detects browser main thread **NOT** web worker or service worker\n */\nexport const isBrowser = isEnvWithDom && !isElectron\nexport const isElectronMain = isElectron && !isEnvWithDom\nexport const isElectronRenderer = isElectron && isEnvWithDom\nexport const isNode = typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !isElectron\n// @ts-ignore\n// eslint-disable-next-line no-undef\nexport const isWebWorker = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\n\n// defeat bundlers replacing process.env.NODE_ENV with \"development\" or whatever\nexport const isTest = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env['NODE' + (() => '_')() + 'ENV'] === 'test'\nexport const isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst cancelablePromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst errorMessage = typeof message === 'string' ? message : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = message instanceof Error ? message : new TimeoutError(errorMessage);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t} finally {\n\t\t\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { CLOSE_TIMEOUT } from './constants.js'\nimport pTimeout from 'p-timeout'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\n\nconst log = logger('libp2p:websockets:socket')\n\nexport interface SocketToConnOptions extends AbortOptions {\n localAddr?: Multiaddr\n}\n\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn (stream: DuplexWebSocket, remoteAddr: Multiaddr, options?: SocketToConnOptions): MultiaddrConnection {\n options = options ?? {}\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if ((options?.signal) != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await stream.sink(source)\n } catch (err: any) {\n if (err.type !== 'aborted') {\n log.error(err)\n }\n }\n },\n\n source: (options.signal != null) ? abortableSource(stream.source, options.signal) : stream.source,\n\n remoteAddr,\n\n timeline: { open: Date.now() },\n\n async close () {\n const start = Date.now()\n\n try {\n await pTimeout(stream.close(), {\n milliseconds: CLOSE_TIMEOUT\n })\n } catch (err) {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing stream to %s:%s after %dms, destroying it manually',\n host, port, Date.now() - start)\n\n stream.destroy()\n } finally {\n maConn.timeline.close = Date.now()\n }\n }\n }\n\n stream.socket.once != null && stream.socket.once('close', () => { // eslint-disable-line @typescript-eslint/prefer-optional-chain\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n })\n\n return maConn\n}\n","// p2p multi-address code\nexport const CODE_P2P = 421\nexport const CODE_CIRCUIT = 290\n\nexport const CODE_TCP = 6\nexport const CODE_WS = 477\nexport const CODE_WSS = 478\n\n// Time to wait for a connection to close gracefully before destroying it manually\nexport const CLOSE_TIMEOUT = 2000\n","import { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\n\nexport const WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss'))\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nexport const WebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\nexport const WebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n WebSockets,\n WebSocketsSecure,\n HTTP,\n HTTPS,\n WebRTCStar,\n WebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS\n)\n\n// Unlike ws-star, stardust can run over any transport thus removing the requirement for websockets (but don't even think about running a stardust server over webrtc-star ;) )\nexport const Stardust = or(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n WebRTCStar,\n WebRTCDirect,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = () => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction) {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = new Multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's propably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n let out = null\n args.some((arg) => {\n const res = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n if (res != null) {\n out = res\n return true\n }\n return false\n })\n\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr) {\n let ma: Multiaddr\n\n try {\n ma = new Multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches: matches,\n partialMatch: partialMatch\n }\n}\n","import * as mafmt from '@multiformats/mafmt'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport {\n CODE_CIRCUIT,\n CODE_P2P,\n CODE_TCP,\n CODE_WS,\n CODE_WSS\n} from './constants.js'\n\nexport function all (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSockets.matches(testMa) ||\n mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function dnsWss (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n\nexport function dnsWsOrWss (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n // WS\n if (mafmt.WebSockets.matches(testMa)) {\n return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS))\n }\n\n // WSS\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n","import type { AbortOptions } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\n\nexport const symbol = Symbol.for('@libp2p/transport')\n\nexport interface ConnectionHandler { (connection: Connection): void }\n\nexport interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] }\n\nexport interface CreateListenerOptions {\n handler?: ConnectionHandler\n upgrader: Upgrader\n}\n\nexport interface DialOptions extends AbortOptions {\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport is understood as something that offers a dial and listen interface to establish connections.\n */\nexport interface Transport {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [symbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial: (ma: Multiaddr, options: DialOptions) => Promise\n\n /**\n * Create transport listeners.\n */\n createListener: (options: CreateListenerOptions) => Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid addresses for the transport\n */\n filter: MultiaddrFilter\n}\n\nexport interface ListenerEvents {\n 'connection': CustomEvent\n 'listening': CustomEvent\n 'error': CustomEvent\n 'close': CustomEvent\n}\n\nexport interface Listener extends EventEmitter {\n /**\n * Start a listener\n */\n listen: (multiaddr: Multiaddr) => Promise\n /**\n * Get listen addresses\n */\n getAddrs: () => Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise}\n */\n close: () => Promise\n}\n\nexport interface UpgraderEvents {\n 'connection': CustomEvent\n 'connectionEnd': CustomEvent\n}\n\nexport interface Upgrader extends EventEmitter {\n /**\n * Upgrades an outbound connection on `transport.dial`.\n */\n upgradeOutbound: (maConn: MultiaddrConnection) => Promise\n\n /**\n * Upgrades an inbound connection on transport listener.\n */\n upgradeInbound: (maConn: MultiaddrConnection) => Promise\n}\n\nexport interface ProtocolHandler {\n (stream: Duplex, connection: Connection): void\n}\n\nexport function isTransport (other: any): other is Transport {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface TransportManagerEvents {\n 'listener:listening': CustomEvent\n 'listener:close': CustomEvent\n}\n\nexport interface TransportManager extends EventEmitter {\n add: (transport: Transport) => void\n dial: (ma: Multiaddr, options?: any) => Promise\n getAddrs: () => Multiaddr[]\n getTransports: () => Transport[]\n transportForMultiaddr: (ma: Multiaddr) => Transport | undefined\n listen: (addrs: Multiaddr[]) => Promise\n remove: (key: string) => Promise\n removeAll: () => Promise\n}\n","import { connect, WebSocketOptions } from 'it-ws/client'\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri'\nimport { AbortError } from '@libp2p/interfaces/errors'\nimport pDefer from 'p-defer'\nimport { logger } from '@libp2p/logger'\nimport { isBrowser, isWebWorker } from 'wherearewe'\nimport { createListener } from './listener.js'\nimport { socketToMaConn } from './socket-to-conn.js'\nimport * as filters from './filters.js'\nimport { Transport, MultiaddrFilter, symbol, CreateListenerOptions, DialOptions } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\nimport type { ClientOptions } from 'ws'\nimport type { Server } from 'http'\n\nconst log = logger('libp2p:websockets')\n\nexport interface WebSocketsInit extends AbortOptions, WebSocketOptions {\n filter?: MultiaddrFilter\n websocket?: ClientOptions\n server?: Server\n}\n\nexport class WebSockets implements Transport {\n private readonly init?: WebSocketsInit\n\n constructor (init?: WebSocketsInit) {\n this.init = init\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/websockets'\n }\n\n get [symbol] (): true {\n return true\n }\n\n async dial (ma: Multiaddr, options: DialOptions): Promise {\n log('dialing %s', ma)\n options = options ?? {}\n\n const socket = await this._connect(ma, options)\n const maConn = socketToMaConn(socket, ma)\n log('new outbound connection %s', maConn.remoteAddr)\n\n const conn = await options.upgrader.upgradeOutbound(maConn)\n log('outbound connection %s upgraded', maConn.remoteAddr)\n return conn\n }\n\n async _connect (ma: Multiaddr, options: AbortOptions): Promise {\n if (options?.signal?.aborted === true) {\n throw new AbortError()\n }\n const cOpts = ma.toOptions()\n log('dialing %s:%s', cOpts.host, cOpts.port)\n\n const errorPromise = pDefer()\n const errfn = (err: any) => {\n log.error('connection error:', err)\n\n errorPromise.reject(err)\n }\n\n const rawSocket = connect(toUri(ma), this.init)\n\n if (rawSocket.socket.on != null) {\n rawSocket.socket.on('error', errfn)\n } else {\n rawSocket.socket.onerror = errfn\n }\n\n if (options.signal == null) {\n await Promise.race([rawSocket.connected(), errorPromise.promise])\n\n log('connected %s', ma)\n return rawSocket\n }\n\n // Allow abort via signal during connect\n let onAbort\n const abort = new Promise((resolve, reject) => {\n onAbort = () => {\n reject(new AbortError())\n // FIXME: https://github.com/libp2p/js-libp2p-websockets/issues/121\n setTimeout(() => {\n rawSocket.close().catch(err => {\n log.error('error closing raw socket', err)\n })\n })\n }\n\n // Already aborted?\n if (options?.signal?.aborted === true) {\n return onAbort()\n }\n\n options?.signal?.addEventListener('abort', onAbort)\n })\n\n try {\n await Promise.race([abort, errorPromise.promise, rawSocket.connected()])\n } finally {\n if (onAbort != null) {\n options?.signal?.removeEventListener('abort', onAbort)\n }\n }\n\n log('connected %s', ma)\n return rawSocket\n }\n\n /**\n * Creates a Websockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener (options: CreateListenerOptions) {\n return createListener({ ...this.init, ...options })\n }\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid Websockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n filter (multiaddrs: Multiaddr[]) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs)\n }\n\n // Browser\n if (isBrowser || isWebWorker) {\n return filters.dnsWss(multiaddrs)\n }\n\n return filters.all(multiaddrs)\n }\n}\n","\nexport function createListener () {\n throw new Error('WebSocket Servers can not be created in the browser!')\n}\n","\nimport all from 'it-all'\n\n/**\n * Collect all values from the iterable and sort them using\n * the passed sorter function\n *\n * @template T\n * @param {AsyncIterable | Iterable} iterable\n * @param {(a: T, b: T) => -1 | 0 | 1} sorter\n * @returns {AsyncIterable}\n */\nexport const sortAll = (iterable, sorter) => {\n return (async function * () {\n const values = await all(iterable)\n yield * values.sort(sorter)\n })()\n}\n\n/**\n * @param {string} s\n * @param {string} r\n */\nexport const replaceStartWith = (s, r) => {\n const matcher = new RegExp('^' + r)\n return s.replace(matcher, '')\n}\n","\nimport { nanoid } from 'nanoid'\nimport { SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/f98719ea086343f7b71f32ea9d9d521d')\n * ```\n */\n static random (): Key {\n return new Key(nanoid().replace(/-/g, ''))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n *\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n","import { urlAlphabet } from './url-alphabet/index.js'\nlet random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import { BaseDatastore } from './base.js'\nimport { Key } from 'interface-datastore/key'\nimport * as Errors from './errors.js'\n\n/**\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-store').Options} Options\n */\n\n/**\n * @class MemoryDatastore\n * @implements {Datastore}\n */\nexport class MemoryDatastore extends BaseDatastore {\n constructor () {\n super()\n\n /** @type {Record} */\n this.data = {}\n }\n\n open () {\n return Promise.resolve()\n }\n\n close () {\n return Promise.resolve()\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n */\n async put (key, val) { // eslint-disable-line require-await\n this.data[key.toString()] = val\n }\n\n /**\n * @param {Key} key\n */\n async get (key) {\n const exists = await this.has(key)\n if (!exists) throw Errors.notFoundError()\n return this.data[key.toString()]\n }\n\n /**\n * @param {Key} key\n */\n async has (key) { // eslint-disable-line require-await\n return this.data[key.toString()] !== undefined\n }\n\n /**\n * @param {Key} key\n */\n async delete (key) { // eslint-disable-line require-await\n delete this.data[key.toString()]\n }\n\n async * _all () {\n yield * Object.entries(this.data)\n .map(([key, value]) => ({ key: new Key(key), value }))\n }\n\n async * _allKeys () {\n yield * Object.entries(this.data)\n .map(([key]) => new Key(key))\n }\n}\n","import { sortAll } from './utils.js'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport take from 'it-take'\n\n/**\n * @typedef {import('interface-store').Options} Options\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Batch} Batch\n */\n\n/**\n * @template O\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * @implements {Datastore}\n */\nexport class BaseDatastore {\n /**\n * @returns {Promise}\n */\n open () {\n return Promise.reject(new Error('.open is not implemented'))\n }\n\n /**\n * @returns {Promise}\n */\n close () {\n return Promise.reject(new Error('.close is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n * @returns {Promise}\n */\n put (key, val, options) {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n get (key, options) {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n has (key, options) {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n delete (key, options) {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield { key, value }\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n for await (const key of source) {\n yield this.get(key, options)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * deleteMany (source, options = {}) {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Pair[]} */\n let puts = []\n /** @type {Key[]} */\n let dels = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\n\n delete (key) {\n dels.push(key)\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options))\n puts = []\n await drain(this.deleteMany(dels, options))\n dels = []\n }\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n *\n * @param {Query} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _all (q, options) {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n *\n * @param {KeyQuery} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q, options) {\n throw new Error('._allKeys is not implemented')\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (e) =>\n e.key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (key) =>\n key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n","import errCode from 'err-code'\n\n/**\n * @param {Error} [err]\n */\nexport function dbOpenFailedError (err) {\n err = err || new Error('Cannot open database')\n return errCode(err, 'ERR_DB_OPEN_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbDeleteFailedError (err) {\n err = err || new Error('Delete failed')\n return errCode(err, 'ERR_DB_DELETE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbWriteFailedError (err) {\n err = err || new Error('Write failed')\n return errCode(err, 'ERR_DB_WRITE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function notFoundError (err) {\n err = err || new Error('Not Found')\n return errCode(err, 'ERR_NOT_FOUND')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function abortedError (err) {\n err = err || new Error('Aborted')\n return errCode(err, 'ERR_ABORTED')\n}\n","export enum messages {\n NOT_STARTED_YET = 'The libp2p node is not started yet',\n DHT_DISABLED = 'DHT is not available',\n PUBSUB_DISABLED = 'PubSub is not available',\n CONN_ENCRYPTION_REQUIRED = 'At least one connection encryption module is required',\n ERR_TRANSPORTS_REQUIRED = 'At least one transport module is required',\n ERR_PROTECTOR_REQUIRED = 'Private network is enforced, but no protector was provided',\n NOT_FOUND = 'Not found'\n}\n\nexport enum codes {\n DHT_DISABLED = 'ERR_DHT_DISABLED',\n ERR_PUBSUB_DISABLED = 'ERR_PUBSUB_DISABLED',\n PUBSUB_NOT_STARTED = 'ERR_PUBSUB_NOT_STARTED',\n DHT_NOT_STARTED = 'ERR_DHT_NOT_STARTED',\n CONN_ENCRYPTION_REQUIRED = 'ERR_CONN_ENCRYPTION_REQUIRED',\n ERR_TRANSPORTS_REQUIRED = 'ERR_TRANSPORTS_REQUIRED',\n ERR_PROTECTOR_REQUIRED = 'ERR_PROTECTOR_REQUIRED',\n ERR_PEER_DIAL_INTERCEPTED = 'ERR_PEER_DIAL_INTERCEPTED',\n ERR_CONNECTION_INTERCEPTED = 'ERR_CONNECTION_INTERCEPTED',\n ERR_INVALID_PROTOCOLS_FOR_STREAM = 'ERR_INVALID_PROTOCOLS_FOR_STREAM',\n ERR_CONNECTION_ENDED = 'ERR_CONNECTION_ENDED',\n ERR_CONNECTION_FAILED = 'ERR_CONNECTION_FAILED',\n ERR_NODE_NOT_STARTED = 'ERR_NODE_NOT_STARTED',\n ERR_ALREADY_ABORTED = 'ERR_ALREADY_ABORTED',\n ERR_TOO_MANY_ADDRESSES = 'ERR_TOO_MANY_ADDRESSES',\n ERR_NO_VALID_ADDRESSES = 'ERR_NO_VALID_ADDRESSES',\n ERR_RELAYED_DIAL = 'ERR_RELAYED_DIAL',\n ERR_DIALED_SELF = 'ERR_DIALED_SELF',\n ERR_DISCOVERED_SELF = 'ERR_DISCOVERED_SELF',\n ERR_DUPLICATE_TRANSPORT = 'ERR_DUPLICATE_TRANSPORT',\n ERR_ENCRYPTION_FAILED = 'ERR_ENCRYPTION_FAILED',\n ERR_HOP_REQUEST_FAILED = 'ERR_HOP_REQUEST_FAILED',\n ERR_INVALID_KEY = 'ERR_INVALID_KEY',\n ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE',\n ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS',\n ERR_INVALID_PEER = 'ERR_INVALID_PEER',\n ERR_MUXER_UNAVAILABLE = 'ERR_MUXER_UNAVAILABLE',\n ERR_NOT_FOUND = 'ERR_NOT_FOUND',\n ERR_TIMEOUT = 'ERR_TIMEOUT',\n ERR_TRANSPORT_UNAVAILABLE = 'ERR_TRANSPORT_UNAVAILABLE',\n ERR_TRANSPORT_DIAL_FAILED = 'ERR_TRANSPORT_DIAL_FAILED',\n ERR_UNSUPPORTED_PROTOCOL = 'ERR_UNSUPPORTED_PROTOCOL',\n ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED = 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED',\n ERR_INVALID_MULTIADDR = 'ERR_INVALID_MULTIADDR',\n ERR_SIGNATURE_NOT_VALID = 'ERR_SIGNATURE_NOT_VALID',\n ERR_FIND_SELF = 'ERR_FIND_SELF',\n ERR_NO_ROUTERS_AVAILABLE = 'ERR_NO_ROUTERS_AVAILABLE',\n ERR_CONNECTION_NOT_MULTIPLEXED = 'ERR_CONNECTION_NOT_MULTIPLEXED',\n ERR_NO_DIAL_TOKENS = 'ERR_NO_DIAL_TOKENS',\n ERR_KEYCHAIN_REQUIRED = 'ERR_KEYCHAIN_REQUIRED',\n ERR_INVALID_CMS = 'ERR_INVALID_CMS',\n ERR_MISSING_KEYS = 'ERR_MISSING_KEYS',\n ERR_NO_KEY = 'ERR_NO_KEY',\n ERR_INVALID_KEY_NAME = 'ERR_INVALID_KEY_NAME',\n ERR_INVALID_KEY_TYPE = 'ERR_INVALID_KEY_TYPE',\n ERR_KEY_ALREADY_EXISTS = 'ERR_KEY_ALREADY_EXISTS',\n ERR_INVALID_KEY_SIZE = 'ERR_INVALID_KEY_SIZE',\n ERR_KEY_NOT_FOUND = 'ERR_KEY_NOT_FOUND',\n ERR_OLD_KEY_NAME_INVALID = 'ERR_OLD_KEY_NAME_INVALID',\n ERR_NEW_KEY_NAME_INVALID = 'ERR_NEW_KEY_NAME_INVALID',\n ERR_PASSWORD_REQUIRED = 'ERR_PASSWORD_REQUIRED',\n ERR_PEM_REQUIRED = 'ERR_PEM_REQUIRED',\n ERR_CANNOT_READ_KEY = 'ERR_CANNOT_READ_KEY',\n ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY',\n ERR_MISSING_PUBLIC_KEY = 'ERR_MISSING_PUBLIC_KEY',\n ERR_INVALID_OLD_PASS_TYPE = 'ERR_INVALID_OLD_PASS_TYPE',\n ERR_INVALID_NEW_PASS_TYPE = 'ERR_INVALID_NEW_PASS_TYPE',\n ERR_INVALID_PASS_LENGTH = 'ERR_INVALID_PASS_LENGTH',\n ERR_NOT_IMPLEMENTED = 'ERR_NOT_IMPLEMENTED',\n ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK',\n ERR_INVALID_RECORD = 'ERR_INVALID_RECORD',\n ERR_ALREADY_SUCCEEDED = 'ERR_ALREADY_SUCCEEDED',\n ERR_NO_HANDLER_FOR_PROTOCOL = 'ERR_NO_HANDLER_FOR_PROTOCOL',\n ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS',\n ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS'\n}\n","import errCode from 'err-code'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport type { Source } from 'it-stream-types'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\n/**\n * Store the multiaddrs from every peer in the passed peer store\n */\nexport async function * storeAddresses (source: Source, peerStore: PeerStore) {\n yield * map(source, async (peer) => {\n // ensure we have the addresses for a given peer\n await peerStore.addressBook.add(peer.id, peer.multiaddrs)\n\n return peer\n })\n}\n\n/**\n * Filter peers by unique peer id\n */\nexport function uniquePeers (source: Source) {\n /** @type Set */\n const seen = new Set()\n\n return filter(source, (peer) => {\n // dedupe by peer id\n if (seen.has(peer.id.toString())) {\n return false\n }\n\n seen.add(peer.id.toString())\n\n return true\n })\n}\n\n/**\n * Require at least `min` peers to be yielded from `source`\n */\nexport async function * requirePeers (source: Source, min: number = 1) {\n let seen = 0\n\n for await (const peer of source) {\n seen++\n\n yield peer\n }\n\n if (seen < min) {\n throw errCode(new Error('not found'), 'NOT_FOUND')\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes, messages } from './errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './content-routing/utils.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error module with no types\n} from 'set-delayed-interval'\nimport { setMaxListeners } from 'events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:peer-routing')\n\nexport interface RefreshManagerInit {\n /**\n * Whether to enable the Refresh manager\n */\n enabled?: boolean\n\n /**\n * Boot delay to start the Refresh Manager (in ms)\n */\n bootDelay?: number\n\n /**\n * Interval between each Refresh Manager run (in ms)\n */\n interval?: number\n\n /**\n * How long to let each refresh run (in ms)\n */\n timeout?: number\n}\n\nexport interface PeerRoutingInit {\n routers: PeerRouting[]\n refreshManager?: RefreshManagerInit\n}\n\nexport class DefaultPeerRouting implements PeerRouting, Startable {\n private readonly components: Components\n private readonly routers: PeerRouting[]\n private readonly refreshManagerInit: RefreshManagerInit\n private timeoutId?: ReturnType\n private started: boolean\n private abortController?: TimeoutController\n\n constructor (components: Components, init: PeerRoutingInit) {\n this.components = components\n this.routers = init.routers\n this.refreshManagerInit = init.refreshManager ?? {}\n this.started = false\n\n this._findClosestPeersTask = this._findClosestPeersTask.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start peer routing service.\n */\n async start () {\n if (this.started || this.routers.length === 0 || this.timeoutId != null || this.refreshManagerInit.enabled === false) {\n return\n }\n\n this.timeoutId = setDelayedInterval(\n this._findClosestPeersTask, this.refreshManagerInit.interval, this.refreshManagerInit.bootDelay\n )\n\n this.started = true\n }\n\n /**\n * Recurrent task to find closest peers and add their addresses to the Address Book.\n */\n async _findClosestPeersTask () {\n if (this.abortController != null) {\n // we are already running the query\n return\n }\n\n try {\n this.abortController = new TimeoutController(this.refreshManagerInit.timeout ?? 10e3)\n\n // this controller may be used while dialing lots of peers so prevent MaxListenersExceededWarning\n // appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.abortController.signal)\n } catch {}\n\n // nb getClosestPeers adds the addresses to the address book\n await drain(this.getClosestPeers(this.components.getPeerId().toBytes(), { signal: this.abortController.signal }))\n } catch (err: any) {\n log.error(err)\n } finally {\n this.abortController?.clear()\n this.abortController = undefined\n }\n }\n\n /**\n * Stop peer routing service.\n */\n async stop () {\n clearDelayedInterval(this.timeoutId)\n\n // abort query if it is in-flight\n this.abortController?.abort()\n\n this.started = false\n }\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: PeerId, options?: AbortOptions): Promise {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n if (id.toString() === this.components.getPeerId().toString()) {\n throw errCode(new Error('Should not try to find self'), codes.ERR_FIND_SELF)\n }\n\n const output = await pipe(\n merge(\n ...this.routers.map(router => (async function * () {\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n log.error(err)\n }\n })())\n ),\n (source) => filter(source, Boolean),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n async (source) => await first(source)\n )\n\n if (output != null) {\n return output\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options?: AbortOptions): AsyncIterable {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.getClosestPeers(key, options))\n ),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\n }\n}\n","import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './utils.js'\nimport drain from 'it-drain'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { CID } from 'multiformats/cid'\nimport type { Components } from '@libp2p/components'\n\nexport interface CompoundContentRoutingInit {\n routers: ContentRouting[]\n}\n\nexport class CompoundContentRouting implements ContentRouting, Startable {\n private readonly routers: ContentRouting[]\n private started: boolean\n private readonly components: Components\n\n constructor (components: Components, init: CompoundContentRoutingInit) {\n this.routers = init.routers ?? []\n this.started = false\n this.components = components\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n async stop () {\n this.started = false\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async * findProviders (key: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content this.routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.findProviders(key, options))\n ),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\n }\n\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide (key: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n await Promise.all(this.routers.map(async (router) => await router.provide(key, options)))\n }\n\n /**\n * Store the given key/value pair in the available content routings\n */\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions) {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.getDHT()\n\n if (dht != null) {\n await drain(dht.put(key, value, options))\n }\n }\n\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.getDHT()\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Get the `n` values to the given key without sorting\n */\n async * getMany (key: Uint8Array, nVals: number, options: AbortOptions) { // eslint-disable-line require-await\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n if (nVals == null || nVals === 0) {\n return\n }\n\n let gotValues = 0\n const dht = this.components.getDHT()\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n yield { from: event.from, val: event.value }\n\n gotValues++\n\n if (gotValues === nVals) {\n break\n }\n }\n }\n }\n\n if (gotValues === 0) {\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n }\n}\n","import { peerIdFromString } from '@libp2p/peer-id'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\n\nfunction peerIdFromMultiaddr (ma: Multiaddr) {\n const idStr = ma.getPeerId()\n\n if (idStr == null) {\n throw errCode(\n new Error(`${ma.toString()} does not have a valid peer type`),\n codes.ERR_INVALID_MULTIADDR\n )\n }\n\n try {\n return peerIdFromString(idStr)\n } catch (err: any) {\n throw errCode(\n new Error(`${ma.toString()} is not a valid peer type`),\n codes.ERR_INVALID_MULTIADDR\n )\n }\n}\n\n/**\n * Converts the given `peer` to a `Peer` object.\n */\nexport function getPeer (peer: PeerId | Multiaddr | string): PeerInfo {\n if (isPeerId(peer)) {\n return {\n id: peer,\n multiaddrs: [],\n protocols: []\n }\n }\n\n if (typeof peer === 'string') {\n peer = new Multiaddr(peer)\n }\n\n let addr\n\n if (Multiaddr.isMultiaddr(peer)) {\n addr = peer\n peer = peerIdFromMultiaddr(peer)\n }\n\n return {\n id: peer,\n multiaddrs: addr != null ? [addr] : [],\n protocols: []\n }\n}\n","import type { AddressManagerEvents } from '@libp2p/interface-address-manager'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Components } from '@libp2p/components'\n\nexport interface AddressManagerInit {\n announceFilter?: AddressFilter\n\n /**\n * list of multiaddrs string representation to listen\n */\n listen?: string[]\n\n /**\n * list of multiaddrs string representation to announce\n */\n announce?: string[]\n\n /**\n * list of multiaddrs string representation to never announce\n */\n noAnnounce?: string[]\n}\n\nexport interface AddressFilter {\n (addrs: Multiaddr[]): Multiaddr[]\n}\n\nconst defaultAddressFilter = (addrs: Multiaddr[]): Multiaddr[] => addrs\n\nexport class DefaultAddressManager extends EventEmitter {\n private readonly components: Components\n private readonly listen: Set\n private readonly announce: Set\n private readonly observed: Set\n private readonly announceFilter: AddressFilter\n\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor (components: Components, init: AddressManagerInit) {\n super()\n\n const { listen = [], announce = [] } = init\n\n this.components = components\n this.listen = new Set(listen.map(ma => ma.toString()))\n this.announce = new Set(announce.map(ma => ma.toString()))\n this.observed = new Set()\n this.announceFilter = init.announceFilter ?? defaultAddressFilter\n }\n\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs (): Multiaddr[] {\n return Array.from(this.listen).map((a) => new Multiaddr(a))\n }\n\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs (): Multiaddr[] {\n return Array.from(this.announce).map((a) => new Multiaddr(a))\n }\n\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs (): Multiaddr[] {\n return Array.from(this.observed).map((a) => new Multiaddr(a))\n }\n\n /**\n * Add peer observed addresses\n */\n addObservedAddr (addr: string | Multiaddr): void {\n let ma = new Multiaddr(addr)\n const remotePeer = ma.getPeerId()\n\n // strip our peer id if it has been passed\n if (remotePeer != null) {\n const remotePeerId = peerIdFromString(remotePeer)\n\n // use same encoding for comparison\n if (remotePeerId.equals(this.components.getPeerId())) {\n ma = ma.decapsulate(new Multiaddr(`/p2p/${this.components.getPeerId().toString()}`))\n }\n }\n\n const addrString = ma.toString()\n\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return\n }\n\n this.observed.add(addrString)\n this.dispatchEvent(new CustomEvent('change:addresses'))\n }\n\n getAddresses (): Multiaddr[] {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString())\n\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.getTransportManager().getAddrs().map(ma => ma.toString())\n }\n\n addrs = addrs.concat(this.getObservedAddrs().map(ma => ma.toString()))\n\n // dedupe multiaddrs\n const addrSet = new Set(addrs)\n\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => new Multiaddr(str)))\n .map(ma => {\n if (ma.getPeerId() === this.components.getPeerId().toString()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${this.components.getPeerId().toString()}`)\n })\n }\n}\n","/**\n * Thin ESM wrapper for CJS named exports.\n *\n * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1\n */\n\nimport mergeOptions from './index.js';\nexport default mergeOptions;\n","/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor:visibility-change-emitter')\n\ninterface VisibilityChangeEmitterEvents {\n 'visibilityChange': CustomEvent\n}\n\ntype Hidden = 'hidden' | 'mozHidden' | 'msHidden' | 'webkitHidden'\n\n/**\n * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.\n *\n * Warning: This does not work on all browsers, but should work on all modern browsers\n *\n * @example\n *\n * const myVisibilityEmitter = new VisibilityChangeEmitter();\n *\n * myVisibilityEmitter.on('visibilityChange', (pageInFocus) => {\n * if ( pageInFocus ){\n * // Page is in focus\n * console.log('In focus');\n * }\n * else {\n * // Page is blurred\n * console.log('Out of focus');\n * }\n * });\n * // To access the visibility state directly, call:\n * console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());\n */\nexport class VisibilityChangeEmitter extends EventEmitter {\n private hidden: Hidden\n private visibilityChange: string\n\n constructor () {\n super()\n\n this.hidden = 'hidden'\n this.visibilityChange = 'visibilityChange'\n\n if (globalThis.document != null) {\n this._initializeVisibilityVarNames()\n this._addVisibilityChangeListener()\n }\n }\n\n /**\n * document.hidden and document.visibilityChange are the two variables we need to check for;\n * Since these variables are named differently in different browsers, this function sets\n * the appropriate name based on the browser being used. Once executed, tha actual names of\n * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange\n * respectively\n *\n * @private\n */\n _initializeVisibilityVarNames () {\n let hidden: Hidden = 'hidden'\n let visibilityChange = 'visibilitychange'\n\n if (typeof globalThis.document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support\n hidden = 'hidden'\n visibilityChange = 'visibilitychange'\n // @ts-expect-error mozHidden is a non-standard field name\n } else if (typeof globalThis.document.mozHidden !== 'undefined') {\n hidden = 'mozHidden'\n visibilityChange = 'mozvisibilitychange'\n // @ts-expect-error msHidden is a non-standard field name\n } else if (typeof globalThis.document.msHidden !== 'undefined') {\n hidden = 'msHidden'\n visibilityChange = 'msvisibilitychange'\n // @ts-expect-error webkitHidden is a non-standard field name\n } else if (typeof globalThis.document.webkitHidden !== 'undefined') {\n hidden = 'webkitHidden'\n visibilityChange = 'webkitvisibilitychange'\n }\n\n this.hidden = hidden\n this.visibilityChange = visibilityChange\n }\n\n /**\n * Adds an event listener on the document that listens to changes in document.visibilityChange\n * (or whatever name by which the visibilityChange variable is known in the browser)\n *\n * @private\n */\n _addVisibilityChangeListener () {\n // @ts-expect-error cannot index document object with string key\n if (typeof globalThis.document.addEventListener === 'undefined' || typeof document[this.hidden] === 'undefined') {\n log('Checking page visibility requires a browser that supports the Page Visibility API.')\n } else {\n // Handle page visibility change\n globalThis.document.addEventListener(this.visibilityChange, this._handleVisibilityChange.bind(this), false)\n }\n }\n\n /**\n * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and\n * ```undefined``` if the page visibility API is not supported by the browser.\n */\n isVisible () {\n // @ts-expect-error cannot index document object with string key\n if (this.hidden === undefined || document[this.hidden] === undefined) {\n return undefined\n }\n\n // @ts-expect-error cannot index document object with string key\n return document[this.hidden] == null\n }\n\n /**\n * The function that is called when document.visibilityChange has changed\n * It emits an event called visibilityChange and sends the value of document.hidden as a\n * parameter\n *\n * @private\n */\n _handleVisibilityChange () {\n // @ts-expect-error cannot index document object with string key\n const visible = globalThis.document[this.hidden] === false\n log(visible ? 'Page Visible' : 'Page Hidden')\n\n // Emit the event\n this.dispatchEvent(new CustomEvent('visibilityChange', {\n detail: visible\n }))\n }\n}\n","/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { VisibilityChangeEmitter } from './visibility-change-emitter.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor')\n\nexport interface LatencyMonitorEvents {\n 'data': CustomEvent\n}\n\nexport interface LatencyMonitorInit {\n /**\n * How often to add a latency check event (ms)\n */\n latencyCheckIntervalMs?: number\n\n /**\n * How often to summarize latency check events. null or 0 disables event firing\n */\n dataEmitIntervalMs?: number\n\n /**\n * What cb-style async function to use\n */\n asyncTestFn?: (cb: () => void) => void\n\n /**\n * What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.\n */\n latencyRandomPercentage?: number\n}\n\nexport interface SummaryObject {\n /**\n * How many events were called\n */\n events: number\n\n /**\n * What was the min time for a cb to be called\n */\n minMs: number\n\n /**\n * What was the max time for a cb to be called\n */\n maxMs: number\n\n /**\n * What was the average time for a cb to be called\n */\n avgMs: number\n\n /**\n * How long this interval was in ms\n */\n lengthMs: number\n}\n\ninterface LatencyData {\n startTime: number\n events: number\n minMs: number\n maxMs: number\n totalMs: number\n}\n\n/**\n * A class to monitor latency of any async function which works in a browser or node. This works by periodically calling\n * the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this.\n * This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0.\n *\n * @extends {EventEmitter}\n *\n * The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop\n * and timing how long it takes to get back.\n *\n * @example\n * const monitor = new LatencyMonitor();\n * monitor.on('data', (summary) => console.log('Event Loop Latency: %O', summary));\n *\n * @example\n * const monitor = new LatencyMonitor({latencyCheckIntervalMs: 1000, dataEmitIntervalMs: 60000, asyncTestFn:ping});\n * monitor.on('data', (summary) => console.log('Ping Pong Latency: %O', summary));\n */\nexport class LatencyMonitor extends EventEmitter {\n private readonly latencyCheckIntervalMs: number\n private readonly latencyRandomPercentage: number\n private readonly latencyCheckMultiply: number\n private readonly latencyCheckSubtract: number\n private readonly dataEmitIntervalMs?: number\n private readonly asyncTestFn?: (cb: () => void) => void\n\n private readonly now: (num?: any) => any\n private readonly getDeltaMS: (num: number) => number\n private visibilityChangeEmitter?: VisibilityChangeEmitter\n private latencyData: LatencyData\n private checkLatencyID?: NodeJS.Timeout\n private emitIntervalID?: NodeJS.Timeout\n\n constructor (init: LatencyMonitorInit = {}) {\n super()\n\n const { latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = init\n\n // 0 isn't valid here, so its ok to use ||\n this.latencyCheckIntervalMs = latencyCheckIntervalMs ?? 500 // 0.5s\n this.latencyRandomPercentage = latencyRandomPercentage ?? 10\n this.latencyCheckMultiply = 2 * (this.latencyRandomPercentage / 100.0) * this.latencyCheckIntervalMs\n this.latencyCheckSubtract = this.latencyCheckMultiply / 2\n\n this.dataEmitIntervalMs = (dataEmitIntervalMs === null || dataEmitIntervalMs === 0)\n ? undefined\n : dataEmitIntervalMs ?? 5 * 1000 // 5s\n log('latencyCheckIntervalMs: %s dataEmitIntervalMs: %s',\n this.latencyCheckIntervalMs, this.dataEmitIntervalMs)\n if (this.dataEmitIntervalMs != null) {\n log('Expecting ~%s events per summary', this.latencyCheckIntervalMs / this.dataEmitIntervalMs)\n } else {\n log('Not emitting summaries')\n }\n\n this.asyncTestFn = asyncTestFn // If there is no asyncFn, we measure latency\n\n // If process: use high resolution timer\n if (globalThis.process?.hrtime != null) {\n log('Using process.hrtime for timing')\n this.now = globalThis.process.hrtime // eslint-disable-line no-undef\n this.getDeltaMS = (startTime) => {\n const hrtime = this.now(startTime)\n return (hrtime[0] * 1000) + (hrtime[1] / 1000000)\n }\n // Let's try for a timer that only monotonically increases\n } else if (typeof window !== 'undefined' && window.performance?.now != null) {\n log('Using performance.now for timing')\n this.now = window.performance.now.bind(window.performance)\n this.getDeltaMS = (startTime) => Math.round(this.now() - startTime)\n } else {\n log('Using Date.now for timing')\n this.now = Date.now\n this.getDeltaMS = (startTime) => this.now() - startTime\n }\n\n this.latencyData = this.initLatencyData()\n }\n\n start () {\n // We check for isBrowser because of browsers set max rates of timeouts when a page is hidden,\n // so we fall back to another library\n // See: http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs\n if (isBrowser()) {\n this.visibilityChangeEmitter = new VisibilityChangeEmitter()\n\n this.visibilityChangeEmitter.addEventListener('visibilityChange', (evt) => {\n const { detail: pageInFocus } = evt\n\n if (pageInFocus) {\n this._startTimers()\n } else {\n this._emitSummary()\n this._stopTimers()\n }\n })\n }\n\n if (this.visibilityChangeEmitter?.isVisible() === true) {\n this._startTimers()\n }\n }\n\n stop () {\n this._stopTimers()\n }\n\n /**\n * Start internal timers\n *\n * @private\n */\n _startTimers () {\n // Timer already started, ignore this\n if (this.checkLatencyID != null) {\n return\n }\n\n this.checkLatency()\n\n if (this.dataEmitIntervalMs != null) {\n this.emitIntervalID = setInterval(() => this._emitSummary(), this.dataEmitIntervalMs)\n if (typeof this.emitIntervalID.unref === 'function') {\n this.emitIntervalID.unref() // Doesn't block exit\n }\n }\n }\n\n /**\n * Stop internal timers\n *\n * @private\n */\n _stopTimers () {\n if (this.checkLatencyID != null) {\n clearTimeout(this.checkLatencyID)\n this.checkLatencyID = undefined\n }\n if (this.emitIntervalID != null) {\n clearInterval(this.emitIntervalID)\n this.emitIntervalID = undefined\n }\n }\n\n /**\n * Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show\n *\n * @private\n */\n _emitSummary () {\n const summary = this.getSummary()\n if (summary.events > 0) {\n this.dispatchEvent(new CustomEvent('data', {\n detail: summary\n }))\n }\n }\n\n /**\n * Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue,\n * it will not count for this time period\n */\n getSummary (): SummaryObject {\n // We might want to adjust for the number of expected events\n // Example: first 1 event it comes back, then such a long blocker that the next emit check comes\n // Then this fires - looks like no latency!!\n const latency = {\n events: this.latencyData.events,\n minMs: this.latencyData.minMs,\n maxMs: this.latencyData.maxMs,\n avgMs: this.latencyData.events > 0\n ? this.latencyData.totalMs / this.latencyData.events\n : Number.POSITIVE_INFINITY,\n lengthMs: this.getDeltaMS(this.latencyData.startTime)\n }\n this.latencyData = this.initLatencyData() // Clear\n\n log.trace('Summary: %O', latency)\n return latency\n }\n\n /**\n * Randomly calls an async fn every roughly latencyCheckIntervalMs (plus some randomness). If no async fn is found,\n * it will simply report on event loop latency.\n */\n checkLatency () {\n // Randomness is needed to avoid alignment by accident to regular things in the event loop\n const randomness = (Math.random() * this.latencyCheckMultiply) - this.latencyCheckSubtract\n\n // We use this to ensure that in case some overlap somehow, we don't take the wrong startTime/offset\n const localData = {\n deltaOffset: Math.ceil(this.latencyCheckIntervalMs + randomness),\n startTime: this.now()\n }\n\n const cb = () => {\n // We are already stopped, ignore this datapoint\n if (this.checkLatencyID == null) {\n return\n }\n const deltaMS = this.getDeltaMS(localData.startTime) - localData.deltaOffset\n this.checkLatency() // Start again ASAP\n\n // Add the data point. If this gets complex, refactor it\n this.latencyData.events++\n this.latencyData.minMs = Math.min(this.latencyData.minMs, deltaMS)\n this.latencyData.maxMs = Math.max(this.latencyData.maxMs, deltaMS)\n this.latencyData.totalMs += deltaMS\n log.trace('MS: %s Data: %O', deltaMS, this.latencyData)\n }\n log.trace('localData: %O', localData)\n\n this.checkLatencyID = setTimeout(() => {\n // This gets rid of including event loop\n if (this.asyncTestFn != null) {\n // Clear timing related things\n localData.deltaOffset = 0\n localData.startTime = this.now()\n this.asyncTestFn(cb)\n } else {\n // setTimeout is not more accurate than 1ms, so this will ensure positive numbers. Add 1 to emitted data to remove.\n // This is not the best, but for now it'll be just fine. This isn't meant to be sub ms accurate.\n localData.deltaOffset -= 1\n // If there is no function to test, we mean check latency which is a special case that is really cb => cb()\n // We avoid that for the few extra function all overheads. Also, we want to keep the timers different\n cb()\n }\n }, localData.deltaOffset)\n\n if (typeof this.checkLatencyID.unref === 'function') {\n this.checkLatencyID.unref() // Doesn't block exit\n }\n }\n\n initLatencyData (): LatencyData {\n return {\n startTime: this.now(),\n minMs: Number.POSITIVE_INFINITY,\n maxMs: Number.NEGATIVE_INFINITY,\n events: 0,\n totalMs: 0\n }\n }\n}\n\nfunction isBrowser () {\n return typeof globalThis.window !== 'undefined'\n}\n","\nexport const OPEN = 'OPEN'\nexport const CLOSING = 'CLOSING'\nexport const CLOSED = 'CLOSED'\n","import errCode from 'err-code'\nimport { anySignal } from 'any-signal'\nimport FIFO from 'p-fifo'\nimport { setMaxListeners } from 'events'\nimport { codes } from '../../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Dialer } from './index.js'\n\nconst log = logger('libp2p:dialer:dial-request')\n\nexport interface DialAction {\n (m: Multiaddr, options: AbortOptions): Promise\n}\n\nexport interface DialRequestOptions {\n addrs: Multiaddr[]\n dialAction: DialAction\n dialer: Dialer\n}\n\nexport class DialRequest {\n private readonly addrs: Multiaddr[]\n private readonly dialer: Dialer\n private readonly dialAction: DialAction\n\n /**\n * Manages running the `dialAction` on multiple provided `addrs` in parallel\n * up to a maximum determined by the number of tokens returned\n * from `dialer.getTokens`. Once a DialRequest is created, it can be\n * started using `DialRequest.run(options)`. Once a single dial has succeeded,\n * all other dials in the request will be cancelled.\n */\n constructor (options: DialRequestOptions) {\n const {\n addrs,\n dialAction,\n dialer\n } = options\n\n this.addrs = addrs\n this.dialer = dialer\n this.dialAction = dialAction\n }\n\n async run (options: AbortOptions = {}): Promise {\n const tokens = this.dialer.getTokens(this.addrs.length)\n\n // If no tokens are available, throw\n if (tokens.length < 1) {\n throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS)\n }\n\n const tokenHolder = new FIFO()\n\n for (const token of tokens) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n }\n\n const dialAbortControllers: Array<(AbortController | undefined)> = this.addrs.map(() => {\n const controller = new AbortController()\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n return controller\n })\n\n if (options.signal != null) {\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, options.signal)\n } catch {}\n }\n\n let completedDials = 0\n let done = false\n\n try {\n return await Promise.any(this.addrs.map(async (addr, i) => {\n const token = await tokenHolder.shift() // get token\n // End attempt once another attempt succeeded\n if (done) {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED)\n }\n\n const controller = dialAbortControllers[i]\n if (controller == null) {\n throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS)\n }\n let conn\n try {\n const signal = controller.signal\n conn = await this.dialAction(addr, { ...options, signal: (options.signal != null) ? anySignal([signal, options.signal]) : signal })\n // Remove the successful AbortController so it is not aborted\n dialAbortControllers[i] = undefined\n } finally {\n completedDials++\n // If we have more or equal dials remaining than tokens, recycle the token, otherwise release it\n if (this.addrs.length - completedDials >= tokens.length) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n } else {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n }\n }\n\n if (conn == null) {\n // Notify Promise.any that attempt was not successful\n // to prevent from returning undefined despite there\n // were successful dial attempts\n throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED)\n } else {\n // This dial succeeded, don't attempt anything else\n done = true\n }\n\n return conn\n }))\n } finally {\n // success/failure happened, abort everything else\n dialAbortControllers.forEach(c => {\n if (c !== undefined) {\n c.abort()\n }\n })\n tokens.forEach(token => this.dialer.releaseToken(token)) // release tokens back to the dialer\n }\n }\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport isIpPrivate from 'private-ip'\n\n/**\n * Check if a given multiaddr has a private address.\n */\nexport function isPrivate (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return Boolean(isIpPrivate(address))\n}\n","import type { Address } from '@libp2p/interface-peer-store'\nimport { isPrivate } from './multiaddr/is-private.js'\n\n/**\n * Compare function for array.sort().\n * This sort aims to move the private addresses to the end of the array.\n * In case of equality, a certified address will come first.\n */\nexport function publicAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n const isAPrivate = isPrivate(a.multiaddr)\n const isBPrivate = isPrivate(b.multiaddr)\n\n if (isAPrivate && !isBPrivate) {\n return 1\n } else if (!isAPrivate && isBPrivate) {\n return -1\n }\n // Check certified?\n if (a.isCertified && !b.isCertified) {\n return -1\n } else if (!a.isCertified && b.isCertified) {\n return 1\n }\n\n return 0\n}\n","\n/**\n * How long in ms a dial attempt is allowed to take\n */\nexport const DIAL_TIMEOUT = 30e3\n\n/**\n * How long in ms an inbound connection upgrade is allowed to take\n */\nexport const INBOUND_UPGRADE_TIMEOUT = 30e3\n\n/**\n * Maximum allowed concurrent dials\n */\nexport const MAX_PARALLEL_DIALS = 100\n\n/**\n * Allowed parallel dials per DialRequest\n */\nexport const MAX_PER_PEER_DIALS = 4\n\n/**\n * Maximum number of allowed addresses to attempt to dial\n */\nexport const MAX_ADDRS_TO_DIAL = 25\n\nexport const METRICS = {\n computeThrottleMaxQueueSize: 1000,\n computeThrottleTimeout: 2000,\n movingAverageIntervals: [\n 60 * 1000, // 1 minute\n 5 * 60 * 1000, // 5 minutes\n 15 * 60 * 1000 // 15 minutes\n ],\n maxOldPeersRetention: 50\n}\n","import { logger } from '@libp2p/logger'\nimport all from 'it-all'\nimport filter from 'it-filter'\nimport { pipe } from 'it-pipe'\nimport errCode from 'err-code'\nimport { Multiaddr, Resolver } from '@multiformats/multiaddr'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { AbortError } from '@libp2p/interfaces/errors'\nimport { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'events'\nimport { DialAction, DialRequest } from './dial-request.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport { codes } from '../../errors.js'\nimport {\n DIAL_TIMEOUT,\n MAX_PARALLEL_DIALS,\n MAX_PER_PEER_DIALS,\n MAX_ADDRS_TO_DIAL\n} from '../../constants.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { getPeer } from '../../get-peer.js'\nimport sort from 'it-sort'\nimport { Components, Initializable } from '@libp2p/components'\nimport map from 'it-map'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { ComponentMetricsTracker } from '@libp2p/interface-metrics'\n\nconst log = logger('libp2p:dialer')\n\nconst METRICS_COMPONENT = 'dialler'\nconst METRICS_PENDING_DIALS = 'pending-dials'\nconst METRICS_PENDING_DIAL_TARGETS = 'pending-dial-targets'\n\nexport interface DialTarget {\n id: string\n addrs: Multiaddr[]\n}\n\nexport interface PendingDial {\n dialRequest: DialRequest\n controller: TimeoutController\n promise: Promise\n destroy: () => void\n}\n\nexport interface PendingDialTarget {\n resolve: (value: any) => void\n reject: (err: Error) => void\n}\n\nexport interface DialerInit {\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take\n */\n dialTimeout?: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n metrics?: ComponentMetricsTracker\n}\n\nexport class Dialer implements Startable, Initializable {\n private components: Components = new Components()\n private readonly addressSorter: AddressSorter\n private readonly maxAddrsToDial: number\n private readonly timeout: number\n private readonly maxDialsPerPeer: number\n public tokens: number[]\n public pendingDials: Map\n public pendingDialTargets: Map\n private started: boolean\n\n constructor (init: DialerInit = {}) {\n this.started = false\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxAddrsToDial = init.maxAddrsToDial ?? MAX_ADDRS_TO_DIAL\n this.timeout = init.dialTimeout ?? DIAL_TIMEOUT\n this.maxDialsPerPeer = init.maxDialsPerPeer ?? MAX_PER_PEER_DIALS\n this.tokens = [...new Array(init.maxParallelDials ?? MAX_PARALLEL_DIALS)].map((_, index) => index)\n this.pendingDials = trackedMap({\n component: METRICS_COMPONENT,\n metric: METRICS_PENDING_DIALS,\n metrics: init.metrics\n })\n this.pendingDialTargets = trackedMap({\n component: METRICS_COMPONENT,\n metric: METRICS_PENDING_DIAL_TARGETS,\n metrics: init.metrics\n })\n\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n Multiaddr.resolvers.set(key, value)\n }\n }\n\n init (components: Components): void {\n this.components = components\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n /**\n * Clears any pending dials\n */\n async stop () {\n this.started = false\n\n for (const dial of this.pendingDials.values()) {\n try {\n dial.controller.abort()\n } catch (err: any) {\n log.error(err)\n }\n }\n this.pendingDials.clear()\n\n for (const pendingTarget of this.pendingDialTargets.values()) {\n pendingTarget.reject(new AbortError('Dialer was destroyed'))\n }\n this.pendingDialTargets.clear()\n }\n\n /**\n * Connects to a given `peer` by dialing all of its known addresses.\n * The dial to the first address that is successfully able to upgrade a connection\n * will be used.\n */\n async dial (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (this.components.getPeerId().equals(id)) {\n throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF)\n }\n\n log('check multiaddrs %p', id)\n\n if (multiaddrs != null && multiaddrs.length > 0) {\n log('storing multiaddrs %p', id, multiaddrs)\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n if (await this.components.getConnectionGater().denyDialPeer(id)) {\n throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED)\n }\n\n log('creating dial target for %p', id)\n\n const dialTarget = await this._createCancellableDialTarget(id, options)\n\n if (dialTarget.addrs.length === 0) {\n throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES)\n }\n\n const pendingDial = this.pendingDials.get(dialTarget.id) ?? this._createPendingDial(dialTarget, options)\n\n try {\n const connection = await pendingDial.promise\n log('dial succeeded to %s', dialTarget.id)\n return connection\n } catch (err: any) {\n log('dial failed to %s', dialTarget.id, err)\n // Error is a timeout\n if (pendingDial.controller.signal.aborted) {\n err.code = codes.ERR_TIMEOUT\n }\n log.error(err)\n throw err\n } finally {\n pendingDial.destroy()\n }\n }\n\n /**\n * Connects to a given `peer` by dialing all of its known addresses.\n * The dial to the first address that is successfully able to upgrade a connection\n * will be used.\n */\n async _createCancellableDialTarget (peer: PeerId, options: AbortOptions): Promise {\n // Make dial target promise cancellable\n const id = `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n const cancellablePromise = new Promise((resolve, reject) => {\n this.pendingDialTargets.set(id, { resolve, reject })\n })\n\n try {\n const dialTarget = await Promise.race([\n this._createDialTarget(peer, options),\n cancellablePromise\n ])\n\n return dialTarget\n } finally {\n this.pendingDialTargets.delete(id)\n }\n }\n\n /**\n * Creates a DialTarget. The DialTarget is used to create and track\n * the DialRequest to a given peer.\n * If a multiaddr is received it should be the first address attempted.\n * Multiaddrs not supported by the available transports will be filtered out.\n */\n async _createDialTarget (peer: PeerId, options: AbortOptions): Promise {\n const knownAddrs = await pipe(\n await this.components.getPeerStore().addressBook.get(peer),\n (source) => filter(source, async (address) => {\n return !(await this.components.getConnectionGater().denyDialMultiaddr(peer, address.multiaddr))\n }),\n (source) => sort(source, this.addressSorter),\n (source) => map(source, (address) => {\n const ma = address.multiaddr\n\n if (peer.toString() === ma.getPeerId()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${peer.toString()}`)\n }),\n async (source) => await all(source)\n )\n\n const addrs: Multiaddr[] = []\n for (const a of knownAddrs) {\n const resolvedAddrs = await this._resolve(a, options)\n resolvedAddrs.forEach(ra => addrs.push(ra))\n }\n\n // Multiaddrs not supported by the available transports will be filtered out.\n const supportedAddrs = addrs.filter(a => this.components.getTransportManager().transportForMultiaddr(a))\n\n if (supportedAddrs.length > this.maxAddrsToDial) {\n await this.components.getPeerStore().delete(peer)\n throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES)\n }\n\n return {\n id: peer.toString(),\n addrs: supportedAddrs\n }\n }\n\n /**\n * Creates a PendingDial that wraps the underlying DialRequest\n */\n _createPendingDial (dialTarget: DialTarget, options: AbortOptions = {}): PendingDial {\n /**\n * @param {Multiaddr} addr\n * @param {{ signal: { aborted: any; }; }} options\n */\n const dialAction: DialAction = async (addr, options = {}) => {\n if (options.signal?.aborted === true) {\n throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)\n }\n\n return await this.components.getTransportManager().dial(addr, options).catch(err => {\n log.error('dial to %s failed', addr, err)\n throw err\n })\n }\n\n const dialRequest = new DialRequest({\n addrs: dialTarget.addrs,\n dialAction,\n dialer: this\n })\n\n // Combine the timeout signal and options.signal, if provided\n const timeoutController = new TimeoutController(this.timeout)\n\n const signals = [timeoutController.signal]\n ;(options.signal != null) && signals.push(options.signal)\n const signal = anySignal(signals)\n\n // this signal will potentially be used while dialing lots of\n // peers so prevent MaxListenersExceededWarning appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, signal)\n } catch {}\n\n const pendingDial = {\n dialRequest,\n controller: timeoutController,\n promise: dialRequest.run({ ...options, signal }),\n destroy: () => {\n timeoutController.clear()\n this.pendingDials.delete(dialTarget.id)\n }\n }\n this.pendingDials.set(dialTarget.id, pendingDial)\n\n return pendingDial\n }\n\n getTokens (num: number) {\n const total = Math.min(num, this.maxDialsPerPeer, this.tokens.length)\n const tokens = this.tokens.splice(0, total)\n log('%d tokens request, returning %d, %d remaining', num, total, this.tokens.length)\n return tokens\n }\n\n releaseToken (token: number) {\n // Guard against duplicate releases\n if (this.tokens.includes(token)) {\n return\n }\n\n log('token %d released', token)\n this.tokens.push(token)\n }\n\n /**\n * Resolve multiaddr recursively\n */\n async _resolve (ma: Multiaddr, options: AbortOptions): Promise {\n // TODO: recursive logic should live in multiaddr once dns4/dns6 support is in place\n // Now only supporting resolve for dnsaddr\n const resolvableProto = ma.protoNames().includes('dnsaddr')\n\n // Multiaddr is not resolvable? End recursion!\n if (!resolvableProto) {\n return [ma]\n }\n\n const resolvedMultiaddrs = await this._resolveRecord(ma, options)\n const recursiveMultiaddrs = await Promise.all(resolvedMultiaddrs.map(async (nm) => {\n return await this._resolve(nm, options)\n }))\n\n const addrs = recursiveMultiaddrs.flat()\n return addrs.reduce((array, newM) => {\n if (array.find(m => m.equals(newM)) == null) {\n array.push(newM)\n }\n return array\n }, ([]))\n }\n\n /**\n * Resolve a given multiaddr. If this fails, an empty array will be returned\n */\n async _resolveRecord (ma: Multiaddr, options: AbortOptions): Promise {\n try {\n ma = new Multiaddr(ma.toString()) // Use current multiaddr module\n const multiaddrs = await ma.resolve(options)\n return multiaddrs\n } catch (err) {\n log.error(`multiaddr ${ma.toString()} could not be resolved`, err)\n return []\n }\n }\n}\n","\nexport const KEEP_ALIVE = 'keep-alive'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport mergeOptions from 'merge-options'\nimport { LatencyMonitor, SummaryObject } from './latency-monitor.js'\n// @ts-expect-error retimer does not have types\nimport retimer from 'retimer'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { codes } from '../errors.js'\nimport { isPeerId, PeerId } from '@libp2p/interface-peer-id'\nimport { setMaxListeners } from 'events'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport { Components, Initializable } from '@libp2p/components'\nimport * as STATUS from '@libp2p/interface-connection/status'\nimport { Dialer } from './dialer/index.js'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { Resolver } from '@multiformats/multiaddr'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { KEEP_ALIVE } from '@libp2p/interface-peer-store/tags'\n\nconst log = logger('libp2p:connection-manager')\n\nconst defaultOptions: Partial = {\n maxConnections: Infinity,\n minConnections: 0,\n maxData: Infinity,\n maxSentData: Infinity,\n maxReceivedData: Infinity,\n maxEventLoopDelay: Infinity,\n pollInterval: 2000,\n autoDialInterval: 10000,\n movingAverageInterval: 60000\n}\n\nconst METRICS_SYSTEM = 'libp2p'\nconst METRICS_COMPONENT = 'connection-manager'\nconst STARTUP_RECONNECT_TIMEOUT = 60000\n\nexport interface ConnectionManagerInit {\n /**\n * The maximum number of connections to keep open\n */\n maxConnections: number\n\n /**\n * The minimum number of connections to keep open\n */\n minConnections: number\n\n /**\n * The max data (in and out), per average interval to allow\n */\n maxData?: number\n\n /**\n * The max outgoing data, per average interval to allow\n */\n maxSentData?: number\n\n /**\n * The max incoming data, per average interval to allow\n */\n maxReceivedData?: number\n\n /**\n * The upper limit the event loop can take to run\n */\n maxEventLoopDelay?: number\n\n /**\n * How often, in milliseconds, metrics and latency should be checked\n */\n pollInterval?: number\n\n /**\n * How often, in milliseconds, to compute averages\n */\n movingAverageInterval?: number\n\n /**\n * If true, try to connect to all discovered peers up to the connection manager limit\n */\n autoDial?: boolean\n\n /**\n * How long to wait between attempting to keep our number of concurrent connections\n * above minConnections\n */\n autoDialInterval: number\n\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take, including DNS resolution\n * of the multiaddr, opening a socket and upgrading it to a Connection.\n */\n dialTimeout?: number\n\n /**\n * When a new inbound connection is opened, the upgrade process (e.g. protect,\n * encrypt, multiplex etc) must complete within this number of ms.\n */\n inboundUpgradeTimeout: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n\n /**\n * On startup we try to dial any peer that has previously been\n * tagged with KEEP_ALIVE up to this timeout in ms. (default: 60000)\n */\n startupReconnectTimeout?: number\n}\n\nexport interface ConnectionManagerEvents {\n 'peer:connect': CustomEvent\n 'peer:disconnect': CustomEvent\n}\n\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager extends EventEmitter implements ConnectionManager, Startable, Initializable {\n public readonly dialer: Dialer\n private components = new Components()\n private readonly opts: Required\n private readonly connections: Map\n private started: boolean\n private timer?: ReturnType\n private readonly latencyMonitor: LatencyMonitor\n private readonly startupReconnectTimeout: number\n private connectOnStartupController?: TimeoutController\n private readonly dialTimeout: number\n\n constructor (init: ConnectionManagerInit) {\n super()\n\n this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n\n if (this.opts.maxConnections < this.opts.minConnections) {\n throw errCode(new Error('Connection Manager maxConnections must be greater than minConnections'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log('options: %o', this.opts)\n\n /**\n * Map of connections per peer\n */\n this.connections = new Map()\n\n this.started = false\n this._checkMetrics = this._checkMetrics.bind(this)\n\n this.latencyMonitor = new LatencyMonitor({\n latencyCheckIntervalMs: init.pollInterval,\n dataEmitIntervalMs: init.pollInterval\n })\n\n try {\n // This emitter gets listened to a lot\n setMaxListeners?.(Infinity, this)\n } catch {}\n\n this.dialer = new Dialer(this.opts)\n\n this.onConnect = this.onConnect.bind(this)\n this.onDisconnect = this.onDisconnect.bind(this)\n\n this.startupReconnectTimeout = init.startupReconnectTimeout ?? STARTUP_RECONNECT_TIMEOUT\n this.dialTimeout = init.dialTimeout ?? 30000\n }\n\n init (components: Components): void {\n this.components = components\n\n this.dialer.init(components)\n\n // track inbound/outbound connections\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'connections',\n label: 'direction',\n value: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n }\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.stat.direction === 'inbound') {\n metric.inbound++\n } else {\n metric.outbound++\n }\n }\n }\n\n return metric\n }\n })\n\n // track total number of streams per protocol\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'protocol-streams-total',\n label: 'protocol',\n value: () => {\n const metric: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n metric[key] = (metric[key] ?? 0) + 1\n }\n }\n }\n\n return metric\n }\n })\n\n // track 90th percentile of streams per protocol\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'protocol-streams-per-connection-90th-percentile',\n label: 'protocol',\n value: () => {\n const allStreams: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams: Record = {}\n\n for (const stream of conn.streams) {\n const key = `${stream.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n streams[key] = (streams[key] ?? 0) + 1\n }\n\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? []\n allStreams[protocol].push(count)\n }\n }\n }\n\n const metric: Record = {}\n\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b)\n\n const index = Math.floor(counts.length * 0.9)\n metric[protocol] = counts[index]\n }\n\n return metric\n }\n })\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start () {\n if (this.components.getMetrics() != null) {\n this.timer = this.timer ?? retimer(this._checkMetrics, this.opts.pollInterval)\n }\n\n // latency monitor\n this.latencyMonitor.start()\n this._onLatencyMeasure = this._onLatencyMeasure.bind(this)\n this.latencyMonitor.addEventListener('data', this._onLatencyMeasure)\n await this.dialer.start()\n\n this.started = true\n log('started')\n }\n\n async afterStart () {\n this.components.getUpgrader().addEventListener('connection', this.onConnect)\n this.components.getUpgrader().addEventListener('connectionEnd', this.onDisconnect)\n\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers: PeerId[] = []\n\n for (const peer of await this.components.getPeerStore().all()) {\n const tags = await this.components.getPeerStore().getTags(peer.id)\n const hasKeepAlive = tags.filter(tag => tag.name === KEEP_ALIVE).length > 0\n\n if (hasKeepAlive) {\n keepAlivePeers.push(peer.id)\n }\n }\n\n this.connectOnStartupController?.clear()\n this.connectOnStartupController = new TimeoutController(this.startupReconnectTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.connectOnStartupController.signal)\n } catch {}\n\n await Promise.all(\n keepAlivePeers.map(async peer => {\n await this.openConnection(peer, {\n signal: this.connectOnStartupController?.signal\n })\n .catch(err => {\n log.error(err)\n })\n })\n )\n })\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n this.connectOnStartupController?.clear()\n })\n }\n\n async beforeStop () {\n // if we are still dialing KEEP_ALIVE peers, abort those dials\n this.connectOnStartupController?.abort()\n this.components.getUpgrader().removeEventListener('connection', this.onConnect)\n this.components.getUpgrader().removeEventListener('connectionEnd', this.onDisconnect)\n }\n\n /**\n * Stops the Connection Manager\n */\n async stop () {\n this.timer?.clear()\n\n this.latencyMonitor.removeEventListener('data', this._onLatencyMeasure)\n this.latencyMonitor.stop()\n await this.dialer.stop()\n\n this.started = false\n await this._close()\n log('stopped')\n }\n\n /**\n * Cleans up the connections\n */\n async _close () {\n // Close all connections we're tracking\n const tasks: Array> = []\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close()\n } catch (err) {\n log.error(err)\n }\n })())\n }\n }\n\n log('closing %d connections', tasks.length)\n await Promise.all(tasks)\n this.connections.clear()\n }\n\n /**\n * Checks the libp2p metrics to determine if any values have exceeded\n * the configured maximums.\n *\n * @private\n */\n async _checkMetrics () {\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n try {\n const movingAverages = metrics.getGlobal().getMovingAverages()\n const received = movingAverages.dataReceived[this.opts.movingAverageInterval].movingAverage\n await this._checkMaxLimit('maxReceivedData', received)\n const sent = movingAverages.dataSent[this.opts.movingAverageInterval].movingAverage\n await this._checkMaxLimit('maxSentData', sent)\n const total = received + sent\n await this._checkMaxLimit('maxData', total)\n log.trace('metrics update', total)\n } finally {\n this.timer = retimer(this._checkMetrics, this.opts.pollInterval)\n }\n }\n }\n\n onConnect (evt: CustomEvent) {\n void this._onConnect(evt).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close()\n return\n }\n\n const peerId = connection.remotePeer\n const peerIdStr = peerId.toString()\n const storedConns = this.connections.get(peerIdStr)\n\n if (storedConns != null) {\n storedConns.push(connection)\n } else {\n this.connections.set(peerIdStr, [connection])\n }\n\n if (peerId.publicKey != null) {\n await this.components.getPeerStore().keyBook.set(peerId, peerId.publicKey)\n }\n\n const numConnections = this.getConnections().length\n const toPrune = numConnections - this.opts.maxConnections\n\n await this._checkMaxLimit('maxConnections', numConnections, toPrune)\n this.dispatchEvent(new CustomEvent('peer:connect', { detail: connection }))\n }\n\n /**\n * Removes the connection from tracking\n */\n onDisconnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return\n }\n\n const peerId = connection.remotePeer.toString()\n let storedConn = this.connections.get(peerId)\n\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id)\n this.connections.set(peerId, storedConn)\n } else if (storedConn != null) {\n this.connections.delete(peerId)\n this.dispatchEvent(new CustomEvent('peer:disconnect', { detail: connection }))\n\n this.components.getMetrics()?.onPeerDisconnected(connection.remotePeer)\n }\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n if (peerId != null) {\n return this.connections.get(peerId.toString()) ?? []\n }\n\n let conns: Connection[] = []\n\n for (const c of this.connections.values()) {\n conns = conns.concat(c)\n }\n\n return conns\n }\n\n async openConnection (peerId: PeerId, options: AbortOptions = {}): Promise {\n log('dial to %p', peerId)\n const existingConnections = this.getConnections(peerId)\n\n if (existingConnections.length > 0) {\n log('had an existing connection to %p', peerId)\n\n return existingConnections[0]\n }\n\n let timeoutController: TimeoutController | undefined\n\n if (options?.signal == null) {\n timeoutController = new TimeoutController(this.dialTimeout)\n options.signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n const connection = await this.dialer.dial(peerId, options)\n let peerConnections = this.connections.get(peerId.toString())\n\n if (peerConnections == null) {\n peerConnections = []\n this.connections.set(peerId.toString(), peerConnections)\n }\n\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false\n\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true\n }\n }\n\n if (!trackedConnection) {\n peerConnections.push(connection)\n }\n\n return connection\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n }\n }\n\n async closeConnections (peerId: PeerId): Promise {\n const connections = this.connections.get(peerId.toString()) ?? []\n\n await Promise.all(\n connections.map(async connection => {\n return await connection.close()\n })\n )\n }\n\n /**\n * Get all open connections with a peer\n */\n getAll (peerId: PeerId): Connection[] {\n if (!isPeerId(peerId)) {\n throw errCode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const id = peerId.toString()\n const connections = this.connections.get(id)\n\n // Return all open connections\n if (connections != null) {\n return connections.filter(connection => connection.stat.status === STATUS.OPEN)\n }\n\n return []\n }\n\n /**\n * If the event loop is slow, maybe close a connection\n */\n _onLatencyMeasure (evt: CustomEvent) {\n const { detail: summary } = evt\n\n this._checkMaxLimit('maxEventLoopDelay', summary.avgMs, 1)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * If the `value` of `name` has exceeded its limit, maybe close a connection\n */\n async _checkMaxLimit (name: keyof ConnectionManagerInit, value: number, toPrune: number = 1) {\n const limit = this.opts[name]\n log.trace('checking limit of %s. current value: %d of %d', name, value, limit)\n if (value > limit) {\n log('%s: limit exceeded: %p, %d/%d, pruning %d connection(s)', this.components.getPeerId(), name, value, limit, toPrune)\n await this._maybePruneConnections(toPrune)\n }\n }\n\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async _maybePruneConnections (toPrune: number) {\n const connections = this.getConnections()\n\n if (connections.length <= this.opts.minConnections || toPrune < 1) {\n return\n }\n\n const peerValues = new PeerMap()\n\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer\n\n if (peerValues.has(remotePeer)) {\n continue\n }\n\n const tags = await this.components.getPeerStore().getTags(remotePeer)\n\n // sum all tag values\n peerValues.set(remotePeer, tags.reduce((acc, curr) => {\n return acc + curr.value\n }, 0))\n }\n\n // sort by value, lowest to highest\n const sortedConnections = connections.sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0\n const peerBValue = peerValues.get(b.remotePeer) ?? 0\n\n if (peerAValue > peerBValue) {\n return 1\n }\n\n if (peerAValue < peerBValue) {\n return -1\n }\n\n return 0\n })\n\n // close some connections\n const toClose = []\n\n for (const connection of sortedConnections) {\n log('too many connections open - closing a connection to %p', connection.remotePeer)\n toClose.push(connection)\n\n if (toClose.length === toPrune) {\n break\n }\n }\n\n // close connections\n await Promise.all(\n toClose.map(async connection => {\n try {\n await connection.close()\n } catch (err) {\n log.error(err)\n }\n\n // TODO: should not need to invoke this manually\n this.onDisconnect(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n })\n )\n }\n}\n","import { logger } from '@libp2p/logger'\nimport mergeOptions from 'merge-options'\n// @ts-expect-error retimer does not have types\nimport retimer from 'retimer'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:connection-manager:auto-dialler')\n\nexport interface AutoDiallerInit {\n /**\n * Should preemptively guarantee connections are above the low watermark\n */\n enabled?: boolean\n\n /**\n * The minimum number of connections to avoid pruning\n */\n minConnections?: number\n\n /**\n * How often, in milliseconds, it should preemptively guarantee connections are above the low watermark\n */\n autoDialInterval?: number\n}\n\nconst defaultOptions: Partial = {\n enabled: true,\n minConnections: 0,\n autoDialInterval: 10000\n}\n\nexport class AutoDialler implements Startable {\n private readonly components: Components\n private readonly options: Required\n private running: boolean\n private autoDialTimeout?: ReturnType\n\n /**\n * Proactively tries to connect to known peers stored in the PeerStore.\n * It will keep the number of connections below the upper limit and sort\n * the peers to connect based on wether we know their keys and protocols.\n */\n constructor (components: Components, init: AutoDiallerInit) {\n this.components = components\n this.options = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n this.running = false\n this._autoDial = this._autoDial.bind(this)\n\n log('options: %j', this.options)\n }\n\n isStarted () {\n return this.running\n }\n\n /**\n * Starts the auto dialer\n */\n async start () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = true\n\n void this._autoDial().catch(err => {\n log.error('could start autodial', err)\n })\n\n log('started')\n }\n\n /**\n * Stops the auto dialler\n */\n async stop () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = false\n\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n log('stopped')\n }\n\n async _autoDial () {\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n const minConnections = this.options.minConnections\n\n // Already has enough connections\n if (this.components.getConnectionManager().getConnections().length >= minConnections) {\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n\n return\n }\n\n // Sort peers on whether we know protocols or public keys for them\n const allPeers = await this.components.getPeerStore().all()\n\n const peers = await pipe(\n // shuffle the peers\n allPeers.sort(() => Math.random() > 0.5 ? 1 : -1),\n (source) => filter(source, (peer) => !peer.id.equals(this.components.getPeerId())),\n (source) => sort(source, (a, b) => {\n if (b.protocols.length > a.protocols.length) {\n return 1\n } else if (b.id.publicKey != null && a.id.publicKey == null) {\n return 1\n }\n return -1\n }),\n async (source) => await all(source)\n )\n\n for (let i = 0; this.running && i < peers.length && this.components.getConnectionManager().getConnections().length < minConnections; i++) {\n // Connection Manager was stopped during async dial\n if (!this.running) {\n return\n }\n\n const peer = peers[i]\n\n if (this.components.getConnectionManager().getConnections(peer.id).length === 0) {\n log('connecting to a peerStore stored peer %p', peer.id)\n try {\n await this.components.getConnectionManager().openConnection(peer.id)\n } catch (err: any) {\n log.error('could not connect to peerStore stored peer', err)\n }\n }\n }\n\n // Connection Manager was stopped\n if (!this.running) {\n return\n }\n\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface CircuitRelay {\n type?: CircuitRelay.Type\n srcPeer?: CircuitRelay.Peer\n dstPeer?: CircuitRelay.Peer\n code?: CircuitRelay.Status\n}\n\nexport namespace CircuitRelay {\n export enum Status {\n SUCCESS = 'SUCCESS',\n HOP_SRC_ADDR_TOO_LONG = 'HOP_SRC_ADDR_TOO_LONG',\n HOP_DST_ADDR_TOO_LONG = 'HOP_DST_ADDR_TOO_LONG',\n HOP_SRC_MULTIADDR_INVALID = 'HOP_SRC_MULTIADDR_INVALID',\n HOP_DST_MULTIADDR_INVALID = 'HOP_DST_MULTIADDR_INVALID',\n HOP_NO_CONN_TO_DST = 'HOP_NO_CONN_TO_DST',\n HOP_CANT_DIAL_DST = 'HOP_CANT_DIAL_DST',\n HOP_CANT_OPEN_DST_STREAM = 'HOP_CANT_OPEN_DST_STREAM',\n HOP_CANT_SPEAK_RELAY = 'HOP_CANT_SPEAK_RELAY',\n HOP_CANT_RELAY_TO_SELF = 'HOP_CANT_RELAY_TO_SELF',\n STOP_SRC_ADDR_TOO_LONG = 'STOP_SRC_ADDR_TOO_LONG',\n STOP_DST_ADDR_TOO_LONG = 'STOP_DST_ADDR_TOO_LONG',\n STOP_SRC_MULTIADDR_INVALID = 'STOP_SRC_MULTIADDR_INVALID',\n STOP_DST_MULTIADDR_INVALID = 'STOP_DST_MULTIADDR_INVALID',\n STOP_RELAY_REFUSED = 'STOP_RELAY_REFUSED',\n MALFORMED_MESSAGE = 'MALFORMED_MESSAGE'\n }\n\n enum __StatusValues {\n SUCCESS = 100,\n HOP_SRC_ADDR_TOO_LONG = 220,\n HOP_DST_ADDR_TOO_LONG = 221,\n HOP_SRC_MULTIADDR_INVALID = 250,\n HOP_DST_MULTIADDR_INVALID = 251,\n HOP_NO_CONN_TO_DST = 260,\n HOP_CANT_DIAL_DST = 261,\n HOP_CANT_OPEN_DST_STREAM = 262,\n HOP_CANT_SPEAK_RELAY = 270,\n HOP_CANT_RELAY_TO_SELF = 280,\n STOP_SRC_ADDR_TOO_LONG = 320,\n STOP_DST_ADDR_TOO_LONG = 321,\n STOP_SRC_MULTIADDR_INVALID = 350,\n STOP_DST_MULTIADDR_INVALID = 351,\n STOP_RELAY_REFUSED = 390,\n MALFORMED_MESSAGE = 400\n }\n\n export namespace Status {\n export const codec = () => {\n return enumeration(__StatusValues)\n }\n }\n\n export enum Type {\n HOP = 'HOP',\n STOP = 'STOP',\n STATUS = 'STATUS',\n CAN_HOP = 'CAN_HOP'\n }\n\n enum __TypeValues {\n HOP = 1,\n STOP = 2,\n STATUS = 3,\n CAN_HOP = 4\n }\n\n export namespace Type {\n export const codec = () => {\n return enumeration(__TypeValues)\n }\n }\n\n export interface Peer {\n id: Uint8Array\n addrs: Uint8Array[]\n }\n\n export namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.id != null) {\n writer.uint32(10)\n writer.bytes(obj.id)\n } else {\n throw new Error('Protocol error: required field \"id\" was not found in object')\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n writer.uint32(18)\n writer.bytes(value)\n }\n } else {\n throw new Error('Protocol error: required field \"addrs\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.addrs = obj.addrs ?? []\n obj.addrs.push(reader.bytes())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n obj.addrs = obj.addrs ?? []\n\n if (obj.id == null) {\n throw new Error('Protocol error: value for required field \"id\" was not found in protobuf')\n }\n\n if (obj.addrs == null) {\n throw new Error('Protocol error: value for required field \"addrs\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.type != null) {\n writer.uint32(8)\n CircuitRelay.Type.codec().encode(obj.type, writer)\n }\n\n if (obj.srcPeer != null) {\n writer.uint32(18)\n CircuitRelay.Peer.codec().encode(obj.srcPeer, writer)\n }\n\n if (obj.dstPeer != null) {\n writer.uint32(26)\n CircuitRelay.Peer.codec().encode(obj.dstPeer, writer)\n }\n\n if (obj.code != null) {\n writer.uint32(32)\n CircuitRelay.Status.codec().encode(obj.code, writer)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.type = CircuitRelay.Type.codec().decode(reader)\n break\n case 2:\n obj.srcPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 3:\n obj.dstPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 4:\n obj.code = CircuitRelay.Status.codec().decode(reader)\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: CircuitRelay): Uint8Array => {\n return encodeMessage(obj, CircuitRelay.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): CircuitRelay => {\n return decodeMessage(buf, CircuitRelay.codec())\n }\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:stream:converter')\n\nexport interface Timeline {\n /**\n * Connection opening timestamp\n */\n open: number\n\n /**\n * Connection upgraded timestamp\n */\n upgraded?: number\n\n /**\n * Connection closed timestamp\n */\n close?: number\n}\n\ninterface StreamOptions {\n signal?: AbortSignal\n\n}\n\ninterface StreamProperties {\n stream: Duplex\n remoteAddr: Multiaddr\n localAddr: Multiaddr\n}\n\n/**\n * Convert a duplex iterable into a MultiaddrConnection.\n * https://github.com/libp2p/interface-transport#multiaddrconnection\n */\nexport function streamToMaConnection (props: StreamProperties, options: StreamOptions = {}) {\n const { stream, remoteAddr } = props\n const { sink, source } = stream\n\n const mapSource = (async function * () {\n for await (const list of source) {\n yield * list\n }\n }())\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if (options.signal != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await sink(source)\n await close()\n } catch (err: any) {\n // If aborted we can safely ignore\n if (err.type !== 'aborted') {\n // If the source errored the socket will already have been destroyed by\n // toIterable.duplex(). If the socket errored it will already be\n // destroyed. There's nothing to do here except log the error & return.\n log(err)\n }\n }\n },\n source: (options.signal != null) ? abortableSource(mapSource, options.signal) : mapSource,\n remoteAddr,\n /** @type {Timeline} */\n timeline: { open: Date.now(), close: undefined },\n async close () {\n await sink(async function * () {\n yield new Uint8Array(0)\n }())\n await close()\n }\n }\n\n async function close () {\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n return await Promise.resolve()\n }\n\n return maConn\n}\n","\nexport const RELAY_CODEC = '/libp2p/circuit/relay/0.1.0'\n","import { Multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { StreamHandler } from './stream-handler.js'\n\n/**\n * Write a response\n */\nfunction writeResponse (streamHandler: StreamHandler, status: CircuitRelay.Status) {\n streamHandler.write({\n type: CircuitRelay.Type.STATUS,\n code: status\n })\n}\n\n/**\n * Validate incomming HOP/STOP message\n */\nexport function validateAddrs (msg: CircuitRelay, streamHandler: StreamHandler) {\n try {\n if (msg.dstPeer?.addrs != null) {\n msg.dstPeer.addrs.forEach((addr) => {\n return new Multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_DST_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_DST_MULTIADDR_INVALID)\n throw err\n }\n\n try {\n if (msg.srcPeer?.addrs != null) {\n msg.srcPeer.addrs.forEach((addr) => {\n return new Multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_SRC_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_SRC_MULTIADDR_INVALID)\n throw err\n }\n}\n","import { logger } from '@libp2p/logger'\nimport * as lp from 'it-length-prefixed'\nimport { Handshake, handshake } from 'it-handshake'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stream-handler')\n\nexport interface StreamHandlerOptions {\n /**\n * A duplex iterable\n */\n stream: Stream\n\n /**\n * max bytes length of message\n */\n maxLength?: number\n}\n\nexport class StreamHandler {\n private readonly stream: Stream\n private readonly shake: Handshake\n private readonly decoder: Source\n\n constructor (options: StreamHandlerOptions) {\n const { stream, maxLength = 4096 } = options\n\n this.stream = stream\n this.shake = handshake(this.stream)\n this.decoder = lp.decode.fromReader(this.shake.reader, { maxDataLength: maxLength })\n }\n\n /**\n * Read and decode message\n */\n async read () {\n // @ts-expect-error FIXME is a source, needs to be a generator\n const msg = await this.decoder.next()\n\n if (msg.value != null) {\n const value = CircuitRelay.decode(msg.value)\n log('read message type', value.type)\n return value\n }\n\n log('read received no value, closing stream')\n // End the stream, we didn't get data\n this.close()\n }\n\n /**\n * Encode and write array of buffers\n */\n write (msg: CircuitRelay) {\n log('write message type %s', msg.type)\n this.shake.write(lp.encode.single(CircuitRelay.encode(msg)))\n }\n\n /**\n * Return the handshake rest stream and invalidate handler\n */\n rest () {\n this.shake.rest()\n return this.shake.stream\n }\n\n /**\n * @param {CircuitRelay} msg - An unencoded CircuitRelay protobuf message\n */\n end (msg: CircuitRelay) {\n this.write(msg)\n this.close()\n }\n\n /**\n * Close the stream\n */\n close () {\n log('closing the stream')\n void this.rest().sink([]).catch(err => {\n log.error(err)\n })\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { validateAddrs } from './utils.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stop')\n\nexport interface HandleStopOptions {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n}\n\n/**\n * Handles incoming STOP requests\n */\nexport function handleStop (options: HandleStopOptions): Duplex | undefined {\n const {\n connection,\n request,\n streamHandler\n } = options\n\n // Validate the STOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid stop request via peer %p %o', connection.remotePeer, err)\n return\n }\n\n // The request is valid\n log('stop request is valid')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n\n return streamHandler.rest()\n}\n\nexport interface StopOptions extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Creates a STOP request\n */\nexport async function stop (options: StopOptions) {\n const {\n connection,\n request,\n signal\n } = options\n\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n log('starting stop request to %p', connection.remotePeer)\n const streamHandler = new StreamHandler({ stream })\n\n streamHandler.write(request)\n const response = await streamHandler.read()\n\n if (response == null) {\n streamHandler.close()\n return\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('stop request to %p was successful', connection.remotePeer)\n return streamHandler.rest()\n }\n\n log('stop request failed with code %d', response.code)\n streamHandler.close()\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { validateAddrs } from './utils.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { pipe } from 'it-pipe'\nimport { codes as Errors } from '../../errors.js'\nimport { stop } from './stop.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { Duplex } from 'it-stream-types'\nimport type { Circuit } from '../transport.js'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:hop')\n\nexport interface HopRequest {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n circuit: Circuit\n connectionManager: ConnectionManager\n}\n\nexport async function handleHop (hopRequest: HopRequest): Promise {\n const {\n connection,\n request,\n streamHandler,\n circuit,\n connectionManager\n } = hopRequest\n\n // Ensure hop is enabled\n if (!circuit.hopEnabled()) {\n log('HOP request received but we are not acting as a relay')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n }\n\n // Validate the HOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid hop request via peer %p %o', connection.remotePeer, err)\n\n return\n }\n\n if (request.dstPeer == null) {\n log('HOP request received but we do not receive a dstPeer')\n return\n }\n\n // Get the connection to the destination (stop) peer\n const destinationPeer = peerIdFromBytes(request.dstPeer.id)\n\n const destinationConnections = connectionManager.getConnections(destinationPeer)\n if (destinationConnections.length === 0 && !circuit.hopActive()) {\n log('HOP request received but we are not connected to the destination peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // TODO: Handle being an active relay\n if (destinationConnections.length === 0) {\n log('did not have connection to remote peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // Handle the incoming HOP request by performing a STOP request\n const stopRequest = {\n type: CircuitPB.Type.STOP,\n dstPeer: request.dstPeer,\n srcPeer: request.srcPeer\n }\n\n let destinationStream: Duplex\n try {\n log('performing STOP request')\n const result = await stop({\n connection: destinationConnections[0],\n request: stopRequest\n })\n\n if (result == null) {\n throw new Error('Could not stop')\n }\n\n destinationStream = result\n } catch (err: any) {\n log.error(err)\n\n return\n }\n\n log('hop request from %p is valid', connection.remotePeer)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n const sourceStream = streamHandler.rest()\n\n log('creating related connections')\n // Short circuit the two streams to create the relayed connection\n return await pipe(\n sourceStream,\n destinationStream,\n sourceStream\n )\n}\n\nexport interface HopConfig extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Performs a HOP request to a relay peer, to request a connection to another\n * peer. A new, virtual, connection will be created between the two via the relay.\n */\nexport async function hop (options: HopConfig): Promise> {\n const {\n connection,\n request,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write(request)\n\n const response = await streamHandler.read()\n\n if (response == null) {\n throw errCode(new Error('HOP request had no response'), Errors.ERR_HOP_REQUEST_FAILED)\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('hop request was successful')\n\n return streamHandler.rest()\n }\n\n log('hop request failed with code %d, closing stream', response.code)\n streamHandler.close()\n\n throw errCode(new Error(`HOP request failed with code \"${response.code ?? 'unknown'}\"`), Errors.ERR_HOP_REQUEST_FAILED)\n}\n\nexport interface CanHopOptions extends AbortOptions {\n connection: Connection\n}\n\n/**\n * Performs a CAN_HOP request to a relay peer, in order to understand its capabilities\n */\nexport async function canHop (options: CanHopOptions) {\n const {\n connection,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write({\n type: CircuitPB.Type.CAN_HOP\n })\n\n const response = await streamHandler.read()\n await streamHandler.close()\n\n if (response == null || response.code !== CircuitPB.Status.SUCCESS) {\n return false\n }\n\n return true\n}\n\nexport interface HandleCanHopOptions {\n connection: Connection\n streamHandler: StreamHandler\n circuit: Circuit\n}\n\n/**\n * Creates an unencoded CAN_HOP response based on the Circuits configuration\n */\nexport function handleCanHop (options: HandleCanHopOptions) {\n const {\n connection,\n streamHandler,\n circuit\n } = options\n const canHop = circuit.hopEnabled()\n log('can hop (%s) request from %p', canHop, connection.remotePeer)\n streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: canHop ? CircuitPB.Status.SUCCESS : CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mafmt from '@multiformats/mafmt'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay as CircuitPB } from './pb/index.js'\nimport { codes } from '../errors.js'\nimport { streamToMaConnection } from '@libp2p/utils/stream-to-ma-conn'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { createListener } from './listener.js'\nimport { handleCanHop, handleHop, hop } from './circuit/hop.js'\nimport { handleStop } from './circuit/stop.js'\nimport { StreamHandler } from './circuit/stream-handler.js'\nimport { symbol } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { Components, Initializable } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Listener, Transport, CreateListenerOptions, ConnectionHandler } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { RelayConfig } from '../index.js'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\n\nconst log = logger('libp2p:circuit')\n\nexport class Circuit implements Transport, Initializable {\n private handler?: ConnectionHandler\n private components: Components = new Components()\n private readonly _init: RelayConfig\n\n constructor (init: RelayConfig) {\n this._init = init\n }\n\n init (components: Components): void {\n this.components = components\n void this.components.getRegistrar().handle(RELAY_CODEC, (data) => {\n void this._onProtocol(data).catch(err => {\n log.error(err)\n })\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n hopEnabled () {\n return true\n }\n\n hopActive () {\n return true\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return 'libp2p/circuit-relay-v1'\n }\n\n async _onProtocol (data: IncomingStreamData) {\n const { connection, stream } = data\n const controller = new TimeoutController(this._init.hop.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n try {\n const source = abortableDuplex(stream, controller.signal)\n const streamHandler = new StreamHandler({\n stream: {\n ...stream,\n ...source\n }\n })\n const request = await streamHandler.read()\n\n if (request == null) {\n log('request was invalid, could not read from stream')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n\n let virtualConnection: Duplex | undefined\n\n switch (request.type) {\n case CircuitPB.Type.CAN_HOP: {\n log('received CAN_HOP request from %p', connection.remotePeer)\n await handleCanHop({ circuit: this, connection, streamHandler })\n break\n }\n case CircuitPB.Type.HOP: {\n log('received HOP request from %p', connection.remotePeer)\n await handleHop({\n connection,\n request,\n streamHandler,\n circuit: this,\n connectionManager: this.components.getConnectionManager()\n })\n break\n }\n case CircuitPB.Type.STOP: {\n log('received STOP request from %p', connection.remotePeer)\n virtualConnection = await handleStop({\n connection,\n request,\n streamHandler\n })\n break\n }\n default: {\n log('Request of type %s not supported', request.type)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n }\n\n if (virtualConnection != null) {\n const remoteAddr = connection.remoteAddr\n .encapsulate('/p2p-circuit')\n .encapsulate(new Multiaddr(request.dstPeer?.addrs[0]))\n const localAddr = new Multiaddr(request.srcPeer?.addrs[0])\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr,\n localAddr\n })\n const type = request.type === CircuitPB.Type.HOP ? 'relay' : 'inbound'\n log('new %s connection %s', type, maConn.remoteAddr)\n\n const conn = await this.components.getUpgrader().upgradeInbound(maConn)\n log('%s connection %s upgraded', type, maConn.remoteAddr)\n\n if (this.handler != null) {\n this.handler(conn)\n }\n }\n } finally {\n controller.clear()\n }\n }\n\n /**\n * Dial a peer over a relay\n */\n async dial (ma: Multiaddr, options: AbortOptions = {}): Promise {\n // Check the multiaddr to see if it contains a relay and a destination peer\n const addrs = ma.toString().split('/p2p-circuit')\n const relayAddr = new Multiaddr(addrs[0])\n const destinationAddr = new Multiaddr(addrs[addrs.length - 1])\n const relayId = relayAddr.getPeerId()\n const destinationId = destinationAddr.getPeerId()\n\n if (relayId == null || destinationId == null) {\n const errMsg = 'Circuit relay dial failed as addresses did not have peer id'\n log.error(errMsg)\n throw errCode(new Error(errMsg), codes.ERR_RELAYED_DIAL)\n }\n\n const relayPeer = peerIdFromString(relayId)\n const destinationPeer = peerIdFromString(destinationId)\n\n let disconnectOnFailure = false\n const relayConnections = this.components.getConnectionManager().getConnections(relayPeer)\n let relayConnection = relayConnections[0]\n\n if (relayConnection == null) {\n await this.components.getPeerStore().addressBook.add(relayPeer, [relayAddr])\n relayConnection = await this.components.getConnectionManager().openConnection(relayPeer, options)\n disconnectOnFailure = true\n }\n\n try {\n const virtualConnection = await hop({\n ...options,\n connection: relayConnection,\n request: {\n type: CircuitPB.Type.HOP,\n srcPeer: {\n id: this.components.getPeerId().toBytes(),\n addrs: this.components.getAddressManager().getAddresses().map(addr => addr.bytes)\n },\n dstPeer: {\n id: destinationPeer.toBytes(),\n addrs: [new Multiaddr(destinationAddr).bytes]\n }\n }\n })\n\n const localAddr = relayAddr.encapsulate(`/p2p-circuit/p2p/${this.components.getPeerId().toString()}`)\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr: ma,\n localAddr\n })\n log('new outbound connection %s', maConn.remoteAddr)\n\n return await this.components.getUpgrader().upgradeOutbound(maConn)\n } catch (err: any) {\n log.error('Circuit relay dial failed', err)\n disconnectOnFailure && await relayConnection.close()\n throw err\n }\n }\n\n /**\n * Create a listener\n */\n createListener (options: CreateListenerOptions): Listener {\n // Called on successful HOP and STOP requests\n this.handler = options.handler\n\n return createListener({\n connectionManager: this.components.getConnectionManager(),\n peerStore: this.components.getPeerStore()\n })\n }\n\n /**\n * Filter check for all Multiaddrs that this transport can dial on\n *\n * @param {Multiaddr[]} multiaddrs\n * @returns {Multiaddr[]}\n */\n filter (multiaddrs: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n return mafmt.Circuit.matches(ma)\n })\n }\n}\n","import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Listener } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface ListenerOptions {\n peerStore: PeerStore\n connectionManager: ConnectionManager\n}\n\nexport function createListener (options: ListenerOptions): Listener {\n const listeningAddrs = new Map()\n\n /**\n * Add swarm handler and listen for incoming connections\n */\n async function listen (addr: Multiaddr): Promise {\n const addrString = addr.toString().split('/p2p-circuit').find(a => a !== '')\n const ma = new Multiaddr(addrString)\n\n const relayPeerStr = ma.getPeerId()\n\n if (relayPeerStr == null) {\n throw new Error('Could not determine relay peer from multiaddr')\n }\n\n const relayPeerId = peerIdFromString(relayPeerStr)\n\n await options.peerStore.addressBook.add(relayPeerId, [ma])\n\n const relayConn = await options.connectionManager.openConnection(relayPeerId)\n const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit')\n\n listeningAddrs.set(relayConn.remotePeer.toString(), relayedAddr)\n listener.dispatchEvent(new CustomEvent('listening'))\n }\n\n /**\n * Get fixed up multiaddrs\n *\n * NOTE: This method will grab the peers multiaddrs and expand them such that:\n *\n * a) If it's an existing /p2p-circuit address for a specific relay i.e.\n * `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the\n * address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where\n * `QmPeer` is this peers id\n * b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit\n * addr, such when dialing over a relay with this address, it will create the circuit using\n * the encapsulated transport address. This is useful when for example, a peer should only\n * be dialed over TCP rather than any other transport\n *\n * @returns {Multiaddr[]}\n */\n function getAddrs () {\n const addrs = []\n for (const addr of listeningAddrs.values()) {\n addrs.push(addr)\n }\n return addrs\n }\n\n const listener: Listener = Object.assign(new EventEmitter(), {\n close: async () => await Promise.resolve(),\n listen,\n getAddrs\n })\n\n // Remove listeningAddrs when a peer disconnects\n options.connectionManager.addEventListener('peer:disconnect', (evt) => {\n const { detail: connection } = evt\n const deleted = listeningAddrs.delete(connection.remotePeer.toString())\n\n if (deleted) {\n // Announce listen addresses change\n listener.dispatchEvent(new CustomEvent('close'))\n }\n })\n\n return listener\n}\n","import { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * Convert a namespace string into a cid\n */\nexport async function namespaceToCid (namespace: string): Promise {\n const bytes = new TextEncoder().encode(namespace)\n const hash = await sha256.digest(bytes)\n\n return CID.createV0(hash)\n}\n","const minute = 60 * 1000\n\n/**\n * Delay before HOP relay service is advertised on the network\n */\nexport const ADVERTISE_BOOT_DELAY = 15 * minute\n\n/**\n * Delay Between HOP relay service advertisements on the network\n */\nexport const ADVERTISE_TTL = 30 * minute\n\n/**\n * Multicodec code\n */\nexport const CIRCUIT_PROTO_CODE = 290\n\n/**\n * PeerStore metadaBook key for HOP relay service\n */\nexport const HOP_METADATA_KEY = 'hop_relay'\n\n/**\n * PeerStore metadaBook value for HOP relay service\n */\nexport const HOP_METADATA_VALUE = 'true'\n\n/**\n * Relay HOP relay service namespace for discovery\n */\nexport const RELAY_RENDEZVOUS_NS = '/libp2p/relay'\n","import { logger } from '@libp2p/logger'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { canHop } from './circuit/hop.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n CIRCUIT_PROTO_CODE,\n HOP_METADATA_KEY,\n HOP_METADATA_VALUE,\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressSorter, PeerProtocolsChangeData } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Components } from '@libp2p/components'\nimport sort from 'it-sort'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\n\nconst log = logger('libp2p:auto-relay')\n\nconst noop = () => {}\n\nexport interface AutoRelayInit {\n addressSorter?: AddressSorter\n maxListeners?: number\n onError?: (error: Error, msg?: string) => void\n}\n\nexport class AutoRelay {\n private readonly components: Components\n private readonly addressSorter: AddressSorter\n private readonly maxListeners: number\n private readonly listenRelays: Set\n private readonly onError: (error: Error, msg?: string) => void\n\n constructor (components: Components, init: AutoRelayInit) {\n this.components = components\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxListeners = init.maxListeners ?? 1\n this.listenRelays = new Set()\n this.onError = init.onError ?? noop\n\n this._onProtocolChange = this._onProtocolChange.bind(this)\n this._onPeerDisconnected = this._onPeerDisconnected.bind(this)\n\n this.components.getPeerStore().addEventListener('change:protocols', (evt) => {\n void this._onProtocolChange(evt).catch(err => {\n log.error(err)\n })\n })\n this.components.getConnectionManager().addEventListener('peer:disconnect', this._onPeerDisconnected)\n }\n\n /**\n * Check if a peer supports the relay protocol.\n * If the protocol is not supported, check if it was supported before and remove it as a listen relay.\n * If the protocol is supported, check if the peer supports **HOP** and add it as a listener if\n * inside the threshold.\n */\n async _onProtocolChange (evt: CustomEvent) {\n const {\n peerId,\n protocols\n } = evt.detail\n const id = peerId.toString()\n\n // Check if it has the protocol\n const hasProtocol = protocols.find(protocol => protocol === RELAY_CODEC)\n\n // If no protocol, check if we were keeping the peer before as a listenRelay\n if (hasProtocol == null) {\n if (this.listenRelays.has(id)) {\n await this._removeListenRelay(id)\n }\n\n return\n }\n\n if (this.listenRelays.has(id)) {\n return\n }\n\n // If protocol, check if can hop, store info in the metadataBook and listen on it\n try {\n const connections = this.components.getConnectionManager().getConnections(peerId)\n\n if (connections.length === 0) {\n return\n }\n\n const connection = connections[0]\n\n // Do not hop on a relayed connection\n if (connection.remoteAddr.protoCodes().includes(CIRCUIT_PROTO_CODE)) {\n log(`relayed connection to ${id} will not be used to hop on`)\n return\n }\n\n const supportsHop = await canHop({ connection })\n\n if (supportsHop) {\n await this.components.getPeerStore().metadataBook.setValue(peerId, HOP_METADATA_KEY, uint8ArrayFromString(HOP_METADATA_VALUE))\n await this._addListenRelay(connection, id)\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n /**\n * Peer disconnects\n */\n _onPeerDisconnected (evt: CustomEvent) {\n const connection = evt.detail\n const peerId = connection.remotePeer\n const id = peerId.toString()\n\n // Not listening on this relay\n if (!this.listenRelays.has(id)) {\n return\n }\n\n this._removeListenRelay(id).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Attempt to listen on the given relay connection\n */\n async _addListenRelay (connection: Connection, id: string): Promise {\n try {\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n // Get peer known addresses and sort them with public addresses first\n const remoteAddrs = await pipe(\n await this.components.getPeerStore().addressBook.get(connection.remotePeer),\n (source) => sort(source, this.addressSorter),\n async (source) => await all(source)\n )\n\n // Attempt to listen on relay\n const result = await Promise.all(\n remoteAddrs.map(async addr => {\n try {\n let multiaddr = addr.multiaddr\n\n if (multiaddr.getPeerId() == null) {\n multiaddr = multiaddr.encapsulate(`/p2p/${connection.remotePeer.toString()}`)\n }\n\n multiaddr = multiaddr.encapsulate('/p2p-circuit')\n\n // Announce multiaddrs will update on listen success by TransportManager event being triggered\n await this.components.getTransportManager().listen([multiaddr])\n return true\n } catch (err: any) {\n log.error('error listening on circuit address', err)\n this.onError(err)\n }\n\n return false\n })\n )\n\n if (result.includes(true)) {\n this.listenRelays.add(id)\n }\n } catch (err: any) {\n this.onError(err)\n this.listenRelays.delete(id)\n }\n }\n\n /**\n * Remove listen relay\n */\n async _removeListenRelay (id: string) {\n if (this.listenRelays.delete(id)) {\n // TODO: this should be responsibility of the connMgr\n await this._listenOnAvailableHopRelays([id])\n }\n }\n\n /**\n * Try to listen on available hop relay connections.\n * The following order will happen while we do not have enough relays.\n * 1. Check the metadata store for known relays, try to listen on the ones we are already connected.\n * 2. Dial and try to listen on the peers we know that support hop but are not connected.\n * 3. Search the network.\n */\n async _listenOnAvailableHopRelays (peersToIgnore: string[] = []) {\n // TODO: The peer redial issue on disconnect should be handled by connection gating\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n const knownHopsToDial = []\n const peers = await this.components.getPeerStore().all()\n\n // Check if we have known hop peers to use and attempt to listen on the already connected\n for (const { id, metadata } of peers) {\n const idStr = id.toString()\n\n // Continue to next if listening on this or peer to ignore\n if (this.listenRelays.has(idStr)) {\n continue\n }\n\n if (peersToIgnore.includes(idStr)) {\n continue\n }\n\n const supportsHop = metadata.get(HOP_METADATA_KEY)\n\n // Continue to next if it does not support Hop\n if ((supportsHop == null) || uint8ArrayToString(supportsHop) !== HOP_METADATA_VALUE) {\n continue\n }\n\n const connections = this.components.getConnectionManager().getConnections(id)\n\n // If not connected, store for possible later use.\n if (connections.length === 0) {\n knownHopsToDial.push(id)\n continue\n }\n\n await this._addListenRelay(connections[0], idStr)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to listen on known peers that are not connected\n for (const peerId of knownHopsToDial) {\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to find relays to hop on the network\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n for await (const provider of this.components.getContentRouting().findProviders(cid)) {\n if (provider.multiaddrs.length === 0) {\n continue\n }\n\n const peerId = provider.id\n\n if (peerId.equals(this.components.getPeerId())) {\n // Skip the provider if it's us as dialing will fail\n continue\n }\n\n await this.components.getPeerStore().addressBook.add(peerId, provider.multiaddrs)\n\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n async _tryToListenOnRelay (peerId: PeerId) {\n try {\n const connection = await this.components.getConnectionManager().openConnection(peerId)\n await this._addListenRelay(connection, peerId.toString())\n } catch (err: any) {\n log.error('Could not use %p as relay', peerId, err)\n this.onError(err, `could not connect and listen on known hop relay ${peerId.toString()}`)\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { codes } from '../errors.js'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error set-delayed-interval does not export types\n} from 'set-delayed-interval'\nimport { AutoRelay } from './auto-relay.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport type { RelayConfig } from '../index.js'\n\nconst log = logger('libp2p:relay')\n\nexport interface RelayAdvertiseConfig {\n bootDelay?: number\n enabled?: boolean\n ttl?: number\n}\n\nexport interface AutoRelayConfig {\n enabled?: boolean\n\n /**\n * maximum number of relays to listen\n */\n maxListeners: number\n}\n\nexport interface RelayInit extends RelayConfig {\n addressSorter?: AddressSorter\n}\n\nexport class Relay implements Startable {\n private readonly components: Components\n private readonly init: RelayInit\n // @ts-expect-error this field isn't used anywhere?\n private readonly autoRelay?: AutoRelay\n private timeout?: any\n private started: boolean\n\n /**\n * Creates an instance of Relay\n */\n constructor (components: Components, init: RelayInit) {\n this.components = components\n // Create autoRelay if enabled\n this.autoRelay = init.autoRelay?.enabled !== false\n ? new AutoRelay(components, {\n addressSorter: init.addressSorter,\n ...init.autoRelay\n })\n : undefined\n\n this.started = false\n this.init = init\n this._advertiseService = this._advertiseService.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start Relay service\n */\n async start () {\n // Advertise service if HOP enabled\n if (this.init.hop.enabled !== false && this.init.advertise.enabled !== false) {\n this.timeout = setDelayedInterval(\n this._advertiseService, this.init.advertise.ttl, this.init.advertise.bootDelay\n )\n }\n\n this.started = true\n }\n\n /**\n * Stop Relay service\n */\n async stop () {\n if (this.timeout != null) {\n clearDelayedInterval(this.timeout)\n }\n\n this.started = false\n }\n\n /**\n * Advertise hop relay service in the network.\n */\n async _advertiseService () {\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n await this.components.getContentRouting().provide(cid)\n } catch (err: any) {\n if (err.code === codes.ERR_NO_ROUTERS_AVAILABLE) {\n log.error('a content router, such as a DHT, must be provided in order to advertise the relay service', err)\n // Stop the advertise\n await this.stop()\n } else {\n log.error(err)\n }\n }\n }\n}\n","import 'node-forge/lib/x509.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\n\nconst pki = forge.pki\n\n/**\n * Gets a self-signed X.509 certificate for the key.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n *\n * TODO: move to libp2p-crypto package\n */\nexport const certificateForKey = (key: any, privateKey: forge.pki.rsa.PrivateKey) => {\n const publicKey = pki.rsa.setPublicKey(privateKey.n, privateKey.e)\n const cert = pki.createCertificate()\n cert.publicKey = publicKey\n cert.serialNumber = '01'\n cert.validity.notBefore = new Date()\n cert.validity.notAfter = new Date()\n cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10) // eslint-disable-line @typescript-eslint/restrict-plus-operands\n const attrs = [{\n name: 'organizationName',\n value: 'ipfs'\n }, {\n shortName: 'OU',\n value: 'keystore'\n }, {\n name: 'commonName',\n value: key.id\n }]\n cert.setSubject(attrs)\n cert.setIssuer(attrs)\n cert.setExtensions([{\n name: 'basicConstraints',\n cA: true\n }, {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n }, {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n emailProtection: true,\n timeStamping: true\n }, {\n name: 'nsCertType',\n client: true,\n server: true,\n email: true,\n objsign: true,\n sslCA: true,\n emailCA: true,\n objCA: true\n }])\n // self-sign certificate\n cert.sign(privateKey)\n\n return cert\n}\n\n/**\n * Finds the first item in a collection that is matched in the\n * `asyncCompare` function.\n *\n * `asyncCompare` is an async function that must\n * resolve to either `true` or `false`.\n *\n * @param {Array} array\n * @param {function(*)} asyncCompare - An async function that returns a boolean\n */\nexport async function findAsync (array: T[], asyncCompare: (val: T) => Promise) {\n const promises = array.map(asyncCompare)\n const results = await Promise.all(promises)\n const index = results.findIndex(result => result)\n return array[index]\n}\n","import 'node-forge/lib/pkcs7.js'\nimport 'node-forge/lib/pbe.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { certificateForKey, findAsync } from './util.js'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { codes } from '../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { KeyChain } from './index.js'\n\nconst log = logger('libp2p:keychain:cms')\n\nconst privates = new WeakMap()\n\n/**\n * Cryptographic Message Syntax (aka PKCS #7)\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content.\n *\n * See RFC 5652 for all the details.\n */\nexport class CMS {\n private readonly keychain: KeyChain\n\n /**\n * Creates a new instance with a keychain\n */\n constructor (keychain: KeyChain, dek: string) {\n if (keychain == null) {\n throw errCode(new Error('keychain is required'), codes.ERR_KEYCHAIN_REQUIRED)\n }\n\n this.keychain = keychain\n privates.set(this, { dek })\n }\n\n /**\n * Creates some protected data.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n */\n async encrypt (name: string, plain: Uint8Array): Promise {\n if (!(plain instanceof Uint8Array)) {\n throw errCode(new Error('Plain data must be a Uint8Array'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const key = await this.keychain.findKeyByName(name)\n const pem = await this.keychain.getPrivateKey(name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n const certificate = await certificateForKey(key, privateKey)\n\n // create a p7 enveloped message\n const p7 = forge.pkcs7.createEnvelopedData()\n p7.addRecipient(certificate)\n p7.content = forge.util.createBuffer(plain)\n p7.encrypt()\n\n // convert message to DER\n const der = forge.asn1.toDer(p7.toAsn1()).getBytes()\n return uint8ArrayFromString(der, 'ascii')\n }\n\n /**\n * Reads some protected data.\n *\n * The keychain must contain one of the keys used to encrypt the data. If none of the keys\n * exists, an Error is returned with the property 'missingKeys'. It is array of key ids.\n */\n async decrypt (cmsData: Uint8Array): Promise {\n if (!(cmsData instanceof Uint8Array)) {\n throw errCode(new Error('CMS data is required'), codes.ERR_INVALID_PARAMETERS)\n }\n\n let cms: any\n try {\n const buf = forge.util.createBuffer(uint8ArrayToString(cmsData, 'ascii'))\n const obj = forge.asn1.fromDer(buf)\n\n cms = forge.pkcs7.messageFromAsn1(obj)\n } catch (err: any) {\n log.error(err)\n throw errCode(new Error('Invalid CMS'), codes.ERR_INVALID_CMS)\n }\n\n // Find a recipient whose key we hold. We only deal with recipient certs\n // issued by ipfs (O=ipfs).\n const recipients: any = cms.recipients\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'O' && a.value === 'ipfs'))\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'CN'))\n // @ts-expect-error cms types not defined\n .map(r => {\n return {\n recipient: r,\n // @ts-expect-error cms types not defined\n keyId: r.issuer.find(a => a.shortName === 'CN').value\n }\n })\n\n const r = await findAsync(recipients, async (recipient: any) => {\n try {\n const key = await this.keychain.findKeyById(recipient.keyId)\n if (key != null) {\n return true\n }\n } catch (err: any) {\n return false\n }\n return false\n })\n\n if (r == null) {\n // @ts-expect-error cms types not defined\n const missingKeys: string[] = recipients.map(r => r.keyId)\n throw errCode(new Error(`Decryption needs one of the key(s): ${missingKeys.join(', ')}`), codes.ERR_MISSING_KEYS, {\n missingKeys\n })\n }\n\n const key = await this.keychain.findKeyById(r.keyId)\n\n if (key == null) {\n throw errCode(new Error('No key available to decrypto'), codes.ERR_NO_KEY)\n }\n\n const pem = await this.keychain.getPrivateKey(key.name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n cms.decrypt(r.recipient, privateKey)\n return uint8ArrayFromString(cms.content.getBytes(), 'ascii')\n }\n}\n","/* eslint max-nested-callbacks: [\"error\", 5] */\n\nimport { logger } from '@libp2p/logger'\nimport sanitize from 'sanitize-filename'\nimport mergeOptions from 'merge-options'\nimport { Key } from 'interface-datastore/key'\nimport { CMS } from './cms.js'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Components } from '@libp2p/components'\nimport { pbkdf2, randomBytes } from '@libp2p/crypto'\nimport type { Startable } from '@libp2p/interfaces/dist/src/startable'\n\nconst log = logger('libp2p:keychain')\n\nexport interface DekOptions {\n hash: string\n salt: string\n iterationCount: number\n keyLength: number\n}\n\nexport interface KeyChainInit {\n pass?: string\n dek?: DekOptions\n}\n\n/**\n * Information about a key.\n */\nexport interface KeyInfo {\n /**\n * The universally unique key id\n */\n id: string\n\n /**\n * The local key name.\n */\n name: string\n}\n\nconst keyPrefix = '/pkcs8/'\nconst infoPrefix = '/info/'\nconst privates = new WeakMap()\n\n// NIST SP 800-132\nconst NIST = {\n minKeyLength: 112 / 8,\n minSaltLength: 128 / 8,\n minIterationCount: 1000\n}\n\nconst defaultOptions = {\n // See https://cryptosense.com/parametesr-choice-for-pbkdf2/\n dek: {\n keyLength: 512 / 8,\n iterationCount: 10000,\n salt: 'you should override this value with a crypto secure random number',\n hash: 'sha2-512'\n }\n}\n\nfunction validateKeyName (name: string) {\n if (name == null) {\n return false\n }\n if (typeof name !== 'string') {\n return false\n }\n return name === sanitize(name.trim()) && name.length > 0\n}\n\n/**\n * Throws an error after a delay\n *\n * This assumes than an error indicates that the keychain is under attack. Delay returning an\n * error to make brute force attacks harder.\n */\nasync function randomDelay () {\n const min = 200\n const max = 1000\n const delay = Math.random() * (max - min) + min\n\n await new Promise(resolve => setTimeout(resolve, delay))\n}\n\n/**\n * Converts a key name into a datastore name\n */\nfunction DsName (name: string) {\n return new Key(keyPrefix + name)\n}\n\n/**\n * Converts a key name into a datastore info name\n */\nfunction DsInfoName (name: string) {\n return new Key(infoPrefix + name)\n}\n\n/**\n * Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.\n *\n * A key in the store has two entries\n * - '/info/*key-name*', contains the KeyInfo for the key\n * - '/pkcs8/*key-name*', contains the PKCS #8 for the key\n *\n */\nexport class KeyChain implements Startable {\n private readonly components: Components\n private init: KeyChainInit\n private started: boolean\n\n /**\n * Creates a new instance of a key chain\n */\n constructor (components: Components, init: KeyChainInit) {\n this.components = components\n this.init = mergeOptions(defaultOptions, init)\n\n // Enforce NIST SP 800-132\n if (this.init.pass != null && this.init.pass?.length < 20) {\n throw new Error('pass must be least 20 characters')\n }\n if (this.init.dek?.keyLength != null && this.init.dek.keyLength < NIST.minKeyLength) {\n throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)\n }\n if (this.init.dek?.salt?.length != null && this.init.dek.salt.length < NIST.minSaltLength) {\n throw new Error(`dek.saltLength must be least ${NIST.minSaltLength} bytes`)\n }\n if (this.init.dek?.iterationCount != null && this.init.dek.iterationCount < NIST.minIterationCount) {\n throw new Error(`dek.iterationCount must be least ${NIST.minIterationCount}`)\n }\n\n const dek = this.init.pass != null && this.init.dek?.salt != null\n ? pbkdf2(\n this.init.pass,\n this.init.dek?.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n\n privates.set(this, { dek })\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n const dsname = DsInfoName('self')\n\n if (!(await this.components.getDatastore().has(dsname))) {\n await this.importPeer('self', this.components.getPeerId())\n }\n\n this.started = true\n }\n\n stop () {\n this.started = false\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data\n * using the Cryptographic Message Syntax (CMS).\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content\n */\n get cms () {\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n\n return new CMS(this, dek)\n }\n\n /**\n * Generates the options for a keychain. A random salt is produced.\n *\n * @returns {object}\n */\n static generateOptions (): KeyChainInit {\n const options = Object.assign({}, defaultOptions)\n const saltLength = Math.ceil(NIST.minSaltLength / 3) * 3 // no base64 padding\n options.dek.salt = uint8ArrayToString(randomBytes(saltLength), 'base64')\n return options\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data.\n * The default options for a keychain.\n *\n * @returns {object}\n */\n static get options () {\n return defaultOptions\n }\n\n /**\n * Create a new key.\n *\n * @param {string} name - The local key name; cannot already exist.\n * @param {string} type - One of the key types; 'rsa'.\n * @param {number} [size = 2048] - The key size in bits. Used for rsa keys only\n */\n async createKey (name: string, type: 'RSA' | 'Ed25519', size = 2048): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error('Invalid key name'), codes.ERR_INVALID_KEY_NAME)\n }\n\n if (typeof type !== 'string') {\n await randomDelay()\n throw errCode(new Error('Invalid key type'), codes.ERR_INVALID_KEY_TYPE)\n }\n\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error('Key name already exists'), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n switch (type.toLowerCase()) {\n case 'rsa':\n if (!Number.isSafeInteger(size) || size < 2048) {\n await randomDelay()\n throw errCode(new Error('Invalid RSA key size'), codes.ERR_INVALID_KEY_SIZE)\n }\n break\n default:\n break\n }\n\n let keyInfo\n try {\n const keypair = await generateKeyPair(type, size)\n const kid = await keypair.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await keypair.export(dek)\n keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n\n await batch.commit()\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n return keyInfo\n }\n\n /**\n * List all the keys.\n *\n * @returns {Promise}\n */\n async listKeys () {\n const query = {\n prefix: infoPrefix\n }\n\n const info = []\n for await (const value of this.components.getDatastore().query(query)) {\n info.push(JSON.parse(uint8ArrayToString(value.value)))\n }\n\n return info\n }\n\n /**\n * Find a key by it's id\n */\n async findKeyById (id: string): Promise {\n try {\n const keys = await this.listKeys()\n return keys.find((k) => k.id === id)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Find a key by it's name.\n *\n * @param {string} name - The local key name.\n * @returns {Promise}\n */\n async findKeyByName (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n const dsname = DsInfoName(name)\n try {\n const res = await this.components.getDatastore().get(dsname)\n return JSON.parse(uint8ArrayToString(res))\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Remove an existing key.\n *\n * @param {string} name - The local key name; must already exist.\n * @returns {Promise}\n */\n async removeKey (name: string) {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n const dsname = DsName(name)\n const keyInfo = await this.findKeyByName(name)\n const batch = this.components.getDatastore().batch()\n batch.delete(dsname)\n batch.delete(DsInfoName(name))\n await batch.commit()\n return keyInfo\n }\n\n /**\n * Rename a key\n *\n * @param {string} oldName - The old local key name; must already exist.\n * @param {string} newName - The new local key name; must not already exist.\n * @returns {Promise}\n */\n async renameKey (oldName: string, newName: string): Promise {\n if (!validateKeyName(oldName) || oldName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid old key name '${oldName}'`), codes.ERR_OLD_KEY_NAME_INVALID)\n }\n if (!validateKeyName(newName) || newName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid new key name '${newName}'`), codes.ERR_NEW_KEY_NAME_INVALID)\n }\n const oldDsname = DsName(oldName)\n const newDsname = DsName(newName)\n const oldInfoName = DsInfoName(oldName)\n const newInfoName = DsInfoName(newName)\n\n const exists = await this.components.getDatastore().has(newDsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${newName}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n try {\n const pem = await this.components.getDatastore().get(oldDsname)\n const res = await this.components.getDatastore().get(oldInfoName)\n\n const keyInfo = JSON.parse(uint8ArrayToString(res))\n keyInfo.name = newName\n const batch = this.components.getDatastore().batch()\n batch.put(newDsname, pem)\n batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))\n batch.delete(oldDsname)\n batch.delete(oldInfoName)\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Export an existing key as a PEM encrypted PKCS #8 string\n */\n async exportKey (name: string, password: string) {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (password == null) {\n await randomDelay()\n throw errCode(new Error('Password is required'), codes.ERR_PASSWORD_REQUIRED)\n }\n\n const dsname = DsName(name)\n try {\n const res = await this.components.getDatastore().get(dsname)\n const pem = uint8ArrayToString(res)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = await importKey(pem, dek)\n return await privateKey.export(password)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Import a new key from a PEM encoded PKCS #8 string\n *\n * @param {string} name - The local key name; must not already exist.\n * @param {string} pem - The PEM encoded PKCS #8 string\n * @param {string} password - The password.\n * @returns {Promise}\n */\n async importKey (name: string, pem: string, password: string): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (pem == null) {\n await randomDelay()\n throw errCode(new Error('PEM encoded key is required'), codes.ERR_PEM_REQUIRED)\n }\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n let privateKey\n try {\n privateKey = await importKey(pem, password)\n } catch (err: any) {\n await randomDelay()\n throw errCode(new Error('Cannot read the key, most likely the password is wrong'), codes.ERR_CANNOT_READ_KEY)\n }\n\n let kid\n try {\n kid = await privateKey.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n pem = await privateKey.export(dek)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n const keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n\n return keyInfo\n }\n\n /**\n * Import a peer key\n */\n async importPeer (name: string, peer: PeerId): Promise {\n try {\n if (!validateKeyName(name)) {\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (peer == null) {\n throw errCode(new Error('PeerId is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n if (peer.privateKey == null) {\n throw errCode(new Error('PeerId.privKey is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n\n const privateKey = await unmarshalPrivateKey(peer.privateKey)\n\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await privateKey.export(dek)\n const keyInfo: KeyInfo = {\n name: name,\n id: peer.toString()\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Gets the private key as PEM encoded PKCS #8 string\n */\n async getPrivateKey (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n try {\n const dsname = DsName(name)\n const res = await this.components.getDatastore().get(dsname)\n return uint8ArrayToString(res)\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Rotate keychain password and re-encrypt all associated keys\n */\n async rotateKeychainPass (oldPass: string, newPass: string) {\n if (typeof oldPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid old pass type '${typeof oldPass}'`), codes.ERR_INVALID_OLD_PASS_TYPE)\n }\n if (typeof newPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid new pass type '${typeof newPass}'`), codes.ERR_INVALID_NEW_PASS_TYPE)\n }\n if (newPass.length < 20) {\n await randomDelay()\n throw errCode(new Error(`Invalid pass length ${newPass.length}`), codes.ERR_INVALID_PASS_LENGTH)\n }\n log('recreating keychain')\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const oldDek = cached.dek\n this.init.pass = newPass\n const newDek = newPass != null && this.init.dek?.salt != null\n ? pbkdf2(\n newPass,\n this.init.dek.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n privates.set(this, { dek: newDek })\n const keys = await this.listKeys()\n for (const key of keys) {\n const res = await this.components.getDatastore().get(DsName(key.name))\n const pem = uint8ArrayToString(res)\n const privateKey = await importKey(pem, oldDek)\n const password = newDek.toString()\n const keyAsPEM = await privateKey.export(password)\n\n // Update stored key\n const batch = this.components.getDatastore().batch()\n const keyInfo = {\n name: key.name,\n id: key.id\n }\n batch.put(DsName(key.name), uint8ArrayFromString(keyAsPEM))\n batch.put(DsInfoName(key.name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n }\n log('keychain reconstructed')\n }\n}\n","import type { MovingAverage } from '@libp2p/interface-metrics'\n\nexport class DefaultMovingAverage {\n public movingAverage: number\n public variance: number\n public deviation: number\n public forecast: number\n private readonly timespan: number\n private previousTime?: number\n\n constructor (timespan: number) {\n if (typeof timespan !== 'number') {\n throw new Error('must provide a timespan to the moving average constructor')\n }\n\n if (timespan <= 0) {\n throw new Error('must provide a timespan > 0 to the moving average constructor')\n }\n\n this.timespan = timespan\n this.movingAverage = 0\n this.variance = 0\n this.deviation = 0\n this.forecast = 0\n }\n\n alpha (t: number, pt: number) {\n return 1 - (Math.exp(-(t - pt) / this.timespan))\n }\n\n push (time: number, value: number) {\n if (this.previousTime != null) {\n // calculate moving average\n const a = this.alpha(time, this.previousTime)\n const diff = value - this.movingAverage\n const incr = a * diff\n this.movingAverage = a * value + (1 - a) * this.movingAverage\n // calculate variance & deviation\n this.variance = (1 - a) * (this.variance + diff * incr)\n this.deviation = Math.sqrt(this.variance)\n // calculate forecast\n this.forecast = this.movingAverage + a * diff\n } else {\n this.movingAverage = value\n }\n\n this.previousTime = time\n }\n}\n\nexport function createMovingAverage (timespan: number): MovingAverage {\n return new DefaultMovingAverage(timespan)\n}\n","import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { createMovingAverage } from './moving-average.js'\n// @ts-expect-error no types\nimport retimer from 'retimer'\nimport type { MovingAverages, Stats, TransferStats } from '@libp2p/interface-metrics'\n\nexport interface StatsEvents {\n 'update': CustomEvent\n}\n\nexport interface StatsInit {\n enabled: boolean\n initialCounters: ['dataReceived', 'dataSent']\n movingAverageIntervals: number[]\n computeThrottleMaxQueueSize: number\n computeThrottleTimeout: number\n}\n\nexport class DefaultStats extends EventEmitter implements Stats {\n private readonly enabled: boolean\n public queue: Array<[string, number, number]>\n private stats: TransferStats\n private frequencyLastTime: number\n private frequencyAccumulators: Record\n private movingAverages: MovingAverages\n private timeout?: any\n private readonly computeThrottleMaxQueueSize: number\n private readonly computeThrottleTimeout: number\n private readonly movingAverageIntervals: number[]\n\n /**\n * A queue based manager for stat processing\n */\n constructor (init: StatsInit) {\n super()\n\n this.enabled = init.enabled\n this.queue = []\n this.stats = {\n dataReceived: 0n,\n dataSent: 0n\n }\n this.frequencyLastTime = Date.now()\n this.frequencyAccumulators = {}\n this.movingAverages = {\n dataReceived: [],\n dataSent: []\n }\n this.computeThrottleMaxQueueSize = init.computeThrottleMaxQueueSize\n this.computeThrottleTimeout = init.computeThrottleTimeout\n\n this._update = this._update.bind(this)\n\n this.movingAverageIntervals = init.movingAverageIntervals\n\n for (let i = 0; i < init.initialCounters.length; i++) {\n const key = init.initialCounters[i]\n this.stats[key] = 0n\n this.movingAverages[key] = []\n\n for (let k = 0; k < this.movingAverageIntervals.length; k++) {\n const interval = this.movingAverageIntervals[k]\n const ma = this.movingAverages[key][interval] = createMovingAverage(interval)\n ma.push(this.frequencyLastTime, 0)\n }\n }\n }\n\n /**\n * Initializes the internal timer if there are items in the queue. This\n * should only need to be called if `Stats.stop` was previously called, as\n * `Stats.push` will also start the processing\n */\n start () {\n if (!this.enabled) {\n return\n }\n\n if (this.queue.length > 0) {\n this._resetComputeTimeout()\n }\n }\n\n /**\n * Stops processing and computing of stats by clearing the internal\n * timer\n */\n stop () {\n if (this.timeout != null) {\n this.timeout.clear()\n this.timeout = null\n }\n }\n\n /**\n * Returns a clone of the current stats.\n */\n getSnapshot () {\n return Object.assign({}, this.stats)\n }\n\n /**\n * Returns a clone of the internal movingAverages\n */\n getMovingAverages (): MovingAverages {\n return Object.assign({}, this.movingAverages)\n }\n\n /**\n * Pushes the given operation data to the queue, along with the\n * current Timestamp, then resets the update timer.\n */\n push (counter: string, inc: number) {\n this.queue.push([counter, inc, Date.now()])\n this._resetComputeTimeout()\n }\n\n /**\n * Resets the timeout for triggering updates.\n */\n _resetComputeTimeout () {\n this.timeout = retimer(this._update, this._nextTimeout())\n }\n\n /**\n * Calculates and returns the timeout for the next update based on\n * the urgency of the update.\n */\n _nextTimeout () {\n // calculate the need for an update, depending on the queue length\n const urgency = this.queue.length / this.computeThrottleMaxQueueSize\n const timeout = Math.max(this.computeThrottleTimeout * (1 - urgency), 0)\n return timeout\n }\n\n /**\n * If there are items in the queue, they will will be processed and\n * the frequency for all items will be updated based on the Timestamp\n * of the last item in the queue. The `update` event will also be emitted\n * with the latest stats.\n *\n * If there are no items in the queue, no action is taken.\n */\n _update () {\n this.timeout = null\n if (this.queue.length > 0) {\n let last: [string, number, number] = ['', 0, 0]\n\n for (last of this.queue) {\n this._applyOp(last)\n }\n\n this.queue = []\n\n if (last.length > 2 && last[0] !== '') {\n this._updateFrequency(last[2]) // contains timestamp of last op\n }\n\n this.dispatchEvent(new CustomEvent('update', {\n detail: this.stats\n }))\n }\n }\n\n /**\n * For each key in the stats, the frequency and moving averages\n * will be updated via Stats._updateFrequencyFor based on the time\n * difference between calls to this method.\n */\n _updateFrequency (latestTime: number) {\n const timeDiff = latestTime - this.frequencyLastTime\n\n this._updateFrequencyFor('dataReceived', timeDiff, latestTime)\n this._updateFrequencyFor('dataSent', timeDiff, latestTime)\n\n this.frequencyLastTime = latestTime\n }\n\n /**\n * Updates the `movingAverages` for the given `key` and also\n * resets the `frequencyAccumulator` for the `key`.\n */\n _updateFrequencyFor (key: 'dataReceived' | 'dataSent', timeDiffMS: number, latestTime: number) {\n const count = this.frequencyAccumulators[key] ?? 0\n this.frequencyAccumulators[key] = 0\n // if `timeDiff` is zero, `hz` becomes Infinity, so we fallback to 1ms\n const safeTimeDiff = timeDiffMS ?? 1\n const hz = (count / safeTimeDiff) * 1000\n\n let movingAverages = this.movingAverages[key]\n if (movingAverages == null) {\n movingAverages = this.movingAverages[key] = []\n }\n\n const intervals = this.movingAverageIntervals\n\n for (let i = 0; i < intervals.length; i++) {\n const movingAverageInterval = intervals[i]\n let movingAverage = movingAverages[movingAverageInterval]\n if (movingAverage == null) {\n movingAverage = movingAverages[movingAverageInterval] = createMovingAverage(movingAverageInterval)\n }\n movingAverage.push(latestTime, hz)\n }\n }\n\n /**\n * For the given operation, `op`, the stats and `frequencyAccumulator`\n * will be updated or initialized if they don't already exist.\n */\n _applyOp (op: [string, number, number]) {\n const key = op[0]\n const inc = op[1]\n\n if (typeof inc !== 'number') {\n throw new Error('invalid increment number')\n }\n\n let n: bigint\n\n if (!Object.prototype.hasOwnProperty.call(this.stats, key)) {\n // @ts-expect-error cannot index type with key\n n = this.stats[key] = 0n\n } else {\n // @ts-expect-error cannot index type with key\n n = this.stats[key]\n }\n\n // @ts-expect-error cannot index type with key\n this.stats[key] = n + BigInt(inc)\n\n if (this.frequencyAccumulators[key] == null) {\n this.frequencyAccumulators[key] = 0\n }\n\n this.frequencyAccumulators[key] += inc\n }\n}\n","import { pipe } from 'it-pipe'\nimport each from 'it-foreach'\nimport LRU from 'hashlru'\nimport { METRICS as defaultOptions } from '../constants.js'\nimport { DefaultStats, StatsInit } from './stats.js'\nimport type { ComponentMetricsUpdate, Metrics, Stats, TrackedMetric, TrackStreamOptions } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\n\nconst initialCounters: ['dataReceived', 'dataSent'] = [\n 'dataReceived',\n 'dataSent'\n]\n\nconst directionToEvent = {\n in: 'dataReceived',\n out: 'dataSent'\n}\n\nexport interface OnMessageOptions {\n remotePeer: PeerId\n protocol?: string\n direction: 'in' | 'out'\n dataLength: number\n}\n\nexport interface MetricsInit {\n enabled: boolean\n computeThrottleMaxQueueSize: number\n computeThrottleTimeout: number\n movingAverageIntervals: number[]\n maxOldPeersRetention: number\n}\n\nexport class DefaultMetrics implements Metrics, Startable {\n public globalStats: DefaultStats\n\n private readonly enabled: boolean\n private readonly peerStats: Map\n private readonly protocolStats: Map\n private readonly oldPeers: ReturnType\n private running: boolean\n private readonly systems: Map>>\n private readonly statsInit: StatsInit\n\n constructor (init: MetricsInit) {\n this.enabled = init.enabled\n this.statsInit = {\n ...init,\n initialCounters\n }\n this.globalStats = new DefaultStats(this.statsInit)\n this.peerStats = new Map()\n this.protocolStats = new Map()\n this.oldPeers = LRU(init.maxOldPeersRetention ?? defaultOptions.maxOldPeersRetention)\n this.running = false\n this._onMessage = this._onMessage.bind(this)\n this.systems = new Map()\n }\n\n isStarted () {\n return this.running\n }\n\n /**\n * Must be called for stats to saved. Any data pushed for tracking\n * will be ignored.\n */\n async start () {\n if (!this.enabled) {\n return\n }\n\n this.running = true\n }\n\n /**\n * Stops all averages timers and prevents new data from being tracked.\n * Once `stop` is called, `start` must be called to resume stats tracking.\n */\n async stop () {\n if (!this.running) {\n return\n }\n\n this.running = false\n this.globalStats.stop()\n\n for (const stats of this.peerStats.values()) {\n stats.stop()\n }\n\n for (const stats of this.protocolStats.values()) {\n stats.stop()\n }\n }\n\n /**\n * Gets the global `Stats` object\n */\n getGlobal () {\n return this.globalStats\n }\n\n /**\n * Returns a list of `PeerId` strings currently being tracked\n */\n getPeers () {\n return Array.from(this.peerStats.keys())\n }\n\n getComponentMetrics () {\n return this.systems\n }\n\n updateComponentMetric (update: ComponentMetricsUpdate) {\n const { system = 'libp2p', component, metric, value, label, help } = update\n\n if (!this.systems.has(system)) {\n this.systems.set(system, new Map())\n }\n\n const systemMetrics = this.systems.get(system)\n\n if (systemMetrics == null) {\n throw new Error('Unknown metric system')\n }\n\n if (!systemMetrics.has(component)) {\n systemMetrics.set(component, new Map())\n }\n\n const componentMetrics = systemMetrics.get(component)\n\n if (componentMetrics == null) {\n throw new Error('Unknown metric component')\n }\n\n componentMetrics.set(metric, {\n label,\n help,\n calculate: typeof value !== 'function' ? () => value : value\n })\n }\n\n /**\n * Returns the `Stats` object for the given `PeerId` whether it\n * is a live peer, or in the disconnected peer LRU cache.\n */\n forPeer (peerId: PeerId): Stats | undefined {\n const idString = peerId.toString()\n return this.peerStats.get(idString) ?? this.oldPeers.get(idString)\n }\n\n /**\n * Returns a list of all protocol strings currently being tracked\n */\n getProtocols (): string[] {\n return Array.from(this.protocolStats.keys())\n }\n\n /**\n * Returns the `Stats` object for the given `protocol`\n */\n forProtocol (protocol: string): Stats | undefined {\n return this.protocolStats.get(protocol)\n }\n\n /**\n * Should be called when all connections to a given peer\n * have closed. The `Stats` collection for the peer will\n * be stopped and moved to an LRU for temporary retention.\n */\n onPeerDisconnected (peerId: PeerId) {\n const idString = peerId.toString()\n const peerStats = this.peerStats.get(idString)\n\n if (peerStats != null) {\n peerStats.stop()\n\n this.peerStats.delete(idString)\n this.oldPeers.set(idString, peerStats)\n }\n }\n\n /**\n * Takes the metadata for a message and tracks it in the\n * appropriate categories. If the protocol is present, protocol\n * stats will also be tracked.\n */\n _onMessage (opts: OnMessageOptions) {\n if (!this.running) {\n return\n }\n\n const { remotePeer, protocol, direction, dataLength } = opts\n\n const key = directionToEvent[direction]\n\n let peerStats = this.forPeer(remotePeer)\n if (peerStats == null) {\n const stats = new DefaultStats(this.statsInit)\n this.peerStats.set(remotePeer.toString(), stats)\n peerStats = stats\n }\n\n // Peer and global stats\n peerStats.push(key, dataLength)\n this.globalStats.push(key, dataLength)\n\n // Protocol specific stats\n if (protocol != null) {\n let protocolStats = this.forProtocol(protocol)\n\n if (protocolStats == null) {\n const stats = new DefaultStats(this.statsInit)\n this.protocolStats.set(protocol, stats)\n protocolStats = stats\n }\n\n protocolStats.push(key, dataLength)\n }\n }\n\n /**\n * Replaces the `PeerId` string with the given `peerId`.\n * If stats are already being tracked for the given `peerId`, the\n * placeholder stats will be merged with the existing stats.\n *\n * @param {PeerId} placeholder - A peerId string\n * @param {PeerId} peerId\n * @returns {void}\n */\n updatePlaceholder (placeholder: PeerId, peerId: PeerId) {\n if (!this.running) {\n return\n }\n\n const placeholderString = placeholder.toString()\n const placeholderStats = this.peerStats.get(placeholderString) ?? this.oldPeers.get(placeholderString)\n const peerIdString = peerId.toString()\n const existingStats = this.peerStats.get(peerIdString) ?? this.oldPeers.get(peerIdString)\n let mergedStats = placeholderStats\n\n // If we already have stats, merge the two\n if (existingStats != null) {\n // If existing, merge\n mergedStats = mergeStats(existingStats, mergedStats)\n // Attempt to delete from the old peers list just in case it was tracked there\n this.oldPeers.remove(peerIdString)\n }\n\n this.peerStats.delete(placeholder.toString())\n this.peerStats.set(peerIdString, mergedStats)\n mergedStats.start()\n }\n\n /**\n * Tracks data running through a given Duplex Iterable `stream`. If\n * the `peerId` is not provided, a placeholder string will be created and\n * returned. This allows lazy tracking of a peer when the peer is not yet known.\n * When the `PeerId` is known, `Metrics.updatePlaceholder` should be called\n * with the placeholder string returned from here, and the known `PeerId`.\n */\n trackStream (opts: TrackStreamOptions): void {\n const { stream, remotePeer, protocol } = opts\n\n if (!this.running) {\n return\n }\n\n const source = stream.source\n stream.source = each(source, chunk => this._onMessage({\n remotePeer,\n protocol,\n direction: 'in',\n dataLength: chunk.byteLength\n }))\n\n const sink = stream.sink\n stream.sink = async source => {\n return await pipe(\n source,\n (source) => each(source, chunk => {\n this._onMessage({\n remotePeer,\n protocol,\n direction: 'out',\n dataLength: chunk.byteLength\n })\n }),\n sink\n )\n }\n }\n}\n\n/**\n * Merges `other` into `target`. `target` will be modified\n * and returned\n */\nfunction mergeStats (target: DefaultStats, other: DefaultStats) {\n target.stop()\n other.stop()\n\n // Merge queues\n target.queue = [...target.queue, ...other.queue]\n\n // TODO: how to merge moving averages?\n return target\n}\n","export default async function pReflect(promise) {\n\ttry {\n\t\tconst value = await promise;\n\n\t\treturn {\n\t\t\tstatus: 'fulfilled',\n\t\t\tvalue,\n\t\t\tisFulfilled: true,\n\t\t\tisRejected: false\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tstatus: 'rejected',\n\t\t\treason: error,\n\t\t\tisFulfilled: false,\n\t\t\tisRejected: true\n\t\t};\n\t}\n}\n\nexport function isFulfilled(promiseResult) {\n\treturn 'value' in promiseResult;\n}\n\nexport function isRejected(promiseResult) {\n\treturn 'reason' in promiseResult;\n}\n","import checkPrivateRedeclaration from \"./checkPrivateRedeclaration.js\";\nexport default function _classPrivateFieldInitSpec(obj, privateMap, value) {\n checkPrivateRedeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}","export default function _checkPrivateRedeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}","export default function _classExtractFieldDescriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n\n return privateMap.get(receiver);\n}","import classApplyDescriptorSet from \"./classApplyDescriptorSet.js\";\nimport classExtractFieldDescriptor from \"./classExtractFieldDescriptor.js\";\nexport default function _classPrivateFieldSet(receiver, privateMap, value) {\n var descriptor = classExtractFieldDescriptor(receiver, privateMap, \"set\");\n classApplyDescriptorSet(receiver, descriptor, value);\n return value;\n}","export default function _classApplyDescriptorSet(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n\n descriptor.value = value;\n }\n}","import classApplyDescriptorGet from \"./classApplyDescriptorGet.js\";\nimport classExtractFieldDescriptor from \"./classExtractFieldDescriptor.js\";\nexport default function _classPrivateFieldGet(receiver, privateMap) {\n var descriptor = classExtractFieldDescriptor(receiver, privateMap, \"get\");\n return classApplyDescriptorGet(receiver, descriptor);\n}","export default function _classApplyDescriptorGet(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n\n return descriptor.value;\n}","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\t\treturn current.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n}\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tif (queue.size > 0) {\n\t\t\tqueue.dequeue()();\n\t\t}\n\t};\n\n\tconst run = async (fn, resolve, args) => {\n\t\tactiveCount++;\n\n\t\tconst result = (async () => fn(...args))();\n\n\t\tresolve(result);\n\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\tnext();\n\t};\n\n\tconst enqueue = (fn, resolve, args) => {\n\t\tqueue.enqueue(run.bind(undefined, fn, resolve, args));\n\n\t\t(async () => {\n\t\t\t// This function needs to wait until the next microtask before comparing\n\t\t\t// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously\n\t\t\t// when the run function is dequeued and called. The comparison in the if-statement\n\t\t\t// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.\n\t\t\tawait Promise.resolve();\n\n\t\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\t\tqueue.dequeue()();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst generator = (fn, ...args) => new Promise(resolve => {\n\t\tenqueue(fn, resolve, args);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue: () => {\n\t\t\t\tqueue.clear();\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n","import pReflect from 'p-reflect';\nimport pLimit from 'p-limit';\n\nexport default async function pSettle(array, options = {}) {\n\tconst {concurrency = Number.POSITIVE_INFINITY} = options;\n\tconst limit = pLimit(concurrency);\n\n\treturn Promise.all(array.map(element => {\n\t\tif (element && typeof element.then === 'function') {\n\t\t\treturn pReflect(element);\n\t\t}\n\n\t\tif (typeof element === 'function') {\n\t\t\treturn pReflect(limit(() => element()));\n\t\t}\n\n\t\treturn pReflect(Promise.resolve(element));\n\t}));\n}\n","import { logger } from '@libp2p/logger'\nimport pSettle from 'p-settle'\nimport { codes } from './errors.js'\nimport errCode from 'err-code'\nimport type { Listener, Transport, TransportManager, TransportManagerEvents } from '@libp2p/interface-transport'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport { trackedMap } from '@libp2p/tracked-map'\n\nconst log = logger('libp2p:transports')\n\nexport interface TransportManagerInit {\n faultTolerance?: FaultTolerance\n}\n\nexport class DefaultTransportManager extends EventEmitter implements TransportManager, Startable {\n private readonly components: Components\n private readonly transports: Map\n private readonly listeners: Map\n private readonly faultTolerance: FaultTolerance\n private started: boolean\n\n constructor (components: Components, init: TransportManagerInit = {}) {\n super()\n\n this.components = components\n this.started = false\n this.transports = new Map()\n this.listeners = trackedMap({\n component: 'transport-manager',\n metric: 'listeners',\n metrics: this.components.getMetrics()\n })\n this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL\n }\n\n /**\n * Adds a `Transport` to the manager\n */\n add (transport: Transport) {\n const tag = transport[Symbol.toStringTag]\n\n if (tag == null) {\n throw errCode(new Error('Transport must have a valid tag'), codes.ERR_INVALID_KEY)\n }\n\n if (this.transports.has(tag)) {\n throw errCode(new Error('There is already a transport with this tag'), codes.ERR_DUPLICATE_TRANSPORT)\n }\n\n log('adding transport %s', tag)\n\n this.transports.set(tag, transport)\n\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, [])\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.getAddressManager().getListenAddrs()\n\n await this.listen(addrs)\n\n this.started = true\n }\n\n /**\n * Stops all listeners\n */\n async stop () {\n const tasks = []\n for (const [key, listeners] of this.listeners) {\n log('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n }\n\n await Promise.all(tasks)\n log('all listeners closed')\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, [])\n }\n\n this.started = false\n }\n\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial (ma: Multiaddr, options?: AbortOptions): Promise {\n const transport = this.transportForMultiaddr(ma)\n\n if (transport == null) {\n throw errCode(new Error(`No transport available for address ${String(ma)}`), codes.ERR_TRANSPORT_UNAVAILABLE)\n }\n\n try {\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.getUpgrader()\n })\n } catch (err: any) {\n if (err.code == null) {\n err.code = codes.ERR_TRANSPORT_DIAL_FAILED\n }\n\n throw err\n }\n }\n\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs (): Multiaddr[] {\n let addrs: Multiaddr[] = []\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()]\n }\n }\n return addrs\n }\n\n /**\n * Returns all the transports instances\n */\n getTransports () {\n return Array.of(...this.transports.values())\n }\n\n /**\n * Finds a transport that matches the given Multiaddr\n */\n transportForMultiaddr (ma: Multiaddr) {\n for (const transport of this.transports.values()) {\n const addrs = transport.filter([ma])\n\n if (addrs.length > 0) {\n return transport\n }\n }\n }\n\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen (addrs: Multiaddr[]) {\n if (addrs == null || addrs.length === 0) {\n log('no addresses were provided for listening, this node is dial only')\n return\n }\n\n const couldNotListen = []\n\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.filter(addrs)\n const tasks = []\n\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n log('creating listener for %s on %s', key, addr)\n const listener = transport.createListener({\n upgrader: this.components.getUpgrader()\n })\n\n let listeners = this.listeners.get(key)\n\n if (listeners == null) {\n listeners = []\n this.listeners.set(key, listeners)\n }\n\n listeners.push(listener)\n\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.dispatchEvent(new CustomEvent('listener:listening', {\n detail: listener\n }))\n })\n listener.addEventListener('close', () => {\n this.dispatchEvent(new CustomEvent('listener:close', {\n detail: listener\n }))\n })\n\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr))\n }\n\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key)\n continue\n }\n\n const results = await pSettle(tasks)\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.isFulfilled)\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw errCode(new Error(`Transport (${key}) could not listen on any available address`), codes.ERR_NO_VALID_ADDRESSES)\n }\n }\n\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`\n if (this.faultTolerance === FaultTolerance.FATAL_ALL) {\n throw errCode(new Error(message), codes.ERR_NO_VALID_ADDRESSES)\n }\n log(`libp2p in dial mode only: ${message}`)\n }\n }\n\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove (key: string) {\n log('removing %s', key)\n\n // Close any running listeners\n for (const listener of this.listeners.get(key) ?? []) {\n await listener.close()\n }\n\n this.transports.delete(key)\n this.listeners.delete(key)\n }\n\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll () {\n const tasks = []\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key))\n }\n\n await Promise.all(tasks)\n }\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n","\nexport const PROTOCOL_ID = '/multistream/1.0.0'\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport first from 'it-first'\nimport { abortableSource } from 'abortable-iterator'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Pushable } from 'it-pushable'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Source } from 'it-stream-types'\nimport type { Reader } from 'it-reader'\nimport type { MultistreamSelectInit } from '.'\n\nconst NewLine = uint8ArrayFromString('\\n')\n\nexport function encode (buffer: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const list = new Uint8ArrayList(buffer, NewLine)\n\n return lp.encode.single(list)\n}\n\n/**\n * `write` encodes and writes a single buffer\n */\nexport function write (writer: Pushable, buffer: Uint8Array | Uint8ArrayList, options: MultistreamSelectInit = {}) {\n const encoded = encode(buffer)\n\n if (options.writeBytes === true) {\n writer.push(encoded.subarray())\n } else {\n writer.push(encoded)\n }\n}\n\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport function writeAll (writer: Pushable, buffers: Uint8Array[], options: MultistreamSelectInit = {}) {\n const list = new Uint8ArrayList()\n\n for (const buf of buffers) {\n list.append(encode(buf))\n }\n\n if (options.writeBytes === true) {\n writer.push(list.subarray())\n } else {\n writer.push(list)\n }\n}\n\nexport async function read (reader: Reader, options?: AbortOptions): Promise {\n let byteLength = 1 // Read single byte chunks until the length is known\n const varByteSource = { // No return impl - we want the reader to remain readable\n [Symbol.asyncIterator]: () => varByteSource,\n next: async () => await reader.next(byteLength)\n }\n\n let input: Source = varByteSource\n\n // If we have been passed an abort signal, wrap the input source in an abortable\n // iterator that will throw if the operation is aborted\n if (options?.signal != null) {\n input = abortableSource(varByteSource, options.signal)\n }\n\n // Once the length has been parsed, read chunk for that length\n const onLength = (l: number) => {\n byteLength = l\n }\n\n const buf = await pipe(\n input,\n lp.decode({ onLength }),\n async (source) => await first(source)\n )\n\n if (buf == null) {\n throw errCode(new Error('no buffer returned'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n if (buf.get(buf.byteLength - 1) !== NewLine[0]) {\n throw errCode(new Error('missing newline'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n return buf.sublist(0, -1) // Remove newline\n}\n\nexport async function readString (reader: Reader, options?: AbortOptions) {\n const buf = await read(reader, options)\n\n return uint8ArrayToString(buf.subarray())\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { PROTOCOL_ID } from './index.js'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:select')\n\nexport async function select (stream: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options: MultistreamSelectInit = {}): Promise> {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols]\n const { reader, writer, rest, stream: shakeStream } = handshake(stream)\n\n const protocol = protocols.shift()\n\n if (protocol == null) {\n throw new Error('At least one protocol must be specified')\n }\n\n log('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol)\n const p1 = uint8ArrayFromString(PROTOCOL_ID)\n const p2 = uint8ArrayFromString(protocol)\n multistream.writeAll(writer, [p1, p2], options)\n\n let response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n }\n\n // We're done\n if (response === protocol) {\n rest()\n return { stream: shakeStream, protocol }\n }\n\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n log('select: write \"%s\"', protocol)\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n const response = await multistream.readString(reader, options)\n log('select: read \"%s\" for \"%s\"', response, protocol)\n\n if (response === protocol) {\n rest() // End our writer so others can start writing to stream\n return { stream: shakeStream, protocol }\n }\n }\n\n rest()\n throw errCode(new Error('protocol selection failed'), 'ERR_UNSUPPORTED_PROTOCOL')\n}\n","import { logger } from '@libp2p/logger'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { PROTOCOL_ID } from './constants.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:handle')\n\nexport async function handle (stream: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: MultistreamSelectInit): Promise> {\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n const { writer, reader, rest, stream: shakeStream } = handshake(stream)\n\n while (true) {\n const protocol = await multistream.readString(reader, options)\n log('read \"%s\"', protocol)\n\n if (protocol === PROTOCOL_ID) {\n log('respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n multistream.write(writer, uint8ArrayFromString(PROTOCOL_ID), options)\n continue\n }\n\n if (protocols.includes(protocol)) {\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n log('respond with \"%s\" for \"%s\"', protocol, protocol)\n rest()\n return { stream: shakeStream, protocol }\n }\n\n if (protocol === 'ls') {\n // \\n\\n\\n\n multistream.write(writer, new Uint8ArrayList(...protocols.map(p => multistream.encode(uint8ArrayFromString(p)))), options)\n // multistream.writeAll(writer, protocols.map(p => uint8ArrayFromString(p)))\n log('respond with \"%s\" for %s', protocols, protocol)\n continue\n }\n\n multistream.write(writer, uint8ArrayFromString('na'), options)\n log('respond with \"na\" for \"%s\"', protocol)\n }\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type * as Status from './status.js'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface ConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\nexport type Direction = 'inbound' | 'outbound'\n\nexport interface ConnectionStat {\n /**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the connection\n */\n timeline: ConnectionTimeline\n\n /**\n * Once a multiplexer has been negotiated for this stream, it will be set on the stat object\n */\n multiplexer?: string\n\n /**\n * Once a connection encrypter has been negotiated for this stream, it will be set on the stat object\n */\n encryption?: string\n\n /**\n * The current status of the connection\n */\n status: keyof typeof Status\n}\n\nexport interface StreamTimeline {\n open: number\n close?: number\n}\n\nexport interface StreamStat {\n /**\n * Outbound streams are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the stream\n */\n timeline: StreamTimeline\n\n /**\n * Once a protocol has been negotiated for this stream, it will be set on the stat object\n */\n protocol?: string\n}\n\n/**\n * A Stream is a data channel between two peers that\n * can be written to and read from at both ends.\n *\n * It may be encrypted and multiplexed depending on the\n * configuration of the nodes.\n */\nexport interface Stream extends Duplex {\n /**\n * Close a stream for reading and writing\n */\n close: () => void\n\n /**\n * Close a stream for reading only\n */\n closeRead: () => void\n\n /**\n * Close a stream for writing only\n */\n closeWrite: () => void\n\n /**\n * Call when a local error occurs, should close the stream for reading and writing\n */\n abort: (err: Error) => void\n\n /**\n * Call when a remote error occurs, should close the stream for reading and writing\n */\n reset: () => void\n\n /**\n * Unique identifier for a stream\n */\n id: string\n\n /**\n * Stats about this stream\n */\n stat: StreamStat\n\n /**\n * User defined stream metadata\n */\n metadata: Record\n}\n\n/**\n * A Connection is a high-level representation of a connection\n * to a remote peer that may have been secured by encryption and\n * multiplexed, depending on the configuration of the nodes\n * between which the connection is made.\n */\nexport interface Connection {\n id: string\n stat: ConnectionStat\n remoteAddr: Multiaddr\n remotePeer: PeerId\n tags: string[]\n streams: Stream[]\n\n newStream: (multicodecs: string | string[], options?: AbortOptions) => Promise\n addStream: (stream: Stream) => void\n removeStream: (id: string) => void\n close: () => Promise\n}\n\nexport const symbol = Symbol.for('@libp2p/connection')\n\nexport function isConnection (other: any): other is Connection {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface ConnectionGater {\n /**\n * denyDialMultiaddr tests whether we're permitted to Dial the\n * specified peer.\n *\n * This is called by the dialer.connectToPeer implementation before\n * dialling a peer.\n *\n * Return true to prevent dialing the passed peer.\n */\n denyDialPeer: (peerId: PeerId) => Promise\n\n /**\n * denyDialMultiaddr tests whether we're permitted to dial the specified\n * multiaddr for the given peer.\n *\n * This is called by the dialer.connectToPeer implementation after it has\n * resolved the peer's addrs, and prior to dialling each.\n *\n * Return true to prevent dialing the passed peer on the passed multiaddr.\n */\n denyDialMultiaddr: (peerId: PeerId, multiaddr: Multiaddr) => Promise\n\n /**\n * denyInboundConnection tests whether an incipient inbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has accepted a connection from its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyInboundConnection: (maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundConnection tests whether an incipient outbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has created a connection with its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyOutboundConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyInboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyOutboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyInboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyOutboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * Used by the address book to filter passed addresses.\n *\n * Return true to allow storing the passed multiaddr for the passed peer.\n */\n filterMultiaddrForPeer: (peer: PeerId, multiaddr: Multiaddr) => Promise\n}\n\nexport interface ConnectionProtector {\n\n /**\n * Takes a given Connection and creates a private encryption stream\n * between its two peers from the PSK the Protector instance was\n * created with.\n */\n protect: (connection: MultiaddrConnection) => Promise\n}\n\nexport interface MultiaddrConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * A MultiaddrConnection is returned by transports after dialing\n * a peer. It is a low-level primitive and is the raw connection\n * without encryption or stream multiplexing.\n */\nexport interface MultiaddrConnection extends Duplex {\n close: (err?: Error) => Promise\n remoteAddr: Multiaddr\n timeline: MultiaddrConnectionTimeline\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { OPEN, CLOSING, CLOSED } from '@libp2p/interface-connection/status'\nimport { symbol } from '@libp2p/interface-connection'\nimport type { Connection, ConnectionStat, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\nconst log = logger('libp2p:connection')\n\ninterface ConnectionInit {\n remoteAddr: Multiaddr\n remotePeer: PeerId\n newStream: (protocols: string[], options?: AbortOptions) => Promise\n close: () => Promise\n getStreams: () => Stream[]\n stat: ConnectionStat\n}\n\n/**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\nexport class ConnectionImpl implements Connection {\n /**\n * Connection identifier.\n */\n public readonly id: string\n\n /**\n * Observed multiaddr of the remote peer\n */\n public readonly remoteAddr: Multiaddr\n\n /**\n * Remote peer id\n */\n public readonly remotePeer: PeerId\n\n /**\n * Connection metadata\n */\n public readonly stat: ConnectionStat\n\n /**\n * User provided tags\n *\n */\n public tags: string[]\n\n /**\n * Reference to the new stream function of the multiplexer\n */\n private readonly _newStream: (protocols: string[], options?: AbortOptions) => Promise\n\n /**\n * Reference to the close function of the raw connection\n */\n private readonly _close: () => Promise\n\n /**\n * Reference to the getStreams function of the muxer\n */\n private readonly _getStreams: () => Stream[]\n\n private _closing: boolean\n\n /**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\n constructor (init: ConnectionInit) {\n const { remoteAddr, remotePeer, newStream, close, getStreams, stat } = init\n\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`\n this.remoteAddr = remoteAddr\n this.remotePeer = remotePeer\n this.stat = {\n ...stat,\n status: OPEN\n }\n this._newStream = newStream\n this._close = close\n this._getStreams = getStreams\n this.tags = []\n this._closing = false\n }\n\n get [Symbol.toStringTag] () {\n return 'Connection'\n }\n\n get [symbol] () {\n return true\n }\n\n /**\n * Get all the streams of the muxer\n */\n get streams () {\n return this._getStreams()\n }\n\n /**\n * Create a new stream from this connection\n */\n async newStream (protocols: string | string[], options?: AbortOptions): Promise {\n if (this.stat.status === CLOSING) {\n throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED')\n }\n\n if (this.stat.status === CLOSED) {\n throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED')\n }\n\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n const stream = await this._newStream(protocols, options)\n\n stream.stat.direction = 'outbound'\n\n return stream\n }\n\n /**\n * Add a stream when it is opened to the registry\n */\n addStream (stream: Stream) {\n stream.stat.direction = 'inbound'\n }\n\n /**\n * Remove stream registry after it is closed\n */\n removeStream (id: string) {\n\n }\n\n /**\n * Close the connection\n */\n async close () {\n if (this.stat.status === CLOSED || this._closing) {\n return\n }\n\n this.stat.status = CLOSING\n\n // close all streams - this can throw if we're not multiplexed\n try {\n this.streams.forEach(s => s.close())\n } catch (err) {\n log.error(err)\n }\n\n // Close raw connection\n this._closing = true\n await this._close()\n this._closing = false\n\n this.stat.timeline.close = Date.now()\n this.stat.status = CLOSED\n }\n}\n\nexport function createConnection (init: ConnectionInit): Connection {\n return new ConnectionImpl(init)\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isTopology, StreamHandlerOptions, StreamHandlerRecord } from '@libp2p/interface-registrar'\nimport merge from 'merge-options'\nimport type { Registrar, StreamHandler, Topology } from '@libp2p/interface-registrar'\nimport type { PeerProtocolsChangeData } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:registrar')\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar implements Registrar {\n private readonly topologies: Map>\n private readonly handlers: Map\n private readonly components: Components\n\n constructor (components: Components) {\n this.topologies = new Map()\n this.handlers = new Map()\n this.components = components\n\n this._onDisconnect = this._onDisconnect.bind(this)\n this._onProtocolChange = this._onProtocolChange.bind(this)\n\n this.components.getConnectionManager().addEventListener('peer:disconnect', this._onDisconnect)\n\n // happens after identify\n this.components.getPeerStore().addEventListener('change:protocols', this._onProtocolChange)\n }\n\n getProtocols () {\n return Array.from(new Set([\n ...this.topologies.keys(),\n ...this.handlers.keys()\n ])).sort()\n }\n\n getHandler (protocol: string) {\n const handler = this.handlers.get(protocol)\n\n if (handler == null) {\n throw errCode(new Error(`No handler registered for protocol ${protocol}`), codes.ERR_NO_HANDLER_FOR_PROTOCOL)\n }\n\n return handler\n }\n\n getTopologies (protocol: string) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n return []\n }\n\n return [\n ...topologies.values()\n ]\n }\n\n /**\n * Registers the `handler` for each protocol\n */\n async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise {\n if (this.handlers.has(protocol)) {\n throw errCode(new Error(`Handler already registered for protocol ${protocol}`), codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED)\n }\n\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts)\n\n this.handlers.set(protocol, {\n handler,\n options\n })\n\n // Add new protocols to self protocols in the Protobook\n await this.components.getPeerStore().protoBook.add(this.components.getPeerId(), [protocol])\n }\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle (protocols: string | string[]) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols]\n\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol)\n })\n\n // Remove protocols from self protocols in the Protobook\n await this.components.getPeerStore().protoBook.remove(this.components.getPeerId(), protocolList)\n }\n\n /**\n * Register handlers for a set of multicodecs given\n */\n async register (protocol: string, topology: Topology): Promise {\n if (!isTopology(topology)) {\n log.error('topology must be an instance of interfaces/topology')\n throw errCode(new Error('topology must be an instance of interfaces/topology'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n\n let topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n topologies = new Map()\n this.topologies.set(protocol, topologies)\n }\n\n topologies.set(id, topology)\n\n // Set registrar\n await topology.setRegistrar(this)\n\n return id\n }\n\n /**\n * Unregister topology\n */\n unregister (id: string) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id)\n\n if (topologies.size === 0) {\n this.topologies.delete(protocol)\n }\n }\n }\n }\n\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect (evt: CustomEvent) {\n const connection = evt.detail\n\n void this.components.getPeerStore().protoBook.get(connection.remotePeer)\n .then(peerProtocols => {\n for (const protocol of peerProtocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(connection.remotePeer)\n }\n }\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Check if a new peer support the multicodecs for this topology\n */\n _onProtocolChange (evt: CustomEvent) {\n const { peerId, protocols, oldProtocols } = evt.detail\n\n const removed = oldProtocols.filter(protocol => !protocols.includes(protocol))\n const added = protocols.filter(protocol => !oldProtocols.includes(protocol))\n\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(peerId)\n }\n }\n\n for (const protocol of added) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n const connection = this.components.getConnectionManager().getConnections(peerId)[0]\n\n if (connection == null) {\n continue\n }\n\n topology.onConnect(peerId, connection)\n }\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mss from '@libp2p/multistream-select'\nimport { pipe } from 'it-pipe'\n// @ts-expect-error mutable-proxy does not export types\nimport mutableProxy from 'mutable-proxy'\nimport { codes } from './errors.js'\nimport { createConnection } from '@libp2p/connection'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { MultiaddrConnection, Connection, Stream } from '@libp2p/interface-connection'\nimport type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Upgrader, UpgraderEvents } from '@libp2p/interface-transport'\nimport type { Duplex } from 'it-stream-types'\nimport { Components, isInitializable } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:upgrader')\n\ninterface CreateConectionOptions {\n cryptoProtocol: string\n direction: 'inbound' | 'outbound'\n maConn: MultiaddrConnection\n upgradedConn: Duplex\n remotePeer: PeerId\n muxerFactory?: StreamMuxerFactory\n}\n\ninterface OnStreamOptions {\n connection: Connection\n stream: Stream\n protocol: string\n}\n\nexport interface CryptoResult extends SecuredConnection {\n protocol: string\n}\n\nexport interface UpgraderInit {\n connectionEncryption: ConnectionEncrypter[]\n muxers: StreamMuxerFactory[]\n\n /**\n * An amount of ms by which an inbound connection upgrade\n * must complete\n */\n inboundUpgradeTimeout: number\n}\n\nfunction findIncomingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxInboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_INBOUND_STREAMS\n}\n\nfunction findOutgoingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxOutboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_OUTBOUND_STREAMS\n}\n\nfunction countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection) {\n let streamCount = 0\n\n connection.streams.forEach(stream => {\n if (stream.stat.direction === direction && stream.stat.protocol === protocol) {\n streamCount++\n }\n })\n\n return streamCount\n}\n\nexport class DefaultUpgrader extends EventEmitter implements Upgrader {\n private readonly components: Components\n private readonly connectionEncryption: Map\n private readonly muxers: Map\n private readonly inboundUpgradeTimeout: number\n\n constructor (components: Components, init: UpgraderInit) {\n super()\n\n this.components = components\n this.connectionEncryption = new Map()\n\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter)\n })\n\n this.muxers = new Map()\n\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer)\n })\n\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout\n }\n\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound (maConn: MultiaddrConnection): Promise {\n let encryptedConn\n let remotePeer\n let upgradedConn: Duplex\n let muxerFactory: StreamMuxerFactory | undefined\n let cryptoProtocol\n let setPeer\n let proxyPeer\n const metrics = this.components.getMetrics()\n\n const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const abortableStream = abortableDuplex(maConn, timeoutController.signal)\n maConn.source = abortableStream.source\n maConn.sink = abortableStream.sink\n\n if (await this.components.getConnectionGater().denyInboundConnection(maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())\n const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n setPeer({ toString: () => idString })\n metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })\n }\n\n log('starting the inbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n const protector = this.components.getConnectionProtector()\n\n if (protector != null) {\n log('protecting the inbound connection')\n protectedConn = await protector.protect(maConn)\n }\n\n try {\n // Encrypt the connection\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptInbound(protectedConn))\n\n if (await this.components.getConnectionGater().denyInboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n // Multiplex the connection\n if (this.muxers.size > 0) {\n const multiplexed = await this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers)\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n } else {\n upgradedConn = encryptedConn\n }\n } catch (err: any) {\n log.error('Failed to upgrade inbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n if (await this.components.getConnectionGater().denyInboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n metrics.updatePlaceholder(proxyPeer, remotePeer)\n setPeer(remotePeer)\n }\n\n log('Successfully upgraded inbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n } finally {\n timeoutController.clear()\n }\n }\n\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound (maConn: MultiaddrConnection): Promise {\n const idStr = maConn.remoteAddr.getPeerId()\n if (idStr == null) {\n throw errCode(new Error('outbound connection must have a peer id'), codes.ERR_INVALID_MULTIADDR)\n }\n\n const remotePeerId = peerIdFromString(idStr)\n\n if (await this.components.getConnectionGater().denyOutboundConnection(remotePeerId, maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n let encryptedConn\n let remotePeer\n let upgradedConn\n let cryptoProtocol\n let muxerFactory\n let setPeer\n let proxyPeer\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())\n const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n setPeer({ toB58String: () => idString })\n metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })\n }\n\n log('Starting the outbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n const protector = this.components.getConnectionProtector()\n\n if (protector != null) {\n protectedConn = await protector.protect(maConn)\n }\n\n try {\n // Encrypt the connection\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptOutbound(protectedConn, remotePeerId))\n\n if (await this.components.getConnectionGater().denyOutboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n // Multiplex the connection\n if (this.muxers.size > 0) {\n const multiplexed = await this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers)\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n } else {\n upgradedConn = encryptedConn\n }\n } catch (err: any) {\n log.error('Failed to upgrade outbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n if (await this.components.getConnectionGater().denyOutboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n metrics.updatePlaceholder(proxyPeer, remotePeer)\n setPeer(remotePeer)\n }\n\n log('Successfully upgraded outbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n }\n\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection (opts: CreateConectionOptions): Connection {\n const {\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n remotePeer,\n muxerFactory\n } = opts\n\n let muxer: StreamMuxer | undefined\n let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise) | undefined\n let connection: Connection // eslint-disable-line prefer-const\n\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return\n }\n\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.getRegistrar().getProtocols()\n const { stream, protocol } = await mss.handle(muxedStream, protocols)\n log('%s: incoming stream opened on %s', direction, protocol)\n\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n metrics.trackStream({ stream, remotePeer, protocol })\n }\n\n if (connection == null) {\n return\n }\n\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.getRegistrar())\n const streamCount = countStreams(protocol, 'inbound', connection)\n\n if (streamCount === incomingLimit) {\n muxedStream.abort(errCode(new Error(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`), codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS))\n\n return\n }\n\n muxedStream.stat.protocol = protocol\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n this.components.getPeerStore().protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))\n\n connection.addStream(muxedStream)\n this._onStream({ connection, stream: { ...muxedStream, ...stream }, protocol })\n })\n .catch(err => {\n log.error(err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n })\n },\n // Run anytime a stream closes\n onStreamEnd: muxedStream => {\n connection?.removeStream(muxedStream.id)\n }\n })\n\n if (isInitializable(muxer)) {\n muxer.init(this.components)\n }\n\n newStream = async (protocols: string[], options: AbortOptions = {}): Promise => {\n if (muxer == null) {\n throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE)\n }\n\n log('%s: starting new stream on %s', direction, protocols)\n const muxedStream = muxer.newStream()\n const metrics = this.components.getMetrics()\n let controller: TimeoutController | undefined\n\n try {\n if (options.signal == null) {\n log('No abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)\n\n controller = new TimeoutController(30000)\n options.signal = controller.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n }\n\n const { stream, protocol } = await mss.select(muxedStream, protocols, options)\n\n if (metrics != null) {\n metrics.trackStream({ stream, remotePeer, protocol })\n }\n\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.getRegistrar())\n const streamCount = countStreams(protocol, 'outbound', connection)\n\n if (streamCount === outgoingLimit) {\n const err = errCode(new Error(`Too many outbound protocol streams for protocol \"${protocol}\" - limit ${outgoingLimit}`), codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)\n muxedStream.abort(err)\n\n throw err\n }\n\n muxedStream.stat.protocol = protocol\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n this.components.getPeerStore().protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))\n\n return {\n ...muxedStream,\n ...stream,\n stat: {\n ...muxedStream.stat,\n protocol\n }\n }\n } catch (err: any) {\n log.error('could not create new stream', err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n\n if (err.code != null) {\n throw err\n }\n\n throw errCode(err, codes.ERR_UNSUPPORTED_PROTOCOL)\n } finally {\n if (controller != null) {\n controller.clear()\n }\n }\n }\n\n // Pipe all data through the muxer\n pipe(upgradedConn, muxer, upgradedConn).catch(log.error)\n }\n\n const _timeline = maConn.timeline\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.stat.status === 'OPEN') {\n await connection.close()\n }\n } catch (err: any) {\n log.error(err)\n } finally {\n this.dispatchEvent(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n }\n })().catch(err => {\n log.error(err)\n })\n }\n\n return Reflect.set(...args)\n }\n })\n maConn.timeline.upgraded = Date.now()\n\n const errConnectionNotMultiplexed = () => {\n throw errCode(new Error('connection is not multiplexed'), codes.ERR_CONNECTION_NOT_MULTIPLEXED)\n }\n\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer: remotePeer,\n stat: {\n status: 'OPEN',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol\n },\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => muxer != null ? muxer.streams : errConnectionNotMultiplexed(),\n close: async () => {\n await maConn.close()\n // Ensure remaining streams are closed\n if (muxer != null) {\n muxer.close()\n }\n }\n })\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: connection\n }))\n\n return connection\n }\n\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream (opts: OnStreamOptions): void {\n const { connection, stream, protocol } = opts\n const { handler } = this.components.getRegistrar().getHandler(protocol)\n\n handler({ connection, stream })\n }\n\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound (connection: Duplex): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('handling inbound crypto protocol selection', protocols)\n\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting inbound connection...')\n\n return {\n ...await encrypter.secureInbound(this.components.getPeerId(), stream),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\n }\n\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound (connection: MultiaddrConnection, remotePeerId: PeerId): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('selecting outbound crypto protocol', protocols)\n\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting outbound connection to %p', remotePeerId)\n\n return {\n ...await encrypter.secureOutbound(this.components.getPeerId(), stream, remotePeerId),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\n }\n\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map): Promise<{ stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('outbound selecting muxer %s', protocols)\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n log('%s selected as muxer protocol', protocol)\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing outbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound (connection: MultiaddrConnection, muxers: Map): Promise<{ stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('inbound handling muxers %s', protocols)\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing inbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Identify {\n protocolVersion?: string\n agentVersion?: string\n publicKey?: Uint8Array\n listenAddrs: Uint8Array[]\n observedAddr?: Uint8Array\n protocols: string[]\n signedPeerRecord?: Uint8Array\n}\n\nexport namespace Identify {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.protocolVersion != null) {\n writer.uint32(42)\n writer.string(obj.protocolVersion)\n }\n\n if (obj.agentVersion != null) {\n writer.uint32(50)\n writer.string(obj.agentVersion)\n }\n\n if (obj.publicKey != null) {\n writer.uint32(10)\n writer.bytes(obj.publicKey)\n }\n\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n writer.uint32(18)\n writer.bytes(value)\n }\n } else {\n throw new Error('Protocol error: required field \"listenAddrs\" was not found in object')\n }\n\n if (obj.observedAddr != null) {\n writer.uint32(34)\n writer.bytes(obj.observedAddr)\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n writer.uint32(26)\n writer.string(value)\n }\n } else {\n throw new Error('Protocol error: required field \"protocols\" was not found in object')\n }\n\n if (obj.signedPeerRecord != null) {\n writer.uint32(66)\n writer.bytes(obj.signedPeerRecord)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 5:\n obj.protocolVersion = reader.string()\n break\n case 6:\n obj.agentVersion = reader.string()\n break\n case 1:\n obj.publicKey = reader.bytes()\n break\n case 2:\n obj.listenAddrs = obj.listenAddrs ?? []\n obj.listenAddrs.push(reader.bytes())\n break\n case 4:\n obj.observedAddr = reader.bytes()\n break\n case 3:\n obj.protocols = obj.protocols ?? []\n obj.protocols.push(reader.string())\n break\n case 8:\n obj.signedPeerRecord = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n obj.listenAddrs = obj.listenAddrs ?? []\n obj.protocols = obj.protocols ?? []\n\n if (obj.listenAddrs == null) {\n throw new Error('Protocol error: value for required field \"listenAddrs\" was not found in protobuf')\n }\n\n if (obj.protocols == null) {\n throw new Error('Protocol error: value for required field \"protocols\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Identify): Uint8Array => {\n return encodeMessage(obj, Identify.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Identify => {\n return decodeMessage(buf, Identify.codec())\n }\n}\n","\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.publicKey != null) {\n writer.uint32(10)\n writer.bytes(obj.publicKey)\n } else {\n throw new Error('Protocol error: required field \"publicKey\" was not found in object')\n }\n\n if (obj.payloadType != null) {\n writer.uint32(18)\n writer.bytes(obj.payloadType)\n } else {\n throw new Error('Protocol error: required field \"payloadType\" was not found in object')\n }\n\n if (obj.payload != null) {\n writer.uint32(26)\n writer.bytes(obj.payload)\n } else {\n throw new Error('Protocol error: required field \"payload\" was not found in object')\n }\n\n if (obj.signature != null) {\n writer.uint32(42)\n writer.bytes(obj.signature)\n } else {\n throw new Error('Protocol error: required field \"signature\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes()\n break\n case 2:\n obj.payloadType = reader.bytes()\n break\n case 3:\n obj.payload = reader.bytes()\n break\n case 5:\n obj.signature = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.publicKey == null) {\n throw new Error('Protocol error: value for required field \"publicKey\" was not found in protobuf')\n }\n\n if (obj.payloadType == null) {\n throw new Error('Protocol error: value for required field \"payloadType\" was not found in protobuf')\n }\n\n if (obj.payload == null) {\n throw new Error('Protocol error: value for required field \"payload\" was not found in protobuf')\n }\n\n if (obj.signature == null) {\n throw new Error('Protocol error: value for required field \"signature\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Envelope): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\n","import errCode from 'err-code'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { codes } from '../errors.js'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\n\nexport interface EnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList) => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\n }\n\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record: Record, peerId: PeerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\n\n const domain = record.domain\n const payloadType = record.codec\n const payload = record.marshal()\n const signData = formatSignaturePayload(domain, payloadType, payload)\n const key = await unmarshalPrivateKey(peerId.privateKey)\n const signature = await key.sign(signData.subarray())\n\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\n }\n\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data: Uint8Array | Uint8ArrayList, domain: string) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw errCode(new Error('envelope signature is not valid for the given domain'), codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: EnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope) {\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return await key.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = unsigned.encode(domainUint8Array.byteLength)\n const payloadTypeLength = unsigned.encode(payloadType.length)\n const payloadLength = unsigned.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.multiaddr != null) {\n writer.uint32(10)\n writer.bytes(obj.multiaddr)\n } else {\n throw new Error('Protocol error: required field \"multiaddr\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.multiaddr == null) {\n throw new Error('Protocol error: value for required field \"multiaddr\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: AddressInfo): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.peerId != null) {\n writer.uint32(10)\n writer.bytes(obj.peerId)\n } else {\n throw new Error('Protocol error: required field \"peerId\" was not found in object')\n }\n\n if (obj.seq != null) {\n writer.uint32(16)\n writer.uint64(obj.seq)\n } else {\n throw new Error('Protocol error: required field \"seq\" was not found in object')\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n writer.uint32(26)\n PeerRecord.AddressInfo.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"addresses\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes()\n break\n case 2:\n obj.seq = reader.uint64()\n break\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.peerId == null) {\n throw new Error('Protocol error: value for required field \"peerId\" was not found in protobuf')\n }\n\n if (obj.seq == null) {\n throw new Error('Protocol error: value for required field \"seq\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerRecord): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n","\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1])\n","import { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\n}\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n const peerRecord = Protobuf.decode(buf)\n const peerId = peerIdFromBytes(peerRecord.peerId)\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => new Multiaddr(a.multiaddr))\n const seqNumber = peerRecord.seq\n\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\n\n /**\n * Marshal a record to be used in an envelope\n */\n marshal () {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown) {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n","/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals (a: any[], b: any[]) {\n const sort = (a: any, b: any) => a.toString().localeCompare(b.toString())\n return a.length === b.length && b.sort(sort) && a.sort(sort).every((item, index) => b[index].equals(item))\n}\n","export const version = '0.38.0-d281a60'\nexport const name = 'libp2p'\n","\nimport { version } from '../version.js'\n\nexport const PROTOCOL_VERSION = 'ipfs/0.1.0' // deprecated\nexport const AGENT_VERSION = `js-libp2p/${version}`\nexport const MULTICODEC_IDENTIFY = '/ipfs/id/1.0.0' // deprecated\nexport const MULTICODEC_IDENTIFY_PUSH = '/ipfs/id/push/1.0.0' // deprecated\n\nexport const IDENTIFY_PROTOCOL_VERSION = '0.1.0'\nexport const MULTICODEC_IDENTIFY_PROTOCOL_NAME = 'id'\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME = 'id/push'\nexport const MULTICODEC_IDENTIFY_PROTOCOL_VERSION = '1.0.0'\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION = '1.0.0'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport drain from 'it-drain'\nimport first from 'it-first'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Multiaddr, protocols } from '@multiformats/multiaddr'\nimport { Identify } from './pb/message.js'\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport {\n MULTICODEC_IDENTIFY,\n MULTICODEC_IDENTIFY_PUSH,\n IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION\n} from './consts.js'\nimport { codes } from '../errors.js'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { Components } from '@libp2p/components'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:identify')\n\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8\n\nexport interface HostProperties {\n agentVersion: string\n}\n\nexport interface IdentifyServiceInit {\n /**\n * The prefix to use for the protocol (default: 'ipfs')\n */\n protocolPrefix: string\n\n /**\n * What details we should send as part of an identify message\n */\n host: HostProperties\n\n /**\n * How long we should wait for a remote peer to send their identify response\n */\n timeout: number\n\n /**\n * Identify responses larger than this in bytes will be rejected (default: 8192)\n */\n maxIdentifyMessageSize?: number\n\n maxInboundStreams: number\n maxOutboundStreams: number\n\n maxPushIncomingStreams: number\n maxPushOutgoingStreams: number\n}\n\nexport class IdentifyService implements Startable {\n private readonly components: Components\n private readonly identifyProtocolStr: string\n private readonly identifyPushProtocolStr: string\n private readonly host: {\n protocolVersion: string\n agentVersion: string\n }\n\n private readonly init: IdentifyServiceInit\n private started: boolean\n\n constructor (components: Components, init: IdentifyServiceInit) {\n this.components = components\n this.started = false\n this.init = init\n\n this.identifyProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`\n this.identifyPushProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`\n\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n ...init.host\n }\n\n // When a new connection happens, trigger identify\n this.components.getConnectionManager().addEventListener('peer:connect', (evt) => {\n const connection = evt.detail\n this.identify(connection).catch(log.error)\n })\n\n // When self multiaddrs change, trigger identify-push\n this.components.getPeerStore().addEventListener('change:multiaddrs', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.getPeerId().equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n\n // When self protocols change, trigger identify-push\n this.components.getPeerStore().addEventListener('change:protocols', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.getPeerId().equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n if (this.started) {\n return\n }\n\n await this.components.getPeerStore().metadataBook.setValue(this.components.getPeerId(), 'AgentVersion', uint8ArrayFromString(this.host.agentVersion))\n await this.components.getPeerStore().metadataBook.setValue(this.components.getPeerId(), 'ProtocolVersion', uint8ArrayFromString(this.host.protocolVersion))\n\n await this.components.getRegistrar().handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n await this.components.getRegistrar().handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxPushIncomingStreams,\n maxOutboundStreams: this.init.maxPushOutgoingStreams\n })\n\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.identifyProtocolStr)\n await this.components.getRegistrar().unhandle(this.identifyPushProtocolStr)\n\n this.started = false\n }\n\n /**\n * Send an Identify Push update to the list of connections\n */\n async push (connections: Connection[]): Promise {\n const signedPeerRecord = await this.components.getPeerStore().addressBook.getRawEnvelope(this.components.getPeerId())\n const listenAddrs = this.components.getAddressManager().getAddresses().map((ma) => ma.bytes)\n const protocols = await this.components.getPeerStore().protoBook.get(this.components.getPeerId())\n\n const pushes = connections.map(async connection => {\n let stream: Stream | undefined\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n stream = await connection.newStream([this.identifyPushProtocolStr], {\n signal: timeoutController.signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n await pipe(\n [Identify.encode({\n listenAddrs,\n signedPeerRecord,\n protocols\n })],\n lp.encode(),\n source,\n drain\n )\n } catch (err: any) {\n // Just log errors\n log.error('could not push identify update to peer', err)\n } finally {\n if (stream != null) {\n stream.close()\n }\n\n timeoutController.clear()\n }\n })\n\n await Promise.all(pushes)\n }\n\n /**\n * Calls `push` on all peer connections\n */\n async pushToPeerStore () {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return\n }\n\n const connections: Connection[] = []\n\n for (const conn of this.components.getConnectionManager().getConnections()) {\n const peerId = conn.remotePeer\n const peer = await this.components.getPeerStore().get(peerId)\n\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n continue\n }\n\n connections.push(conn)\n }\n\n await this.push(connections)\n }\n\n async _identify (connection: Connection, options: AbortOptions = {}): Promise {\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.identifyProtocolStr], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data == null) {\n throw errCode(new Error('No data could be retrieved'), codes.ERR_CONNECTION_ENDED)\n }\n\n try {\n return Identify.decode(data)\n } catch (err: any) {\n throw errCode(err, codes.ERR_INVALID_MESSAGE)\n }\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Requests the `Identify` message from peer associated with the given `connection`.\n * If the identified peer does not match the `PeerId` associated with the connection,\n * an error will be thrown.\n */\n async identify (connection: Connection, options: AbortOptions = {}): Promise {\n const message = await this._identify(connection, options)\n\n const {\n publicKey,\n listenAddrs,\n protocols,\n observedAddr,\n signedPeerRecord,\n agentVersion,\n protocolVersion\n } = message\n\n if (publicKey == null) {\n throw errCode(new Error('public key was missing from identify message'), codes.ERR_MISSING_PUBLIC_KEY)\n }\n\n const id = await peerIdFromKeys(publicKey)\n\n if (!connection.remotePeer.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (this.components.getPeerId().equals(id)) {\n throw errCode(new Error('identified peer is our own peer id?'), codes.ERR_INVALID_PEER)\n }\n\n // Get the observedAddr if there is one\n const cleanObservedAddr = IdentifyService.getCleanMultiaddr(observedAddr)\n\n if (signedPeerRecord != null) {\n log('received signed peer record from %p', id)\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(signedPeerRecord, PeerRecord.DOMAIN)\n\n if (!envelope.peerId.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)) {\n await this.components.getPeerStore().protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n return\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('no signed peer record received from %p', id)\n }\n\n log('falling back to legacy addresses from %p', id)\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.getPeerStore().addressBook.set(id, listenAddrs.map((addr) => new Multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n await this.components.getPeerStore().protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n // TODO: Add and score our observed addr\n log('received observed address of %s', cleanObservedAddr?.toString())\n // this.components.getAddressManager().addObservedAddr(observedAddr)\n }\n\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async _handleIdentify (data: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const publicKey = this.components.getPeerId().publicKey ?? new Uint8Array(0)\n const peerData = await this.components.getPeerStore().get(this.components.getPeerId())\n const multiaddrs = this.components.getAddressManager().getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n let signedPeerRecord = peerData.peerRecordEnvelope\n\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.components.getPeerId(),\n multiaddrs\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.getPeerId())\n await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)\n signedPeerRecord = envelope.marshal().subarray()\n }\n\n const message = Identify.encode({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr: connection.remoteAddr.bytes,\n protocols: peerData.protocols\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n await pipe(\n [message],\n lp.encode(),\n source,\n drain\n )\n } catch (err: any) {\n log.error('could not respond to identify request', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n }\n\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush (data: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n let message: Identify | undefined\n try {\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data != null) {\n message = Identify.decode(data)\n }\n } catch (err: any) {\n return log.error('received invalid message', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n\n if (message == null) {\n return log.error('received invalid message')\n }\n\n const id = connection.remotePeer\n\n if (this.components.getPeerId().equals(id)) {\n log('received push from ourselves?')\n return\n }\n\n log('received push from %p', id)\n\n if (message.signedPeerRecord != null) {\n log('received signedPeerRecord in push')\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(message.signedPeerRecord, PeerRecord.DOMAIN)\n\n if (await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)) {\n log('consumed signedPeerRecord sent in push')\n\n await this.components.getPeerStore().protoBook.set(id, message.protocols)\n return\n } else {\n log('failed to consume signedPeerRecord sent in push')\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('did not receive signedPeerRecord in push')\n }\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.getPeerStore().addressBook.set(id,\n message.listenAddrs.map((addr) => new Multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n // Update the protocols\n try {\n await this.components.getPeerStore().protoBook.set(id, message.protocols)\n } catch (err: any) {\n log.error('received invalid protocols', err)\n }\n\n log('handled push from %p', id)\n }\n\n /**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\n static getCleanMultiaddr (addr: Uint8Array | string | null | undefined) {\n if (addr != null && addr.length > 0) {\n try {\n return new Multiaddr(addr)\n } catch {\n\n }\n }\n }\n}\n\n/**\n * The protocols the IdentifyService supports\n */\nexport const multicodecs = {\n IDENTIFY: MULTICODEC_IDENTIFY,\n IDENTIFY_PUSH: MULTICODEC_IDENTIFY_PUSH\n}\n\nexport const Message = { Identify }\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, enumeration } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface FetchRequest {\n identifier: string\n}\n\nexport namespace FetchRequest {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.identifier != null) {\n writer.uint32(10)\n writer.string(obj.identifier)\n } else {\n throw new Error('Protocol error: required field \"identifier\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.identifier = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.identifier == null) {\n throw new Error('Protocol error: value for required field \"identifier\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchRequest): Uint8Array => {\n return encodeMessage(obj, FetchRequest.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchRequest => {\n return decodeMessage(buf, FetchRequest.codec())\n }\n}\n\nexport interface FetchResponse {\n status: FetchResponse.StatusCode\n data: Uint8Array\n}\n\nexport namespace FetchResponse {\n export enum StatusCode {\n OK = 'OK',\n NOT_FOUND = 'NOT_FOUND',\n ERROR = 'ERROR'\n }\n\n enum __StatusCodeValues {\n OK = 0,\n NOT_FOUND = 1,\n ERROR = 2\n }\n\n export namespace StatusCode {\n export const codec = () => {\n return enumeration(__StatusCodeValues)\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.status != null) {\n writer.uint32(8)\n FetchResponse.StatusCode.codec().encode(obj.status, writer)\n } else {\n throw new Error('Protocol error: required field \"status\" was not found in object')\n }\n\n if (obj.data != null) {\n writer.uint32(18)\n writer.bytes(obj.data)\n } else {\n throw new Error('Protocol error: required field \"data\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.status = FetchResponse.StatusCode.codec().decode(reader)\n break\n case 2:\n obj.data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.status == null) {\n throw new Error('Protocol error: value for required field \"status\" was not found in protobuf')\n }\n\n if (obj.data == null) {\n throw new Error('Protocol error: value for required field \"data\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchResponse): Uint8Array => {\n return encodeMessage(obj, FetchResponse.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchResponse => {\n return decodeMessage(buf, FetchResponse.codec())\n }\n}\n","\n// https://github.com/libp2p/specs/tree/master/fetch#wire-protocol\nexport const PROTOCOL_VERSION = '0.0.1'\nexport const PROTOCOL_NAME = 'fetch'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport * as lp from 'it-length-prefixed'\nimport { FetchRequest, FetchResponse } from './pb/proto.js'\nimport { PROTOCOL_NAME, PROTOCOL_VERSION } from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Components } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:fetch')\n\nexport interface FetchServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a remote peer to send any data\n */\n timeout: number\n}\n\nexport interface HandleMessageOptions {\n stream: Stream\n protocol: string\n}\n\nexport interface LookupFunction {\n (key: string): Promise\n}\n\n/**\n * A simple libp2p protocol for requesting a value corresponding to a key from a peer.\n * Developers can register one or more lookup function for retrieving the value corresponding to\n * a given key. Each lookup function must act on a distinct part of the overall key space, defined\n * by a fixed prefix that all keys that should be routed to that lookup function will start with.\n */\nexport class FetchService implements Startable {\n public readonly protocol: string\n private readonly components: Components\n private readonly lookupFunctions: Map\n private started: boolean\n private readonly init: FetchServiceInit\n\n constructor (components: Components, init: FetchServiceInit) {\n this.started = false\n this.components = components\n this.protocol = `/${init.protocolPrefix ?? 'libp2p'}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.lookupFunctions = new Map() // Maps key prefix to value lookup function\n this.handleMessage = this.handleMessage.bind(this)\n this.init = init\n }\n\n async start () {\n await this.components.getRegistrar().handle(this.protocol, (data) => {\n void this.handleMessage(data)\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n data.stream.close()\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Sends a request to fetch the value associated with the given key from the given peer\n */\n async fetch (peer: PeerId, key: string, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const connection = await this.components.getConnectionManager().openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.protocol], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const result = await pipe(\n [FetchRequest.encode({ identifier: key })],\n lp.encode(),\n source,\n lp.decode(),\n async function (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n const response = FetchResponse.decode(buf)\n\n switch (response.status) {\n case (FetchResponse.StatusCode.OK): {\n return response.data\n }\n case (FetchResponse.StatusCode.NOT_FOUND): {\n return null\n }\n case (FetchResponse.StatusCode.ERROR): {\n const errmsg = (new TextDecoder()).decode(response.data)\n throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)\n }\n default: {\n throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)\n }\n }\n }\n )\n\n return result ?? null\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Invoked when a fetch request is received. Reads the request message off the given stream and\n * responds based on looking up the key in the request via the lookup callback that corresponds\n * to the key's prefix.\n */\n async handleMessage (data: IncomingStreamData) {\n const { stream } = data\n const self = this\n\n await pipe(\n stream,\n lp.decode(),\n async function * (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n // for await (const buf of source) {\n const request = FetchRequest.decode(buf)\n\n let response: FetchResponse\n const lookup = self._getLookupFunction(request.identifier)\n if (lookup != null) {\n const data = await lookup(request.identifier)\n if (data != null) {\n response = { status: FetchResponse.StatusCode.OK, data }\n } else {\n response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }\n }\n } else {\n const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier)\n response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }\n }\n\n yield FetchResponse.encode(response)\n },\n lp.encode(),\n stream\n )\n }\n\n /**\n * Given a key, finds the appropriate function for looking up its corresponding value, based on\n * the key's prefix.\n */\n _getLookupFunction (key: string) {\n for (const prefix of this.lookupFunctions.keys()) {\n if (key.startsWith(prefix)) {\n return this.lookupFunctions.get(prefix)\n }\n }\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix\n */\n registerLookupFunction (prefix: string, lookup: LookupFunction) {\n if (this.lookupFunctions.has(prefix)) {\n throw errCode(new Error(\"Fetch protocol handler for key prefix '\" + prefix + \"' already registered\"), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n this.lookupFunctions.set(prefix, lookup)\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix.\n */\n unregisterLookupFunction (prefix: string, lookup?: LookupFunction) {\n if (lookup != null) {\n const existingLookup = this.lookupFunctions.get(prefix)\n\n if (existingLookup !== lookup) {\n return\n }\n }\n\n this.lookupFunctions.delete(prefix)\n }\n}\n","\nexport const PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { randomBytes } from '@libp2p/crypto'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION } from './constants.js'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { Stream } from '@libp2p/interface-connection'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:ping')\n\nexport interface PingServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a ping response\n */\n timeout: number\n}\n\nexport class PingService implements Startable {\n public readonly protocol: string\n private readonly components: Components\n private started: boolean\n private readonly init: PingServiceInit\n\n constructor (components: Components, init: PingServiceInit) {\n this.components = components\n this.started = false\n this.protocol = `/${init.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.init = init\n }\n\n async start () {\n await this.components.getRegistrar().handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage (data: IncomingStreamData) {\n const { stream } = data\n\n void pipe(stream, stream)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n *\n * @param {PeerId|Multiaddr} peer\n * @returns {Promise}\n */\n async ping (peer: PeerId, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const start = Date.now()\n const data = randomBytes(PING_LENGTH)\n const connection = await this.components.getConnectionManager().openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.protocol], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const result = await pipe(\n [data],\n source,\n async (source) => await first(source)\n )\n const end = Date.now()\n\n if (result == null || !uint8ArrayEquals(data, result.subarray())) {\n throw errCode(new Error('Received wrong ping ack'), codes.ERR_WRONG_PING_ACK)\n }\n\n return end - start\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n}\n","import { isLoopbackAddr } from 'is-loopback-addr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Check if a given multiaddr is a loopback address.\n */\nexport function isLoopback (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return isLoopbackAddr(address)\n}\n","/**\n * Check if a given ip address is a loopback address\n */\nexport function isLoopbackAddr (ip: string) {\n return /^127\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n /^::1$/.test(ip)\n}\n","import { upnpNat, NatAPI } from '@achingbrain/nat-port-mapper'\nimport { logger } from '@libp2p/logger'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { isBrowser } from 'wherearewe'\nimport isPrivateIp from 'private-ip'\nimport * as pkg from './version.js'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:nat')\nconst DEFAULT_TTL = 7200\n\nfunction highPort (min = 1024, max = 65535) {\n return Math.floor(Math.random() * (max - min + 1) + min)\n}\n\nexport interface PMPOptions {\n /**\n * Whether to enable PMP as well as UPnP\n */\n enabled?: boolean\n}\n\nexport interface NatManagerInit {\n /**\n * Whether to enable the NAT manager\n */\n enabled: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n externalAddress?: string\n\n /**\n * Pass a value to use instead of auto-detection\n */\n localAddress?: string\n\n /**\n * A string value to use for the port mapping description on the gateway\n */\n description?: string\n\n /**\n * How long UPnP port mappings should last for in seconds (minimum 1200)\n */\n ttl?: number\n\n /**\n * Whether to automatically refresh UPnP port mappings when their TTL is reached\n */\n keepAlive: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n gateway?: string\n}\n\nexport class NatManager implements Startable {\n private readonly components: Components\n private readonly enabled: boolean\n private readonly externalAddress?: string\n private readonly localAddress?: string\n private readonly description: string\n private readonly ttl: number\n private readonly keepAlive: boolean\n private readonly gateway?: string\n private started: boolean\n private client?: NatAPI\n\n constructor (components: Components, init: NatManagerInit) {\n this.components = components\n\n this.started = false\n this.enabled = init.enabled\n this.externalAddress = init.externalAddress\n this.localAddress = init.localAddress\n this.description = init.description ?? `${pkg.name}@${pkg.version} ${this.components.getPeerId().toString()}`\n this.ttl = init.ttl ?? DEFAULT_TTL\n this.keepAlive = init.keepAlive ?? true\n this.gateway = init.gateway\n\n if (this.ttl < DEFAULT_TTL) {\n throw errCode(new Error(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`), codes.ERR_INVALID_PARAMETERS)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n start () {}\n\n /**\n * Attempt to use uPnP to configure port mapping using the current gateway.\n *\n * Run after start to ensure the transport manager has all addresses configured.\n */\n afterStart () {\n if (isBrowser || !this.enabled || this.started) {\n return\n }\n\n this.started = true\n\n // done async to not slow down startup\n void this._start().catch((err) => {\n // hole punching errors are non-fatal\n log.error(err)\n })\n }\n\n async _start () {\n const addrs = this.components.getTransportManager().getAddrs()\n\n for (const addr of addrs) {\n // try to open uPnP ports for each thin waist address\n const { family, host, port, transport } = addr.toOptions()\n\n if (!addr.isThinWaistAddress() || transport !== 'tcp') {\n // only bare tcp addresses\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (isLoopback(addr)) {\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (family !== 4) {\n // ignore ipv6\n // eslint-disable-next-line no-continue\n continue\n }\n\n const client = await this._getClient()\n const publicIp = this.externalAddress ?? await client.externalIp()\n\n if (isPrivateIp(publicIp)) {\n throw new Error(`${publicIp} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`)\n }\n\n const publicPort = highPort()\n\n log(`opening uPnP connection from ${publicIp}:${publicPort} to ${host}:${port}`)\n\n await client.map({\n publicPort,\n localPort: port,\n localAddress: this.localAddress,\n protocol: transport.toUpperCase() === 'TCP' ? 'TCP' : 'UDP'\n })\n\n this.components.getAddressManager().addObservedAddr(Multiaddr.fromNodeAddress({\n family: 4,\n address: publicIp,\n port: publicPort\n }, transport))\n }\n }\n\n async _getClient () {\n if (this.client != null) {\n return this.client\n }\n\n this.client = await upnpNat({\n description: this.description,\n ttl: this.ttl,\n keepAlive: this.keepAlive,\n gateway: this.gateway\n })\n\n return this.client\n }\n\n /**\n * Stops the NAT manager\n */\n async stop () {\n if (isBrowser || this.client == null) {\n return\n }\n\n try {\n await this.client.close()\n this.client = undefined\n } catch (err: any) {\n log.error(err)\n }\n }\n}\n","\nexport async function upnpNat () {\n throw new Error('Not supported in browsers')\n}\n\nexport async function pmpNat () {\n throw new Error('Not supported in browsers')\n}\n","import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport type { Components } from '@libp2p/components'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { logger } from '@libp2p/logger'\nimport { protocols } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:peer-record-updater')\n\nexport class PeerRecordUpdater implements Startable {\n private readonly components: Components\n private started: boolean\n\n constructor (components: Components) {\n this.components = components\n this.started = false\n this.update = this.update.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n this.components.getTransportManager().addEventListener('listener:listening', this.update)\n this.components.getTransportManager().addEventListener('listener:close', this.update)\n this.components.getAddressManager().addEventListener('change:addresses', this.update)\n }\n\n async stop () {\n this.started = false\n this.components.getTransportManager().removeEventListener('listener:listening', this.update)\n this.components.getTransportManager().removeEventListener('listener:close', this.update)\n this.components.getAddressManager().removeEventListener('change:addresses', this.update)\n }\n\n /**\n * Create (or update if existing) self peer record and store it in the AddressBook.\n */\n update () {\n Promise.resolve()\n .then(async () => {\n const peerRecord = new PeerRecord({\n peerId: this.components.getPeerId(),\n multiaddrs: this.components.getAddressManager().getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.getPeerId())\n await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)\n })\n .catch(err => {\n log.error('Could not update self peer record: %o', err)\n })\n }\n}\n","import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTPeerRouting implements PeerRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async findPeer (peerId: PeerId, options: AbortOptions = {}) {\n for await (const event of this.dht.findPeer(peerId, options)) {\n if (event.name === 'FINAL_PEER') {\n return event.peer\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n async * getClosestPeers (key: Uint8Array, options: AbortOptions = {}) {\n for await (const event of this.dht.getClosestPeers(key, options)) {\n if (event.name === 'PEER_RESPONSE') {\n yield * event.closer\n }\n }\n }\n}\n","\nexport const codes = {\n ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS',\n ERR_NOT_FOUND: 'ERR_NOT_FOUND'\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { codes } from './errors.js'\nimport { PeerRecord, RecordEnvelope } from '@libp2p/peer-record'\nimport { pipe } from 'it-pipe'\nimport all from 'it-all'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport each from 'it-foreach'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { AddressFilter, Peer, PeerMultiaddrsChangeData, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Store } from './store.js'\nimport type { Envelope } from '@libp2p/interface-record'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\n\nconst log = logger('libp2p:peer-store:address-book')\nconst EVENT_NAME = 'change:multiaddrs'\n\nasync function allowAll () {\n return true\n}\n\nexport class PeerStoreAddressBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n private readonly addressFilter: AddressFilter\n\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store, addressFilter?: AddressFilter) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n this.addressFilter = addressFilter ?? allowAll\n }\n\n /**\n * ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope.\n * This will return a boolean that indicates if the record was successfully processed and added\n * into the AddressBook.\n */\n async consumePeerRecord (envelope: Envelope) {\n log.trace('consumePeerRecord await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('consumePeerRecord got write lock')\n\n let peerId\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n let peerRecord\n try {\n peerRecord = PeerRecord.createFromProtobuf(envelope.payload)\n } catch (err: any) {\n log.error('invalid peer record received')\n return false\n }\n\n peerId = peerRecord.peerId\n const multiaddrs = peerRecord.multiaddrs\n\n // Verify peerId\n if (!peerId.equals(envelope.peerId)) {\n log('signing key does not match PeerId in the PeerRecord')\n return false\n }\n\n // ensure the record has multiaddrs\n if (multiaddrs == null || multiaddrs.length === 0) {\n return false\n }\n\n if (await this.store.has(peerId)) {\n peer = await this.store.load(peerId)\n\n if (peer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope)\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)\n\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber)\n return false\n }\n }\n }\n\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter, true)\n\n // Replace unsigned addresses by the new ones from the record\n // TODO: Once we have ttls for the addresses, we should merge these in\n updatedPeer = await this.store.patchOrCreate(peerId, {\n addresses,\n peerRecordEnvelope: envelope.marshal().subarray()\n })\n\n log('stored provided peer record for %p', peerRecord.peerId)\n } finally {\n log.trace('consumePeerRecord release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(({ multiaddr }) => multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n return true\n }\n\n async getRawEnvelope (peerId: PeerId) {\n log.trace('getRawEnvelope await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getRawEnvelope got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.peerRecordEnvelope\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getRawEnvelope release read lock')\n release()\n }\n }\n\n /**\n * Get an Envelope containing a PeerRecord for the given peer.\n * Returns undefined if no record exists.\n */\n async getPeerRecord (peerId: PeerId) {\n const raw = await this.getRawEnvelope(peerId)\n\n if (raw == null) {\n return undefined\n }\n\n return await RecordEnvelope.createFromProtobuf(raw)\n }\n\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.addresses\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let hasPeer = false\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length && addresses.length === peer.addresses.length) {\n // not changing anything, no need to update\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, { addresses })\n\n log('set multiaddrs for %p', peerId)\n } finally {\n log.trace('set multiaddrs for %p', peerId)\n log('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (!hasPeer) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async add (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let hasPeer\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, { addresses })\n\n log('added multiaddrs for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (hasPeer === true) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n addresses: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: [],\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n }\n }\n}\n\nasync function filterMultiaddrs (peerId: PeerId, multiaddrs: Multiaddr[], addressFilter: AddressFilter, isCertified: boolean = false) {\n return await pipe(\n multiaddrs,\n (source) => each(source, (multiaddr) => {\n if (!Multiaddr.isMultiaddr(multiaddr)) {\n log.error('multiaddr must be an instance of Multiaddr')\n throw errcode(new Error('multiaddr must be an instance of Multiaddr'), codes.ERR_INVALID_PARAMETERS)\n }\n }),\n (source) => filter(source, async (multiaddr) => await addressFilter(peerId, multiaddr)),\n (source) => map(source, (multiaddr) => {\n return {\n multiaddr: new Multiaddr(multiaddr.toString()),\n isCertified\n }\n }),\n async (source) => await all(source)\n )\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, KeyBook, PeerPublicKeyChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:key-book')\n\nconst EVENT_NAME = 'change:pubkey'\n\nexport class PeerStoreKeyBook implements KeyBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The KeyBook is responsible for keeping the known public keys of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Set the Peer public key\n */\n async set (peerId: PeerId, publicKey: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(publicKey instanceof Uint8Array)) {\n log.error('publicKey must be an instance of Uint8Array to store data')\n throw errcode(new Error('publicKey must be an instance of PublicKey'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let updatedKey = false\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if ((peer.pubKey != null) && uint8arrayEquals(peer.pubKey, publicKey)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: publicKey\n })\n updatedKey = true\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n if (updatedKey) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: publicKey,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n }\n\n /**\n * Get Public key of the given PeerId, if stored\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await write lock')\n const release = await this.store.lock.readLock()\n log.trace('get got write lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.pubKey\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log('get release write lock')\n release()\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: undefined\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: undefined,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, MetadataBook, PeerMetadataChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:metadata-book')\n\nconst EVENT_NAME = 'change:metadata'\n\nexport class PeerStoreMetadataBook implements MetadataBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The MetadataBook is responsible for keeping metadata\n * about known peers\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Get the known data of a provided peer\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return new Map()\n }\n\n /**\n * Get specific metadata value, if it exists\n */\n async getValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('getValue await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getValue got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata.get(key)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getValue release write lock')\n release()\n }\n }\n\n async set (peerId: PeerId, metadata: Map) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(metadata instanceof Map)) {\n log.error('valid metadata must be provided to store data')\n throw errcode(new Error('valid metadata must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.mergeOrCreate(peerId, {\n metadata\n })\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n /**\n * Set metadata key and value of a provided peer\n */\n async setValue (peerId: PeerId, key: string, value: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (typeof key !== 'string' || !(value instanceof Uint8Array)) {\n log.error('valid key and value must be provided to store data')\n throw errcode(new Error('valid key and value must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('setValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('setValue got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const existingValue = peer.metadata.get(key)\n\n if (existingValue != null && uint8ArrayEquals(value, existingValue)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n metadata: new Map([[key, value]])\n })\n } finally {\n log.trace('setValue release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: updatedPeer.metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n if (peer != null) {\n await this.store.patch(peerId, {\n metadata: new Map()\n })\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: new Map(),\n oldMetadata: peer.metadata\n }\n }))\n }\n }\n\n async deleteValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('deleteValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('deleteValue got write lock')\n\n let metadata\n let peer: Peer | undefined\n\n try {\n peer = await this.store.load(peerId)\n metadata = peer.metadata\n\n metadata.delete(key)\n\n await this.store.patch(peerId, {\n metadata\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('deleteValue release write lock')\n release()\n }\n\n if (metadata != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { Peer, PeerProtocolsChangeData, PeerStore, ProtoBook } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:proto-book')\n\nconst EVENT_NAME = 'change:protocols'\n\nexport class PeerStoreProtoBook implements ProtoBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The ProtoBook is responsible for keeping the known supported\n * protocols of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n async get (peerId: PeerId) {\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.protocols\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n\n log('stored provided protocols for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async add (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...peer.protocols,\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n protocols\n })\n\n log('added provided protocols for %p', peerId)\n } finally {\n log.trace('add release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async remove (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('remove await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('remove got write lock')\n\n let peer: Peer | undefined\n let updatedPeer: Peer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const protocolSet = new Set(peer.protocols)\n\n for (const protocol of protocols) {\n protocolSet.delete(protocol)\n }\n\n if (peer.protocols.length === protocolSet.size) {\n return\n }\n\n protocols = Array.from(protocolSet)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n } finally {\n log.trace('remove release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n protocols: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: [],\n oldProtocols: peer.protocols\n }\n }))\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Peer {\n addresses: Address[]\n protocols: string[]\n metadata: Metadata[]\n pubKey?: Uint8Array\n peerRecordEnvelope?: Uint8Array\n}\n\nexport namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n writer.uint32(10)\n Address.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"addresses\" was not found in object')\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n writer.uint32(18)\n writer.string(value)\n }\n } else {\n throw new Error('Protocol error: required field \"protocols\" was not found in object')\n }\n\n if (obj.metadata != null) {\n for (const value of obj.metadata) {\n writer.uint32(26)\n Metadata.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"metadata\" was not found in object')\n }\n\n if (obj.pubKey != null) {\n writer.uint32(34)\n writer.bytes(obj.pubKey)\n }\n\n if (obj.peerRecordEnvelope != null) {\n writer.uint32(42)\n writer.bytes(obj.peerRecordEnvelope)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n addresses: [],\n protocols: [],\n metadata: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.addresses.push(Address.codec().decode(reader, reader.uint32()))\n break\n case 2:\n obj.protocols.push(reader.string())\n break\n case 3:\n obj.metadata.push(Metadata.codec().decode(reader, reader.uint32()))\n break\n case 4:\n obj.pubKey = reader.bytes()\n break\n case 5:\n obj.peerRecordEnvelope = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n}\n\nexport interface Address {\n multiaddr: Uint8Array\n isCertified?: boolean\n}\n\nexport namespace Address {\n let _codec: Codec
\n\n export const codec = (): Codec
=> {\n if (_codec == null) {\n _codec = message
((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.multiaddr != null) {\n writer.uint32(10)\n writer.bytes(obj.multiaddr)\n } else {\n throw new Error('Protocol error: required field \"multiaddr\" was not found in object')\n }\n\n if (obj.isCertified != null) {\n writer.uint32(16)\n writer.bool(obj.isCertified)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes()\n break\n case 2:\n obj.isCertified = reader.bool()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.multiaddr == null) {\n throw new Error('Protocol error: value for required field \"multiaddr\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Address): Uint8Array => {\n return encodeMessage(obj, Address.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Address => {\n return decodeMessage(buf, Address.codec())\n }\n}\n\nexport interface Metadata {\n key: string\n value: Uint8Array\n}\n\nexport namespace Metadata {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.key != null) {\n writer.uint32(10)\n writer.string(obj.key)\n } else {\n throw new Error('Protocol error: required field \"key\" was not found in object')\n }\n\n if (obj.value != null) {\n writer.uint32(18)\n writer.bytes(obj.value)\n } else {\n throw new Error('Protocol error: required field \"value\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: '',\n value: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string()\n break\n case 2:\n obj.value = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.key == null) {\n throw new Error('Protocol error: value for required field \"key\" was not found in protobuf')\n }\n\n if (obj.value == null) {\n throw new Error('Protocol error: value for required field \"value\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Metadata): Uint8Array => {\n return encodeMessage(obj, Metadata.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Metadata => {\n return decodeMessage(buf, Metadata.codec())\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PriorityQueue_queue;\nimport lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n constructor() {\n _PriorityQueue_queue.set(this, []);\n }\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n run,\n };\n if (this.size && __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\")[this.size - 1].priority >= options.priority) {\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").push(element);\n return;\n }\n const index = lowerBound(__classPrivateFieldGet(this, _PriorityQueue_queue, \"f\"), element, (a, b) => b.priority - a.priority);\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").splice(index, 0, element);\n }\n dequeue() {\n const item = __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").length;\n }\n}\n_PriorityQueue_queue = new WeakMap();\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pendingCount, _PQueue_concurrency, _PQueue_isPaused, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_emitEvents, _PQueue_onResumeInterval, _PQueue_isIntervalPaused_get, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, _PQueue_onEvent;\nimport EventEmitter from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\nconst timeoutError = new TimeoutError();\n/**\nThe error thrown by `queue.add()` when a job is aborted before it is run. See `signal`.\n*/\nexport class AbortError extends Error {\n}\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n _PQueue_instances.add(this);\n _PQueue_carryoverConcurrencyCount.set(this, void 0);\n _PQueue_isIntervalIgnored.set(this, void 0);\n _PQueue_intervalCount.set(this, 0);\n _PQueue_intervalCap.set(this, void 0);\n _PQueue_interval.set(this, void 0);\n _PQueue_intervalEnd.set(this, 0);\n _PQueue_intervalId.set(this, void 0);\n _PQueue_timeoutId.set(this, void 0);\n _PQueue_queue.set(this, void 0);\n _PQueue_queueClass.set(this, void 0);\n _PQueue_pendingCount.set(this, 0);\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n _PQueue_concurrency.set(this, void 0);\n _PQueue_isPaused.set(this, void 0);\n _PQueue_throwOnTimeout.set(this, void 0);\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n \n Applies to each future operation.\n */\n Object.defineProperty(this, \"timeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\\` (${typeof options.interval})`);\n }\n __classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, \"f\");\n __classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, \"f\");\n __classPrivateFieldSet(this, _PQueue_interval, options.interval, \"f\");\n __classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), \"f\");\n __classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, \"f\");\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n __classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, \"f\");\n __classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, \"f\");\n }\n get concurrency() {\n return __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n __classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n }\n /**\n Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options = {}) {\n return new Promise((resolve, reject) => {\n const run = async () => {\n var _a;\n var _b, _c;\n __classPrivateFieldSet(this, _PQueue_pendingCount, (_b = __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\"), _b++, _b), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\"), _c++, _c), \"f\");\n try {\n if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n reject(new AbortError('The task was aborted.'));\n return;\n }\n const operation = (this.timeout === undefined && options.timeout === undefined) ? fn({ signal: options.signal }) : pTimeout(Promise.resolve(fn({ signal: options.signal })), (options.timeout === undefined ? this.timeout : options.timeout), () => {\n if (options.throwOnTimeout === undefined ? __classPrivateFieldGet(this, _PQueue_throwOnTimeout, \"f\") : options.throwOnTimeout) {\n reject(timeoutError);\n }\n return undefined;\n });\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n reject(error);\n this.emit('error', error);\n }\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_next).call(this);\n };\n __classPrivateFieldGet(this, _PQueue_queue, \"f\").enqueue(run, options);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('add');\n });\n }\n /**\n Same as `.add()`, but accepts an array of sync or async functions.\n\n @returns A promise that resolves when all functions are resolved.\n */\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n return this;\n }\n __classPrivateFieldSet(this, _PQueue_isPaused, false, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n __classPrivateFieldSet(this, _PQueue_isPaused, true, \"f\");\n }\n /**\n Clear the queue.\n */\n clear() {\n __classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet(this, _PQueue_queueClass, \"f\"))(), \"f\");\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'next', () => __classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (__classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'idle');\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\");\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return __classPrivateFieldGet(this, _PQueue_isPaused, \"f\");\n }\n}\n_PQueue_carryoverConcurrencyCount = new WeakMap(), _PQueue_isIntervalIgnored = new WeakMap(), _PQueue_intervalCount = new WeakMap(), _PQueue_intervalCap = new WeakMap(), _PQueue_interval = new WeakMap(), _PQueue_intervalEnd = new WeakMap(), _PQueue_intervalId = new WeakMap(), _PQueue_timeoutId = new WeakMap(), _PQueue_queue = new WeakMap(), _PQueue_queueClass = new WeakMap(), _PQueue_pendingCount = new WeakMap(), _PQueue_concurrency = new WeakMap(), _PQueue_isPaused = new WeakMap(), _PQueue_throwOnTimeout = new WeakMap(), _PQueue_instances = new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") < __classPrivateFieldGet(this, _PQueue_intervalCap, \"f\");\n}, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") < __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n}, _PQueue_next = function _PQueue_next() {\n var _a;\n __classPrivateFieldSet(this, _PQueue_pendingCount, (_a = __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\"), _a--, _a), \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('next');\n}, _PQueue_emitEvents = function _PQueue_emitEvents() {\n this.emit('empty');\n if (__classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0) {\n this.emit('idle');\n }\n}, _PQueue_onResumeInterval = function _PQueue_onResumeInterval() {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n __classPrivateFieldSet(this, _PQueue_timeoutId, undefined, \"f\");\n}, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get() {\n const now = Date.now();\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\") === undefined) {\n const delay = __classPrivateFieldGet(this, _PQueue_intervalEnd, \"f\") - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n __classPrivateFieldSet(this, _PQueue_intervalCount, (__classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\")) ? __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") : 0, \"f\");\n }\n else {\n // Act as the interval is pending\n if (__classPrivateFieldGet(this, _PQueue_timeoutId, \"f\") === undefined) {\n __classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onResumeInterval).call(this);\n }, delay), \"f\");\n }\n return true;\n }\n }\n return false;\n}, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother() {\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_emitEvents).call(this);\n return false;\n }\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n const canInitializeInterval = !__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_isIntervalPaused_get);\n if (__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesConcurrentAllowAnother_get)) {\n const job = __classPrivateFieldGet(this, _PQueue_queue, \"f\").dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n }\n return true;\n }\n }\n return false;\n}, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded() {\n if (__classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalId, \"f\") !== undefined) {\n return;\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n }, __classPrivateFieldGet(this, _PQueue_interval, \"f\")), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet(this, _PQueue_interval, \"f\"), \"f\");\n}, _PQueue_onInterval = function _PQueue_onInterval() {\n if (__classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n }\n __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\") ? __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") : 0, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n}, _PQueue_processQueue = function _PQueue_processQueue() {\n // eslint-disable-next-line no-empty\n while (__classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this)) { }\n}, _PQueue_onEvent = async function _PQueue_onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n};\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst cancelablePromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst errorMessage = typeof message === 'string' ? message : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = message instanceof Error ? message : new TimeoutError(errorMessage);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t} finally {\n\t\t\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","\nexport const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read'\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read'\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read'\n\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write'\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write'\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write'\n","export interface WebworkerEventListener {\n (worker: Worker, event: MessageEvent): void\n}\n\nconst events: Record = {}\n\nconst observable = (worker: Worker & { port?: any }) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event)\n })\n\n if (worker.port != null) {\n worker.port.addEventListener('message', (event: any) => {\n observable.dispatchEvent('message', worker, event)\n })\n }\n}\n\nobservable.addEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n events[type] = []\n }\n\n events[type].push(fn)\n}\n\nobservable.removeEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n return\n }\n\n events[type] = events[type]\n .filter(listener => listener === fn)\n}\n\nobservable.dispatchEvent = function (type: string, worker: Worker, event: MessageEvent) {\n if (events[type] == null) {\n return\n }\n\n events[type].forEach(fn => fn(worker, event))\n}\n\nexport default observable\n","import { nanoid } from 'nanoid'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport observer from 'observable-webworkers'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n return await new Promise((resolve) => {\n const releaseEventListener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return await new Promise((resolve) => {\n const listener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK))\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK))\n\n return emitter\n }\n\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK)\n }\n}\n","export { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nexport let nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\n","import PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock: () => Promise\n writeLock: () => Promise\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock: (name: string, options: MorticeOptions) => Mortice['readLock']\n writeLock: (name: string, options: MorticeOptions) => Mortice['writeLock']\n}\n\nconst mutexes: Record = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required): Promise {\n let res: (release: Release) => void\n\n const p = new Promise((resolve) => {\n res = resolve\n })\n\n void queue.add(async () => await pTimeout((async () => {\n return await new Promise((resolve) => {\n res(() => {\n resolve()\n })\n })\n })(), {\n milliseconds: options.timeout\n }))\n\n return await p\n}\n\nconst createMutex = (name: string, options: Required): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\n return {\n async readLock () {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return await createReleaseable(readQueue, options)\n }\n\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start()\n\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n return await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return await readPromise\n },\n async writeLock () {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null\n\n return await createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler: () => Promise\n}\n\nexport default function createMortice (options?: MorticeOptions) {\n const opts: Required = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n","import { logger } from '@libp2p/logger'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { Metadata, Peer as PeerPB } from './pb/peer.js'\nimport mortice from 'mortice'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport type { Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:peer-store:store')\n\nconst NAMESPACE_COMMON = '/peers/'\n\nexport interface Store {\n has: (peerId: PeerId) => Promise\n save: (peer: Peer) => Promise\n load: (peerId: PeerId) => Promise\n delete: (peerId: PeerId) => Promise\n merge: (peerId: PeerId, data: Partial) => Promise\n mergeOrCreate: (peerId: PeerId, data: Partial) => Promise\n patch: (peerId: PeerId, data: Partial) => Promise\n patchOrCreate: (peerId: PeerId, data: Partial) => Promise\n all: () => AsyncIterable\n\n lock: {\n readLock: () => Promise<() => void>\n writeLock: () => Promise<() => void>\n }\n}\n\nexport class PersistentStore {\n private components: Components = new Components()\n public lock: any\n\n constructor () {\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n })\n }\n\n init (components: Components) {\n this.components = components\n }\n\n _peerIdToDatastoreKey (peerId: PeerId) {\n if (peerId.type == null) {\n log.error('peerId must be an instance of peer-id to store data')\n throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const b32key = peerId.toCID().toString()\n return new Key(`${NAMESPACE_COMMON}${b32key}`)\n }\n\n async has (peerId: PeerId) {\n return await this.components.getDatastore().has(this._peerIdToDatastoreKey(peerId))\n }\n\n async delete (peerId: PeerId) {\n await this.components.getDatastore().delete(this._peerIdToDatastoreKey(peerId))\n }\n\n async load (peerId: PeerId): Promise {\n const buf = await this.components.getDatastore().get(this._peerIdToDatastoreKey(peerId))\n const peer = PeerPB.decode(buf)\n const metadata = new Map()\n\n for (const meta of peer.metadata) {\n metadata.set(meta.key, meta.value)\n }\n\n return {\n ...peer,\n id: peerId,\n addresses: peer.addresses.map(({ multiaddr, isCertified }) => {\n return {\n multiaddr: new Multiaddr(multiaddr),\n isCertified: isCertified ?? false\n }\n }),\n metadata,\n pubKey: peer.pubKey ?? undefined,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined\n }\n }\n\n async save (peer: Peer) {\n if (peer.pubKey != null && peer.id.publicKey != null && !uint8arrayEquals(peer.pubKey, peer.id.publicKey)) {\n log.error('peer publicKey bytes do not match peer id publicKey bytes')\n throw errcode(new Error('publicKey bytes do not match peer id publicKey bytes'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // dedupe addresses\n const addressSet = new Set()\n const addresses = peer.addresses\n .filter(address => {\n if (addressSet.has(address.multiaddr.toString())) {\n return false\n }\n\n addressSet.add(address.multiaddr.toString())\n return true\n })\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString())\n })\n .map(({ multiaddr, isCertified }) => ({\n multiaddr: multiaddr.bytes,\n isCertified\n }))\n\n const metadata: Metadata[] = []\n\n ;[...peer.metadata.keys()].sort().forEach(key => {\n const value = peer.metadata.get(key)\n\n if (value != null) {\n metadata.push({ key, value })\n }\n })\n\n const buf = PeerPB.encode({\n addresses,\n protocols: peer.protocols.sort(),\n pubKey: peer.pubKey,\n metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope\n })\n\n await this.components.getDatastore().put(this._peerIdToDatastoreKey(peer.id), buf.subarray())\n\n return await this.load(peer.id)\n }\n\n async patch (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._patch(peerId, data, peer)\n }\n\n async patchOrCreate (peerId: PeerId, data: Partial) {\n let peer: Peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._patch(peerId, data, peer)\n }\n\n async _patch (peerId: PeerId, data: Partial, peer: Peer) {\n return await this.save({\n ...peer,\n ...data,\n id: peerId\n })\n }\n\n async merge (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._merge(peerId, data, peer)\n }\n\n async mergeOrCreate (peerId: PeerId, data: Partial) {\n /** @type {Peer} */\n let peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._merge(peerId, data, peer)\n }\n\n async _merge (peerId: PeerId, data: Partial, peer: Peer) {\n // if the peer has certified addresses, use those in\n // favour of the supplied versions\n const addresses = new Map()\n\n peer.addresses.forEach((addr) => {\n addresses.set(addr.multiaddr.toString(), addr.isCertified)\n })\n\n ;(data.addresses ?? []).forEach(addr => {\n const addrString = addr.multiaddr.toString()\n const isAlreadyCertified = Boolean(addresses.get(addrString))\n\n const isCertified = isAlreadyCertified || addr.isCertified\n\n addresses.set(addrString, isCertified)\n })\n\n return await this.save({\n id: peerId,\n addresses: Array.from(addresses.entries()).map(([addrStr, isCertified]) => {\n return {\n multiaddr: new Multiaddr(addrStr),\n isCertified\n }\n }),\n protocols: Array.from(new Set([\n ...(peer.protocols ?? []),\n ...(data.protocols ?? [])\n ])),\n metadata: new Map([\n ...(peer.metadata?.entries() ?? []),\n ...(data.metadata?.entries() ?? [])\n ]),\n pubKey: data.pubKey ?? (peer != null ? peer.pubKey : undefined),\n peerRecordEnvelope: data.peerRecordEnvelope ?? (peer != null ? peer.peerRecordEnvelope : undefined)\n })\n }\n\n async * all () {\n for await (const key of this.components.getDatastore().queryKeys({\n prefix: NAMESPACE_COMMON\n })) {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2]\n const buf = base32.decode(base32Str)\n\n yield this.load(peerIdFromBytes(buf))\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Tags {\n tags: Tag[]\n}\n\nexport namespace Tags {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.tags != null) {\n for (const value of obj.tags) {\n writer.uint32(10)\n Tag.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"tags\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n tags: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.tags.push(Tag.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tags): Uint8Array => {\n return encodeMessage(obj, Tags.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tags => {\n return decodeMessage(buf, Tags.codec())\n }\n}\n\nexport interface Tag {\n name: string\n value?: number\n expiry?: bigint\n}\n\nexport namespace Tag {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.name != null) {\n writer.uint32(10)\n writer.string(obj.name)\n } else {\n throw new Error('Protocol error: required field \"name\" was not found in object')\n }\n\n if (obj.value != null) {\n writer.uint32(16)\n writer.uint32(obj.value)\n }\n\n if (obj.expiry != null) {\n writer.uint32(24)\n writer.uint64(obj.expiry)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n name: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.name = reader.string()\n break\n case 2:\n obj.value = reader.uint32()\n break\n case 3:\n obj.expiry = reader.uint64()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.name == null) {\n throw new Error('Protocol error: value for required field \"name\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tag): Uint8Array => {\n return encodeMessage(obj, Tag.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tag => {\n return decodeMessage(buf, Tag.codec())\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { PeerStoreAddressBook } from './address-book.js'\nimport { PeerStoreKeyBook } from './key-book.js'\nimport { PeerStoreMetadataBook } from './metadata-book.js'\nimport { PeerStoreProtoBook } from './proto-book.js'\nimport { PersistentStore, Store } from './store.js'\nimport type { PeerStore, AddressBook, KeyBook, MetadataBook, ProtoBook, PeerStoreEvents, PeerStoreInit, Peer, TagOptions } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { Components, Initializable } from '@libp2p/components'\nimport errCode from 'err-code'\nimport { Tag, Tags } from './pb/tags.js'\n\nconst log = logger('libp2p:peer-store')\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nexport class PersistentPeerStore extends EventEmitter implements PeerStore, Initializable {\n public addressBook: AddressBook\n public keyBook: KeyBook\n public metadataBook: MetadataBook\n public protoBook: ProtoBook\n\n private components: Components = new Components()\n private readonly store: Store\n\n constructor (init: PeerStoreInit = {}) {\n super()\n\n this.store = new PersistentStore()\n this.addressBook = new PeerStoreAddressBook(this.dispatchEvent.bind(this), this.store, init.addressFilter)\n this.keyBook = new PeerStoreKeyBook(this.dispatchEvent.bind(this), this.store)\n this.metadataBook = new PeerStoreMetadataBook(this.dispatchEvent.bind(this), this.store)\n this.protoBook = new PeerStoreProtoBook(this.dispatchEvent.bind(this), this.store)\n }\n\n init (components: Components) {\n this.components = components\n ;(this.store as PersistentStore).init(components)\n }\n\n async forEach (fn: (peer: Peer) => void) {\n log.trace('getPeers await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getPeers got read lock')\n\n try {\n for await (const peer of this.store.all()) {\n if (peer.id.equals(this.components.getPeerId())) {\n // Skip self peer if present\n continue\n }\n\n fn(peer)\n }\n } finally {\n log.trace('getPeers release read lock')\n release()\n }\n }\n\n async all (): Promise {\n const output: Peer[] = []\n\n await this.forEach(peer => {\n output.push(peer)\n })\n\n return output\n }\n\n /**\n * Delete the information of the given peer in every book\n */\n async delete (peerId: PeerId) {\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n try {\n await this.store.delete(peerId)\n } finally {\n log.trace('delete release write lock')\n release()\n }\n }\n\n /**\n * Get the stored information of a given peer\n */\n async get (peerId: PeerId) {\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n return await this.store.load(peerId)\n } finally {\n log.trace('get release read lock')\n release()\n }\n }\n\n /**\n * Returns true if we have a record of the peer\n */\n async has (peerId: PeerId) {\n log.trace('has await read lock')\n const release = await this.store.lock.readLock()\n log.trace('has got read lock')\n\n try {\n return await this.store.has(peerId)\n } finally {\n log.trace('has release read lock')\n release()\n }\n }\n\n async tagPeer (peerId: PeerId, tag: string, options: TagOptions = {}) {\n const providedValue = options.value ?? 0\n const value = Math.round(providedValue)\n const ttl = options.ttl ?? undefined\n\n if (value !== providedValue || value < 0 || value > 100) {\n throw errCode(new Error('Tag value must be between 0-100'), 'ERR_TAG_VALUE_OUT_OF_BOUNDS')\n }\n\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n for (const t of tags) {\n if (t.name === tag) {\n throw errCode(new Error('Peer already tagged'), 'ERR_DUPLICATE_TAG')\n }\n }\n\n tags.push({\n name: tag,\n value,\n expiry: ttl == null ? undefined : BigInt(Date.now() + ttl)\n })\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async unTagPeer (peerId: PeerId, tag: string) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n tags = tags.filter(t => t.name !== tag)\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async getTags (peerId: PeerId) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n const now = BigInt(Date.now())\n const unexpiredTags = tags.filter(tag => tag.expiry == null || tag.expiry > now)\n\n if (unexpiredTags.length !== tags.length) {\n // remove any expired tags\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags: unexpiredTags }).subarray())\n }\n\n return unexpiredTags.map(t => ({\n name: t.name,\n value: t.value ?? 0\n }))\n }\n}\n","import drain from 'it-drain'\nimport errCode from 'err-code'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { CID } from 'multiformats/cid'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTContentRouting implements ContentRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async provide (cid: CID) {\n await drain(this.dht.provide(cid))\n }\n\n async * findProviders (cid: CID, options: AbortOptions = {}) {\n for await (const event of this.dht.findProviders(cid, options)) {\n if (event.name === 'PROVIDER') {\n yield * event.providers\n }\n }\n }\n\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise {\n await drain(this.dht.put(key, value, options))\n }\n\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n for await (const event of this.dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n}\n","import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { logger } from '@libp2p/logger'\nimport type { Components } from '@libp2p/components'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:dialer:auto-dialer')\n\nexport interface AutoDialerInit {\n enabled: boolean\n minConnections: number\n dialTimeout: number\n}\n\nexport class AutoDialer {\n private readonly components: Components\n private readonly enabled: boolean\n private readonly minConnections: number\n private readonly dialTimeout: number\n\n constructor (components: Components, init: AutoDialerInit) {\n this.components = components\n this.enabled = init.enabled\n this.minConnections = init.minConnections\n this.dialTimeout = init.dialTimeout\n }\n\n public handle (evt: CustomEvent) {\n const { detail: peer } = evt\n\n if (!this.enabled) {\n return\n }\n\n const connections = this.components.getConnectionManager().getConnections(peer.id)\n\n // If auto dialing is on and we have no connection to the peer, check if we should dial\n if (connections.length === 0) {\n const minConnections = this.minConnections ?? 0\n\n const allConnections = this.components.getConnectionManager().getConnections()\n\n if (minConnections > allConnections.length) {\n log('auto-dialing discovered peer %p with timeout %d', peer.id, this.dialTimeout)\n\n const controller = new TimeoutController(this.dialTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n void this.components.getConnectionManager().openConnection(peer.id, {\n signal: controller.signal\n })\n .catch(err => {\n log.error('could not connect to discovered peer %p with %o', peer.id, err)\n })\n .finally(() => {\n controller.clear()\n })\n }\n }\n }\n}\n","const globalFetch = globalThis.fetch;\nconst globalHeaders = globalThis.Headers;\nconst globalRequest = globalThis.Request;\nconst globalResponse = globalThis.Response;\nexport {\n globalFetch as fetch\n};\nexport {\n globalHeaders as Headers\n};\nexport {\n globalRequest as Request\n};\nexport {\n globalResponse as Response\n};","import { fetch as nativeFetch, Headers } from 'native-fetch'\n\n/**\n * Build fetch resource for request\n */\nexport function buildResource (serverResolver: string, hostname: string, recordType: string) {\n return `${serverResolver}?name=${hostname}&type=${recordType}`\n}\n\nexport interface DNSJSON {\n Question: Question[]\n Answer: Answer[]\n}\n\ninterface Question {\n name: string\n type: number\n}\n\ninterface Answer {\n name: string\n type: number\n data: string\n TTL: number\n}\n\n/**\n * Use fetch to find the record\n */\nexport async function request (resource: string, signal: AbortSignal) {\n const req = await nativeFetch(resource, {\n headers: new Headers({\n accept: 'application/dns-json'\n }),\n signal\n })\n const res = await req.json()\n\n return res as DNSJSON\n}\n\n/**\n * Creates cache key composed by recordType and hostname\n *\n * @param {string} hostname\n * @param {string} recordType\n */\nexport function getCacheKey (hostname: string, recordType: string) {\n return `${recordType}_${hostname}`\n}\n","import debug from 'debug'\nimport Receptacle from 'receptacle'\nimport * as utils from './utils.js'\nimport type { DNSJSON } from './utils'\n\nconst log = Object.assign(debug('dns-over-http-resolver'), {\n error: debug('dns-over-http-resolver:error')\n})\n\nexport interface Request { (resource: string, signal: AbortSignal): Promise }\n\ninterface ResolverOptions {\n maxCache?: number\n request?: Request\n}\n\n/**\n * DNS over HTTP resolver.\n * Uses a list of servers to resolve DNS records with HTTP requests.\n */\nclass Resolver {\n private readonly _cache: Receptacle\n private readonly _TXTcache: Receptacle\n private _servers: string[]\n private readonly _request: Request\n private _abortControllers: AbortController[]\n\n /**\n * @class\n * @param {object} [options]\n * @param {number} [options.maxCache = 100] - maximum number of cached dns records\n * @param {Request} [options.request] - function to return DNSJSON\n */\n constructor (options: ResolverOptions = {}) {\n this._cache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._TXTcache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._servers = [\n 'https://cloudflare-dns.com/dns-query',\n 'https://dns.google/resolve'\n ]\n this._request = options.request ?? utils.request\n this._abortControllers = []\n }\n\n /**\n * Cancel all outstanding DNS queries made by this resolver. Any outstanding\n * requests will be aborted and promises rejected.\n */\n cancel () {\n this._abortControllers.forEach(controller => controller.abort())\n }\n\n /**\n * Get an array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n getServers () {\n return this._servers\n }\n\n /**\n * Get a shuffled array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n _getShuffledServers () {\n const newServers = [...this._servers]\n\n for (let i = newServers.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i)\n const temp = newServers[i]\n newServers[i] = newServers[j]\n newServers[j] = temp\n }\n\n return newServers\n }\n\n /**\n * Sets the IP address and port of servers to be used when performing DNS resolution.\n *\n * @param {string[]} servers - array of RFC 5952 formatted addresses.\n */\n setServers (servers: string[]) {\n this._servers = servers\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into the appropriate DNS record\n *\n * @param {string} hostname - host name to resolve\n * @param {string} [rrType = 'A'] - resource record type\n */\n async resolve (hostname: string, rrType = 'A') {\n switch (rrType) {\n case 'A':\n return await this.resolve4(hostname)\n case 'AAAA':\n return await this.resolve6(hostname)\n case 'TXT':\n return await this.resolveTxt(hostname)\n default:\n throw new Error(`${rrType} is not supported`)\n }\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv4 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve4 (hostname: string) {\n const recordType = 'A'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryA ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv6 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve6 (hostname: string) {\n const recordType = 'AAAA'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryAaaa ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into a Text record\n *\n * @param {string} hostname - host name to resolve\n */\n async resolveTxt (hostname: string) {\n const recordType = 'TXT'\n const cached = this._TXTcache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => [a.data.replace(/['\"]+/g, '')])\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._TXTcache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryTxt ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n clearCache () {\n this._cache.clear()\n this._TXTcache.clear()\n }\n}\n\nexport default Resolver\n","import dns from 'dns-over-http-resolver'\n\nexport default dns\n","import { getProtocol } from '../protocols-table.js'\nimport Resolver from './dns.js'\nimport type { AbortOptions, Multiaddr } from '../index.js'\n\nconst { code: dnsaddrCode } = getProtocol('dnsaddr')\n\n/**\n * Resolver for dnsaddr addresses.\n */\nexport async function dnsaddrResolver (addr: Multiaddr, options: AbortOptions = {}) {\n const resolver = new Resolver()\n\n if (options.signal != null) {\n options.signal.addEventListener('abort', () => {\n resolver.cancel()\n })\n }\n\n const peerId = addr.getPeerId()\n const [, hostname] = addr.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? []\n\n if (hostname == null) {\n throw new Error('No hostname found in multiaddr')\n }\n\n const records = await resolver.resolveTxt(`_dnsaddr.${hostname}`)\n\n let addresses = records.flat().map((a) => a.split('=')[1])\n\n if (peerId != null) {\n addresses = addresses.filter((entry) => entry.includes(peerId))\n }\n\n return addresses\n}\n","import mergeOptions from 'merge-options'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport * as Constants from './constants.js'\nimport { AGENT_VERSION } from './identify/consts.js'\nimport * as RelayConstants from './circuit/constants.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { FaultTolerance } from './transport-manager.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Libp2pInit } from './index.js'\nimport { codes, messages } from './errors.js'\nimport errCode from 'err-code'\nimport type { RecursivePartial } from '@libp2p/interfaces'\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'\n\nconst DefaultConfig: Partial = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs: Multiaddr[]) => multiaddrs\n },\n connectionManager: {\n maxConnections: 300,\n minConnections: 50,\n autoDial: true,\n autoDialInterval: 10000,\n maxParallelDials: Constants.MAX_PARALLEL_DIALS,\n maxDialsPerPeer: Constants.MAX_PER_PEER_DIALS,\n dialTimeout: Constants.DIAL_TIMEOUT,\n inboundUpgradeTimeout: Constants.INBOUND_UPGRADE_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n },\n addressSorter: publicAddressesFirst\n },\n connectionGater: {},\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n },\n metrics: {\n enabled: false,\n computeThrottleMaxQueueSize: 1000,\n computeThrottleTimeout: 2000,\n movingAverageIntervals: [\n 60 * 1000, // 1 minute\n 5 * 60 * 1000, // 5 minutes\n 15 * 60 * 1000 // 15 minutes\n ],\n maxOldPeersRetention: 50\n },\n peerRouting: {\n refreshManager: {\n enabled: true,\n interval: 6e5,\n bootDelay: 10e3\n }\n },\n nat: {\n enabled: true,\n ttl: 7200,\n keepAlive: true\n },\n relay: {\n enabled: true,\n advertise: {\n bootDelay: RelayConstants.ADVERTISE_BOOT_DELAY,\n enabled: false,\n ttl: RelayConstants.ADVERTISE_TTL\n },\n hop: {\n enabled: false,\n active: false,\n timeout: 30000\n },\n autoRelay: {\n enabled: false,\n maxListeners: 2\n }\n },\n identify: {\n protocolPrefix: 'ipfs',\n host: {\n agentVersion: AGENT_VERSION\n },\n // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48\n timeout: 60000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxPushIncomingStreams: 1,\n maxPushOutgoingStreams: 1\n },\n ping: {\n protocolPrefix: 'ipfs',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n },\n fetch: {\n protocolPrefix: 'libp2p',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n }\n}\n\nexport function validateConfig (opts: RecursivePartial): Libp2pInit {\n const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts)\n\n if (resultingOptions.transports == null || resultingOptions.transports.length < 1) {\n throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED)\n }\n\n if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) {\n throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED)\n }\n\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED)\n }\n\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (resultingOptions.identify.host.agentVersion === AGENT_VERSION) {\n if (isNode || isElectronMain) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.process.version}`\n } else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`\n }\n }\n\n return resultingOptions\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerIdProto {\n id: Uint8Array\n pubKey?: Uint8Array\n privKey?: Uint8Array\n}\n\nexport namespace PeerIdProto {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.id != null) {\n writer.uint32(10)\n writer.bytes(obj.id)\n } else {\n throw new Error('Protocol error: required field \"id\" was not found in object')\n }\n\n if (obj.pubKey != null) {\n writer.uint32(18)\n writer.bytes(obj.pubKey)\n }\n\n if (obj.privKey != null) {\n writer.uint32(26)\n writer.bytes(obj.privKey)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n id: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.pubKey = reader.bytes()\n break\n case 3:\n obj.privKey = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.id == null) {\n throw new Error('Protocol error: value for required field \"id\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerIdProto): Uint8Array => {\n return encodeMessage(obj, PeerIdProto.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerIdProto => {\n return decodeMessage(buf, PeerIdProto.codec())\n }\n}\n","import { generateKeyPair, marshalPrivateKey, unmarshalPrivateKey, marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { peerIdFromKeys, peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerIdProto } from './proto.js'\nimport type { PublicKey, PrivateKey } from '@libp2p/interface-keys'\nimport type { RSAPeerId, Ed25519PeerId, Secp256k1PeerId, PeerId } from '@libp2p/interface-peer-id'\n\nexport const createEd25519PeerId = async (): Promise => {\n const key = await generateKeyPair('Ed25519')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'Ed25519') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createSecp256k1PeerId = async (): Promise => {\n const key = await generateKeyPair('secp256k1')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'secp256k1') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createRSAPeerId = async (opts?: { bits: number }): Promise => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048)\n const id = await createFromPrivKey(key)\n\n if (id.type === 'RSA') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport async function createFromPubKey (publicKey: PublicKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(publicKey))\n}\n\nexport async function createFromPrivKey (privateKey: PrivateKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey))\n}\n\nexport function exportToProtobuf (peerId: RSAPeerId | Ed25519PeerId | Secp256k1PeerId, excludePrivateKey?: boolean): Uint8Array {\n return PeerIdProto.encode({\n id: peerId.multihash.bytes,\n pubKey: peerId.publicKey,\n privKey: excludePrivateKey === true || peerId.privateKey == null ? undefined : peerId.privateKey\n })\n}\n\nexport async function createFromProtobuf (buf: Uint8Array) {\n const {\n id,\n privKey,\n pubKey\n } = PeerIdProto.decode(buf)\n\n return await createFromParts(\n id,\n privKey,\n pubKey\n )\n}\n\nexport async function createFromJSON (obj: { id: string, privKey?: string, pubKey?: string }) {\n return await createFromParts(\n uint8ArrayFromString(obj.id, 'base58btc'),\n obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined,\n obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined\n )\n}\n\nasync function createFromParts (multihash: Uint8Array, privKey?: Uint8Array, pubKey?: Uint8Array) {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey)\n\n return await createFromPrivKey(key)\n } else if (pubKey != null) {\n const key = await unmarshalPublicKey(pubKey)\n\n return await createFromPubKey(key)\n }\n\n return peerIdFromBytes(multihash)\n}\n","import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\n\nexport const symbol = Symbol.for('@libp2p/peer-discovery')\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent\n}\n\nexport interface PeerDiscovery extends EventEmitter {\n /**\n * Used to identify the peer discovery mechanism\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isPeerDiscovery function\n */\n [symbol]: true\n}\n\nexport function isPeerDiscovery (other: any): other is PeerDiscovery {\n return other != null && Boolean(other[symbol])\n}\n","import type { DualDHT, QueryEvent, SingleDHT } from '@libp2p/interface-dht'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { symbol } from '@libp2p/interface-peer-discovery'\n\nexport class DummyDHT extends EventEmitter implements DualDHT {\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/dummy-dht'\n }\n\n get wan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get lan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findProviders (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findPeer (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n getClosestPeers (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n provide (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n put (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async getMode (): Promise<'client' | 'server'> {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async setMode (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async refreshRoutingTable (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n}\n","import { EventEmitter } from '@libp2p/interfaces/events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign } from '@libp2p/interface-pubsub'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\n\nexport class DummyPubSub extends EventEmitter implements PubSub {\n isStarted (): boolean {\n return false\n }\n\n start (): void | Promise {\n\n }\n\n stop (): void | Promise {\n\n }\n\n get globalSignaturePolicy (): typeof StrictSign | typeof StrictNoSign {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n get multicodecs (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getPeers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getTopics (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n subscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n unsubscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getSubscribers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n async publish (): Promise {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n}\n","import { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport { Startable, isStartable } from '@libp2p/interfaces/startable'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { MemoryDatastore } from 'datastore-core/memory'\nimport { DefaultPeerRouting } from './peer-routing.js'\nimport { CompoundContentRouting } from './content-routing/index.js'\nimport { getPeer } from './get-peer.js'\nimport { codes } from './errors.js'\nimport { DefaultAddressManager } from './address-manager/index.js'\nimport { DefaultConnectionManager } from './connection-manager/index.js'\nimport { AutoDialler } from './connection-manager/auto-dialler.js'\nimport { Circuit } from './circuit/transport.js'\nimport { Relay } from './circuit/index.js'\nimport { KeyChain } from './keychain/index.js'\nimport { DefaultMetrics } from './metrics/index.js'\nimport { DefaultTransportManager } from './transport-manager.js'\nimport { DefaultUpgrader } from './upgrader.js'\nimport { DefaultRegistrar } from './registrar.js'\nimport { IdentifyService } from './identify/index.js'\nimport { FetchService } from './fetch/index.js'\nimport { PingService } from './ping/index.js'\nimport { NatManager } from './nat-manager.js'\nimport { PeerRecordUpdater } from './peer-record-updater.js'\nimport { DHTPeerRouting } from './dht/dht-peer-routing.js'\nimport { PersistentPeerStore } from '@libp2p/peer-store'\nimport { DHTContentRouting } from './dht/dht-content-routing.js'\nimport { AutoDialer } from './connection-manager/dialer/auto-dialer.js'\nimport { Initializable, Components, isInitializable } from '@libp2p/components'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Libp2p, Libp2pEvents, Libp2pInit, Libp2pOptions } from './index.js'\nimport { validateConfig } from './config.js'\nimport { createEd25519PeerId } from '@libp2p/peer-id-factory'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport errCode from 'err-code'\nimport { unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport { DummyDHT } from './dht/dummy-dht.js'\nimport { DummyPubSub } from './pubsub/dummy-pubsub.js'\nimport { PeerSet } from '@libp2p/peer-collections'\n\nconst log = logger('libp2p')\n\nexport class Libp2pNode extends EventEmitter implements Libp2p {\n public peerId: PeerId\n public dht: DualDHT\n public pubsub: PubSub\n public identifyService?: IdentifyService\n public fetchService: FetchService\n public pingService: PingService\n public components: Components\n public peerStore: PeerStore\n public contentRouting: ContentRouting\n public peerRouting: PeerRouting\n public keychain: KeyChain\n public connectionManager: ConnectionManager\n public registrar: Registrar\n public metrics?: Metrics\n\n private started: boolean\n private readonly services: Startable[]\n private readonly initializables: Initializable[]\n\n constructor (init: Libp2pInit) {\n super()\n\n this.initializables = []\n this.started = false\n this.peerId = init.peerId\n this.components = new Components({\n peerId: init.peerId,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: {\n denyDialPeer: async () => await Promise.resolve(false),\n denyDialMultiaddr: async () => await Promise.resolve(false),\n denyInboundConnection: async () => await Promise.resolve(false),\n denyOutboundConnection: async () => await Promise.resolve(false),\n denyInboundEncryptedConnection: async () => await Promise.resolve(false),\n denyOutboundEncryptedConnection: async () => await Promise.resolve(false),\n denyInboundUpgradedConnection: async () => await Promise.resolve(false),\n denyOutboundUpgradedConnection: async () => await Promise.resolve(false),\n filterMultiaddrForPeer: async () => await Promise.resolve(true),\n ...init.connectionGater\n }\n })\n this.components.setPeerStore(new PersistentPeerStore({\n addressFilter: this.components.getConnectionGater().filterMultiaddrForPeer,\n ...init.peerStore\n }))\n\n this.services = [\n this.components\n ]\n\n // Create Metrics\n if (init.metrics.enabled) {\n this.metrics = this.components.setMetrics(new DefaultMetrics(init.metrics))\n }\n\n this.peerStore = this.components.getPeerStore()\n\n this.peerStore.addEventListener('peer', evt => {\n const { detail: peerData } = evt\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peerData }))\n })\n\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.components.setConnectionProtector(init.connectionProtector)\n }\n\n // Set up the Upgrader\n this.components.setUpgrader(new DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map(component => this.configureComponent(component)),\n muxers: (init.streamMuxers ?? []).map(component => this.configureComponent(component)),\n inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout\n }))\n\n // Create the Connection Manager\n this.connectionManager = this.components.setConnectionManager(new DefaultConnectionManager(init.connectionManager))\n\n // Create the Registrar\n this.registrar = this.components.setRegistrar(new DefaultRegistrar(this.components))\n\n // Setup the transport manager\n this.components.setTransportManager(new DefaultTransportManager(this.components, init.transportManager))\n\n // Addresses {listen, announce, noAnnounce}\n this.components.setAddressManager(new DefaultAddressManager(this.components, init.addresses))\n\n // update our peer record when addresses change\n this.configureComponent(new PeerRecordUpdater(this.components))\n\n this.configureComponent(new AutoDialler(this.components, {\n enabled: init.connectionManager.autoDial,\n minConnections: init.connectionManager.minConnections,\n autoDialInterval: init.connectionManager.autoDialInterval\n }))\n\n // Create keychain\n const keychainOpts = KeyChain.generateOptions()\n this.keychain = this.configureComponent(new KeyChain(this.components, {\n ...keychainOpts,\n ...init.keychain\n }))\n\n // Create the Nat Manager\n this.services.push(new NatManager(this.components, init.nat))\n\n init.transports.forEach((transport) => {\n this.components.getTransportManager().add(this.configureComponent(transport))\n })\n\n // Attach stream multiplexers\n if (init.streamMuxers != null && init.streamMuxers.length > 0) {\n // Add the identify service since we can multiplex\n this.identifyService = new IdentifyService(this.components, {\n ...init.identify\n })\n this.configureComponent(this.identifyService)\n }\n\n // dht provided components (peerRouting, contentRouting, dht)\n if (init.dht != null) {\n this.dht = this.components.setDHT(init.dht)\n } else {\n this.dht = new DummyDHT()\n }\n\n // Create pubsub if provided\n if (init.pubsub != null) {\n this.pubsub = this.components.setPubSub(init.pubsub)\n } else {\n this.pubsub = new DummyPubSub()\n }\n\n // Attach remaining APIs\n // peer and content routing will automatically get modules from _modules and _dht\n\n const peerRouters: PeerRouting[] = (init.peerRouters ?? []).map(component => this.configureComponent(component))\n\n if (init.dht != null) {\n // add dht to routers\n peerRouters.push(this.configureComponent(new DHTPeerRouting(this.dht)))\n\n // use dht for peer discovery\n this.dht.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n\n this.peerRouting = this.components.setPeerRouting(this.configureComponent(new DefaultPeerRouting(this.components, {\n ...init.peerRouting,\n routers: peerRouters\n })))\n\n const contentRouters: ContentRouting[] = (init.contentRouters ?? []).map(component => this.configureComponent(component))\n\n if (init.dht != null) {\n // add dht to routers\n contentRouters.push(this.configureComponent(new DHTContentRouting(this.dht)))\n }\n\n this.contentRouting = this.components.setContentRouting(this.configureComponent(new CompoundContentRouting(this.components, {\n routers: contentRouters\n })))\n\n if (init.relay.enabled) {\n this.components.getTransportManager().add(this.configureComponent(new Circuit(init.relay)))\n\n this.configureComponent(new Relay(this.components, {\n addressSorter: init.connectionManager.addressSorter,\n ...init.relay\n }))\n }\n\n this.fetchService = this.configureComponent(new FetchService(this.components, {\n ...init.fetch\n }))\n\n this.pingService = this.configureComponent(new PingService(this.components, {\n ...init.ping\n }))\n\n const autoDialer = this.configureComponent(new AutoDialer(this.components, {\n enabled: init.connectionManager.autoDial !== false,\n minConnections: init.connectionManager.minConnections,\n dialTimeout: init.connectionManager.dialTimeout ?? 30000\n }))\n\n this.addEventListener('peer:discovery', evt => {\n if (!this.isStarted()) {\n return\n }\n\n autoDialer.handle(evt)\n })\n\n // Discovery modules\n for (const service of init.peerDiscovery ?? []) {\n this.configureComponent(service)\n\n service.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n }\n\n private configureComponent (component: T): T {\n if (isStartable(component)) {\n this.services.push(component)\n }\n\n if (isInitializable(component)) {\n this.initializables.push(component)\n }\n\n return component\n }\n\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start () {\n if (this.started) {\n return\n }\n\n this.started = true\n\n log('libp2p is starting')\n\n try {\n // Set available components on all modules interested in components\n this.initializables.forEach(obj => {\n obj.init(this.components)\n })\n\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStart != null) {\n await service.beforeStart()\n }\n })\n )\n\n // start any startables\n await Promise.all(\n this.services.map(service => service.start())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStart != null) {\n await service.afterStart()\n }\n })\n )\n\n log('libp2p has started')\n } catch (err: any) {\n log.error('An error occurred starting libp2p', err)\n await this.stop()\n throw err\n }\n }\n\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop () {\n if (!this.started) {\n return\n }\n\n log('libp2p is stopping')\n\n this.started = false\n\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStop != null) {\n await service.beforeStop()\n }\n })\n )\n\n await Promise.all(\n this.services.map(servce => servce.stop())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStop != null) {\n await service.afterStop()\n }\n })\n )\n\n log('libp2p has stopped')\n }\n\n isStarted () {\n return this.started\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n return this.components.getConnectionManager().getConnections(peerId)\n }\n\n getPeers (): PeerId[] {\n const peerSet = new PeerSet()\n\n for (const conn of this.components.getConnectionManager().getConnections()) {\n peerSet.add(conn.remotePeer)\n }\n\n return Array.from(peerSet)\n }\n\n async dial (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n\n return await this.components.getConnectionManager().openConnection(id, options)\n }\n\n async dialProtocol (peer: PeerId | Multiaddr, protocols: string | string[], options: AbortOptions = {}) {\n if (protocols == null) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n\n if (protocols.length === 0) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n const connection = await this.dial(peer, options)\n\n return await connection.newStream(protocols, options)\n }\n\n getMultiaddrs (): Multiaddr[] {\n return this.components.getAddressManager().getAddresses()\n }\n\n async hangUp (peer: PeerId | Multiaddr | string): Promise {\n const { id } = getPeer(peer)\n\n await this.components.getConnectionManager().closeConnections(id)\n }\n\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise {\n log('getPublicKey %p', peer)\n\n if (peer.publicKey != null) {\n return peer.publicKey\n }\n\n const peerInfo = await this.peerStore.get(peer)\n\n if (peerInfo.pubKey != null) {\n return peerInfo.pubKey\n }\n\n if (this.dht == null) {\n throw errCode(new Error('Public key was not in the peer store and the DHT is not enabled'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.multihash.digest\n ])\n\n // search the dht\n for await (const event of this.dht.get(peerKey, options)) {\n if (event.name === 'VALUE') {\n const key = unmarshalPublicKey(event.value)\n\n await this.peerStore.keyBook.set(peer, event.value)\n\n return key.bytes\n }\n }\n\n throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD)\n }\n\n async fetch (peer: PeerId | Multiaddr | string, key: string, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (multiaddrs != null) {\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n return await this.fetchService.fetch(id, key, options)\n }\n\n async ping (peer: PeerId | Multiaddr | string, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (multiaddrs.length > 0) {\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n return await this.pingService.ping(id, options)\n }\n\n async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.getRegistrar().handle(protocol, handler, options)\n })\n )\n }\n\n async unhandle (protocols: string[] | string): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.getRegistrar().unhandle(protocol)\n })\n )\n }\n\n /**\n * Called whenever peer discovery services emit `peer` events.\n * Known peers may be emitted.\n */\n onDiscoveryPeer (evt: CustomEvent) {\n const { detail: peer } = evt\n\n if (peer.id.toString() === this.peerId.toString()) {\n log.error(new Error(codes.ERR_DISCOVERED_SELF))\n return\n }\n\n if (peer.multiaddrs.length > 0) {\n void this.components.getPeerStore().addressBook.add(peer.id, peer.multiaddrs).catch(err => log.error(err))\n }\n\n if (peer.protocols.length > 0) {\n void this.components.getPeerStore().protoBook.set(peer.id, peer.protocols).catch(err => log.error(err))\n }\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peer }))\n }\n}\n\n/**\n * Returns a new Libp2pNode instance - this exposes more of the internals than the\n * libp2p interface and is useful for testing and debugging.\n */\nexport async function createLibp2pNode (options: Libp2pOptions): Promise {\n if (options.peerId == null) {\n options.peerId = await createEd25519PeerId()\n }\n\n return new Libp2pNode(validateConfig(options))\n}\n","/**\n * Return pseudo random subset of the input.\n */\nexport function getPseudoRandomSubset(\n values: T[],\n wantedNumber: number\n): T[] {\n if (values.length <= wantedNumber || values.length <= 1) {\n return values;\n }\n\n return shuffle(values).slice(0, wantedNumber);\n}\n\nfunction shuffle(arr: T[]): T[] {\n if (arr.length <= 1) {\n return arr;\n }\n const randInt = (): number => {\n return Math.floor(Math.random() * Math.floor(arr.length));\n };\n\n for (let i = 0; i < arr.length; i++) {\n const j = randInt();\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n return arr;\n}\n","import type {\n PeerDiscovery,\n PeerDiscoveryEvents,\n} from \"@libp2p/interface-peer-discovery\";\nimport { symbol } from \"@libp2p/interface-peer-discovery\";\nimport type { PeerInfo } from \"@libp2p/interface-peer-info\";\nimport { CustomEvent, EventEmitter } from \"@libp2p/interfaces/events\";\nimport { Multiaddr } from \"@multiformats/multiaddr\";\nimport debug from \"debug\";\n\nimport { multiaddrsToPeerInfo } from \"./multiaddr_to_peer_info\";\nimport { getPseudoRandomSubset } from \"./random_subset\";\n\nconst log = debug(\"waku:peer-discovery-static-list\");\n\nexport interface Options {\n /**\n * The maximum of peers to connect to as part of the bootstrap process.\n *\n * @default The length of the passed `peers` array.\n */\n maxPeers?: number;\n /**\n * The interval between emitting addresses in milliseconds.\n *\n * @default {@link PeerDiscoveryEvents.DefaultInterval}\n */\n interval?: number;\n}\n\n/**\n * Parse options and expose function to return bootstrap peer addresses.\n *\n * @throws if an invalid combination of options is passed, see [[BootstrapOptions]] for details.\n */\nexport class PeerDiscoveryStaticPeers\n extends EventEmitter\n implements PeerDiscovery\n{\n static DefaultInterval = 200;\n private readonly peers: PeerInfo[];\n private timer?: ReturnType;\n private readonly interval: number;\n\n /**\n * @param peers Multiaddrs of peers to connect to.\n * @param opts\n */\n constructor(peers: string[] | Multiaddr[], opts?: Options) {\n super();\n\n this.interval = opts?.interval ?? PeerDiscoveryStaticPeers.DefaultInterval;\n const maxPeers = opts?.maxPeers ?? peers?.length;\n\n const peerMas = peers.map((peer: string | Multiaddr) => {\n if (typeof peer === \"string\") {\n return new Multiaddr(peer);\n } else {\n return peer;\n }\n });\n this.peers = multiaddrsToPeerInfo(getPseudoRandomSubset(peerMas, maxPeers));\n log(\n \"Use provided list of peers (reduced to maxPeers)\",\n this.peers.map((ma) => ma.toString())\n );\n }\n\n /**\n * Start emitting static peers.\n */\n start(): void {\n this._startTimer();\n }\n\n private _startTimer(): void {\n if (this.peers) {\n log(\"Starting to emit static peers.\");\n if (this.timer != null) {\n return;\n }\n\n this.timer = setInterval(() => this._returnPeers(), this.interval);\n\n this._returnPeers();\n }\n }\n\n _returnPeers(): void {\n if (this.timer == null) {\n return;\n }\n\n this.peers.forEach((peerData) => {\n this.dispatchEvent(\n new CustomEvent(\"peer\", { detail: peerData })\n );\n });\n }\n\n /**\n * Stop emitting peers.\n */\n stop(): void {\n if (this.timer != null) {\n clearInterval(this.timer);\n }\n\n this.timer = undefined;\n }\n\n get [symbol](): true {\n return true;\n }\n\n get [Symbol.toStringTag](): string {\n return \"@waku/peer-discovery-static-list\";\n }\n}\n","import { PeerInfo } from \"@libp2p/interface-peer-info\";\nimport { peerIdFromString } from \"@libp2p/peer-id\";\nimport { Multiaddr } from \"@multiformats/multiaddr\";\n\nexport function multiaddrsToPeerInfo(mas: Multiaddr[]): PeerInfo[] {\n return mas\n .map((ma) => {\n const peerIdStr = ma.getPeerId();\n const protocols: string[] = [];\n return {\n id: peerIdStr ? peerIdFromString(peerIdStr) : null,\n multiaddrs: [ma.decapsulateCode(421)],\n protocols,\n };\n })\n .filter((peerInfo): peerInfo is PeerInfo => peerInfo.id !== null);\n}\n","import { Multiaddr } from \"@multiformats/multiaddr\";\n\nimport { getPseudoRandomSubset } from \"./random_subset\";\n\nexport const DefaultWantedNumber = 1;\n\nexport enum Fleet {\n Prod = \"prod\",\n Test = \"test\",\n}\n\n/**\n * Return list of pre-defined (hardcoded) bootstrap nodes.\n *\n * Default behavior is to return nodes of the nwaku Status Prod fleet.\n *\n * @param fleet The fleet to be returned. Defaults to production fleet.\n * @param wantedNumber The number of connections desired. Defaults to [[DefaultWantedNumber]].\n *\n * @returns An array of multiaddresses.\n */\nexport function getPredefinedBootstrapNodes(\n fleet: Fleet = Fleet.Prod,\n wantedNumber: number = DefaultWantedNumber\n): Multiaddr[] {\n if (wantedNumber <= 0) {\n return [];\n }\n\n let nodes;\n switch (fleet) {\n case Fleet.Prod:\n nodes = fleets.fleets[\"wakuv2.prod\"][\"waku-websocket\"];\n break;\n case Fleet.Test:\n nodes = fleets.fleets[\"wakuv2.test\"][\"waku-websocket\"];\n break;\n default:\n nodes = fleets.fleets[\"wakuv2.prod\"][\"waku-websocket\"];\n }\n\n nodes = Object.values(nodes) as string[];\n\n nodes = nodes.map((node: string) => new Multiaddr(node));\n return getPseudoRandomSubset(nodes, wantedNumber);\n}\n\nexport const fleets = {\n fleets: {\n \"wakuv2.prod\": {\n \"waku-websocket\": {\n \"node-01.ac-cn-hongkong-c.wakuv2.prod\":\n \"/dns4/node-01.ac-cn-hongkong-c.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAm4v86W3bmT1BiH6oSPzcsSr24iDQpSN5Qa992BCjjwgrD\",\n \"node-01.do-ams3.wakuv2.prod\":\n \"/dns4/node-01.do-ams3.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAmL5okWopX7NqZWBUKVqW8iUxCEmd5GMHLVPwCgzYzQv3e\",\n \"node-01.gc-us-central1-a.wakuv2.prod\":\n \"/dns4/node-01.gc-us-central1-a.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAmVkKntsECaYfefR1V2yCR79CegLATuTPE6B9TxgxBiiiA\",\n },\n },\n \"wakuv2.test\": {\n \"waku-websocket\": {\n \"node-01.ac-cn-hongkong-c.wakuv2.test\":\n \"/dns4/node-01.ac-cn-hongkong-c.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAkvWiyFsgRhuJEb9JfjYxEkoHLgnUQmr1N5mKWnYjxYRVm\",\n \"node-01.do-ams3.wakuv2.test\":\n \"/dns4/node-01.do-ams3.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAmPLe7Mzm8TsYUubgCAW1aJoeFScxrLj8ppHFivPo97bUZ\",\n \"node-01.gc-us-central1-a.wakuv2.test\":\n \"/dns4/node-01.gc-us-central1-a.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAmJb2e28qLXxT5kZxVUUoJt72EMzNGXB47Rxx5hw3q4YjS\",\n },\n },\n },\n};\n","import { Noise } from \"@chainsafe/libp2p-noise\";\nimport type { PeerDiscovery } from \"@libp2p/interface-peer-discovery\";\nimport { Mplex } from \"@libp2p/mplex\";\nimport { WebSockets } from \"@libp2p/websockets\";\nimport { all as filterAll } from \"@libp2p/websockets/filters\";\nimport { createLibp2p, Libp2pOptions } from \"libp2p\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { PeerDiscoveryStaticPeers } from \"./peer_discovery_static_list\";\nimport { getPredefinedBootstrapNodes } from \"./predefined_bootstrap_nodes\";\nimport { Waku, WakuOptions } from \"./waku\";\nimport { WakuFilter } from \"./waku_filter\";\nimport { WakuLightPush } from \"./waku_light_push\";\nimport { WakuRelay } from \"./waku_relay\";\nimport { WakuStore } from \"./waku_store\";\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use.\n *\n * One and only one pubsub topic is used by Waku. This is used by:\n * - WakuRelay to receive, route and send messages,\n * - WakuLightPush to send messages,\n * - WakuStore to retrieve messages.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link index.DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n /**\n * You can pass options to the `Libp2p` instance used by {@link index.waku.Waku} using the {@link CreateOptions.libp2p} property.\n * This property is the same type than the one passed to [`Libp2p.create`](https://github.com/libp2p/js-libp2p/blob/master/doc/API.md#create)\n * apart that we made the `modules` property optional and partial,\n * allowing its omission and letting Waku set good defaults.\n * Notes that some values are overridden by {@link index.waku.Waku} to ensure it implements the Waku protocol.\n */\n libp2p?: Partial;\n /**\n * Byte array used as key for the noise protocol used for connection encryption\n * by [`Libp2p.create`](https://github.com/libp2p/js-libp2p/blob/master/doc/API.md#create)\n * This is only used for test purposes to not run out of entropy during CI runs.\n */\n staticNoiseKey?: Uint8Array;\n /**\n * Use recommended bootstrap method to discovery and connect to new nodes.\n */\n defaultBootstrap?: boolean;\n}\n\nexport async function createWaku(\n options?: CreateOptions & WakuOptions\n): Promise {\n const libp2pOptions = options?.libp2p ?? {};\n const peerDiscovery = libp2pOptions.peerDiscovery ?? [];\n if (options?.defaultBootstrap) {\n peerDiscovery.push(defaultPeerDiscovery());\n Object.assign(libp2pOptions, { peerDiscovery });\n }\n\n const libp2p = await defaultLibp2p(new WakuRelay(options), libp2pOptions);\n\n const wakuStore = new WakuStore(libp2p, options);\n const wakuLightPush = new WakuLightPush(libp2p, options);\n const wakuFilter = new WakuFilter(libp2p, options);\n\n return new Waku(options ?? {}, libp2p, wakuStore, wakuLightPush, wakuFilter);\n}\n\nexport function defaultPeerDiscovery(): PeerDiscovery {\n return new PeerDiscoveryStaticPeers(getPredefinedBootstrapNodes());\n}\n\nexport async function defaultLibp2p(\n wakuRelay: WakuRelay,\n options?: Partial\n): Promise {\n const libp2pOpts = Object.assign(\n {\n transports: [new WebSockets({ filter: filterAll })],\n streamMuxers: [new Mplex()],\n connectionEncryption: [new Noise()],\n },\n { pubsub: wakuRelay },\n options ?? {}\n );\n\n return createLibp2p(libp2pOpts);\n}\n","import { createLibp2pNode } from './libp2p.js'\nimport type { AbortOptions, RecursivePartial } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { FaultTolerance } from './transport-manager.js'\nimport type { IdentifyServiceInit } from './identify/index.js'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { Datastore } from 'interface-datastore'\nimport type { PeerStore, PeerStoreInit } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AutoRelayConfig, RelayAdvertiseConfig } from './circuit/index.js'\nimport type { PeerDiscovery } from '@libp2p/interface-peer-discovery'\nimport type { Connection, ConnectionGater, ConnectionProtector, Stream } from '@libp2p/interface-connection'\nimport type { Transport } from '@libp2p/interface-transport'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { Metrics, MetricsInit } from '@libp2p/interface-metrics'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { KeyChain } from './keychain/index.js'\nimport type { ConnectionManagerInit } from './connection-manager/index.js'\nimport type { PingServiceInit } from './ping/index.js'\nimport type { FetchServiceInit } from './fetch/index.js'\n\nexport interface PersistentPeerStoreOptions {\n threshold?: number\n}\n\nexport interface DEKConfig {\n keyLength: number\n iterationCount: number\n salt: string\n hash: string\n}\n\nexport interface KeychainConfig {\n pass?: string\n dek?: DEKConfig\n}\n\nexport interface MetricsConfig {\n enabled?: boolean\n}\n\nexport interface HopConfig {\n enabled?: boolean\n active?: boolean\n timeout: number\n}\n\nexport interface RelayConfig {\n enabled: boolean\n advertise: RelayAdvertiseConfig\n hop: HopConfig\n autoRelay: AutoRelayConfig\n}\n\nexport interface NatManagerConfig {\n enabled: boolean\n externalAddress?: string\n localAddress?: string\n description?: string\n ttl?: number\n keepAlive: boolean\n gateway?: string\n}\n\nexport interface AddressesConfig {\n listen: string[]\n announce: string[]\n noAnnounce: string[]\n announceFilter: (multiaddrs: Multiaddr[]) => Multiaddr[]\n}\n\nexport interface TransportManagerConfig {\n faultTolerance?: FaultTolerance\n}\n\nexport interface PeerStoreConfig {\n persistence?: boolean\n threshold?: number\n}\n\nexport interface PeerRoutingConfig {\n refreshManager: RefreshManagerConfig\n}\n\nexport interface RefreshManagerConfig {\n enabled?: boolean\n interval: number\n bootDelay: number\n}\n\nexport interface Libp2pInit {\n peerId: PeerId\n addresses: AddressesConfig\n connectionManager: ConnectionManagerInit\n connectionGater: Partial\n transportManager: TransportManagerConfig\n datastore: Datastore\n metrics: MetricsInit\n peerStore: PeerStoreInit\n peerRouting: PeerRoutingConfig\n keychain: KeychainConfig\n nat: NatManagerConfig\n relay: RelayConfig\n identify: IdentifyServiceInit\n ping: PingServiceInit\n fetch: FetchServiceInit\n\n transports: Transport[]\n streamMuxers?: StreamMuxerFactory[]\n connectionEncryption?: ConnectionEncrypter[]\n peerDiscovery?: PeerDiscovery[]\n peerRouters?: PeerRouting[]\n contentRouters?: ContentRouting[]\n dht?: DualDHT\n pubsub?: PubSub\n connectionProtector?: ConnectionProtector\n}\n\nexport interface Libp2pEvents {\n 'peer:discovery': CustomEvent\n}\n\nexport interface Libp2p extends Startable, EventEmitter {\n peerId: PeerId\n peerStore: PeerStore\n peerRouting: PeerRouting\n contentRouting: ContentRouting\n keychain: KeyChain\n connectionManager: ConnectionManager\n registrar: Registrar\n metrics?: Metrics\n pubsub: PubSub\n dht: DualDHT\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n */\n getMultiaddrs: () => Multiaddr[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n */\n getConnections: (peerId?: PeerId) => Connection[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers: () => PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`\n */\n dial: (peer: PeerId | Multiaddr, options?: AbortOptions) => Promise\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n */\n dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise\n\n /**\n * Disconnects all connections to the given `peer`\n */\n hangUp: (peer: PeerId | Multiaddr | string) => Promise\n\n /**\n * Registers the `handler` for each protocol\n */\n handle: (protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n unhandle: (protocols: string[] | string) => Promise\n\n /**\n * Pings the given peer in order to obtain the operation latency\n */\n ping: (peer: Multiaddr | PeerId, options?: AbortOptions) => Promise\n\n /**\n * Sends a request to fetch the value associated with the given key from the given peer.\n */\n fetch: (peer: PeerId | Multiaddr | string, key: string, options?: AbortOptions) => Promise\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA' type\n * this may mean searching the DHT if the key is not present in the KeyStore.\n */\n getPublicKey: (peer: PeerId, options?: AbortOptions) => Promise\n}\n\nexport type Libp2pOptions = RecursivePartial\n\n/**\n * Returns a new instance of the Libp2p interface, generating a new PeerId\n * if one is not passed as part of the options.\n */\nexport async function createLibp2p (options: Libp2pOptions): Promise {\n return await createLibp2pNode(options)\n}\n","import { waitForRemotePeer, utils } from \"js-waku\";\nimport * as React from \"react\";\nimport protobuf from \"protobufjs\";\nimport { createWaku } from \"js-waku/lib/create_waku\";\n\nconst ContentTopic = \"/toy-chat/2/huilong/proto\";\n\nconst ProtoChatMessage = new protobuf.Type(\"ChatMessage\")\n .add(new protobuf.Field(\"timestamp\", 1, \"uint64\"))\n .add(new protobuf.Field(\"nick\", 2, \"string\"))\n .add(new protobuf.Field(\"text\", 3, \"bytes\"));\n\nfunction App() {\n const [waku, setWaku] = React.useState(undefined);\n const [wakuStatus, setWakuStatus] = React.useState(\"None\");\n const [messages, setMessages] = React.useState([]);\n\n React.useEffect(() => {\n if (wakuStatus !== \"None\") return;\n\n setWakuStatus(\"Starting\");\n\n createWaku({ defaultBootstrap: true }).then((waku) => {\n waku.start().then(() => {\n setWaku(waku);\n setWakuStatus(\"Connecting\");\n });\n });\n }, [waku, wakuStatus]);\n\n React.useEffect(() => {\n if (!waku) return;\n\n // We do not handle disconnection/re-connection in this example\n if (wakuStatus === \"Connected\") return;\n\n waitForRemotePeer(waku, [\"store\"]).then(() => {\n // We are now connected to a store node\n setWakuStatus(\"Connected\");\n });\n }, [waku, wakuStatus]);\n\n React.useEffect(() => {\n if (wakuStatus !== \"Connected\") return;\n\n const processMessages = (retrievedMessages) => {\n const messages = retrievedMessages.map(decodeMessage).filter(Boolean);\n\n setMessages((currentMessages) => {\n return currentMessages.concat(messages.reverse());\n });\n };\n\n const startTime = new Date();\n // 7 days/week, 24 hours/day, 60min/hour, 60secs/min, 100ms/sec\n startTime.setTime(startTime.getTime() - 7 * 24 * 60 * 60 * 1000);\n\n // TODO: Remove this timeout once https://github.com/status-im/js-waku/issues/913 is done\n setTimeout(\n () =>\n waku.store\n .queryHistory([ContentTopic], {\n callback: processMessages,\n timeFilter: { startTime, endTime: new Date() },\n })\n .catch((e) => {\n console.log(\"Failed to retrieve messages\", e);\n setWakuStatus(\"Error Encountered\");\n }),\n 200\n );\n }, [waku, wakuStatus]);\n\n return (\n
\n
\n

{wakuStatus}

\n

Messages

\n
    \n \n
\n
\n
\n );\n}\n\nexport default App;\n\nfunction decodeMessage(wakuMessage) {\n if (!wakuMessage.payload) return;\n\n const { timestamp, nick, text } = ProtoChatMessage.decode(\n wakuMessage.payload\n );\n\n if (!timestamp || !text || !nick) return;\n\n const time = new Date();\n time.setTime(Number(timestamp));\n\n const utf8Text = utils.bytesToUtf8(text);\n\n return {\n text: utf8Text,\n timestamp: time,\n nick,\n timestampInt: wakuMessage.timestamp,\n };\n}\n\nfunction Messages(props) {\n return props.messages.map(({ text, timestamp, nick, timestampInt }) => {\n return (\n
  • \n ({formatDate(timestamp)}) {nick}: {text}\n
  • \n );\n });\n}\n\nfunction formatDate(timestamp) {\n return timestamp.toLocaleString([], {\n month: \"short\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n}\n","import React from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport \"./index.css\";\nimport App from \"./App\";\n\nconst root = ReactDOM.createRoot(document.getElementById(\"root\"));\nroot.render(\n \n \n \n);\n"],"names":["module","exports","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","charAt","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","undefined","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","Object","keys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","fetch","asPromise","require","fs","inquire","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","Float32Array","f32","f8b","le","writeFloat_f32_cpy","val","buf","pos","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","writeFloat_ieee754","writeUint","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","moduleName","mod","eval","e","path","isAbsolute","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","call","utf8","len","read","write","c1","c2","writeUint16BE","out","writeUint16LE","readInt32BE","array","readUint32BE","readInt32LE","readUint32LE","writeUint32BE","writeUint32LE","writeUint64BE","writeUint64LE","bitLength","result","mul","int_1","div","DataView","byteOffset","byteLength","getFloat32","getFloat64","setFloat32","setFloat64","core","input","key","j0","j1","j2","j3","j4","j5","j6","j7","j8","j9","j10","j11","j12","j13","j14","j15","x0","x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13","x14","x15","binary_1","streamXOR","nonce","src","dst","nonceInplaceCounterLength","nc","counterLength","set","block","incrementCounter","wipe_1","counter","carry","ZEROS","nonceLength","tagLength","_key","ChaCha20Poly1305","plaintext","associatedData","authKey","chacha_1","resultLength","_authenticate","subarray","sealed","calculatedTag","constant_time_1","tagOut","ciphertext","h","poly1305_1","update","tag","digest","clean","compare","a","subject","resultIfOne","resultIfZero","saveState","restoreState","cleanSavedState","hash","salt","info","_counter","_hash","_info","okm","hmac_1","_hmac","_buffer","digestLength","_bufpos","HKDF","ctr","reset","finish","_fillBuffer","_finished","_inner","_outer","blockSize","pad","hash_1","_innerKeyedState","_outerKeyedState","HMAC","data","savedState","imul","al","bl","x","isInteger","isFinite","_r","Uint16Array","_h","_pad","_leftover","_fin","t0","t1","t2","t3","t4","t5","t6","t7","Poly1305","m","mpos","bytes","hibit","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","mac","macpos","mask","f","g","_blocks","want","randomBytes","prng","system_1","wipe","ALPHANUMERIC","randomString","charset","charsLen","maxByte","randomByte","bits","constructor","isAvailable","isInstantiated","browserCrypto","self","crypto","msCrypto","getRandomValues","_crypto","min","nodeCrypto","name","_source","browser_1","node_1","_state","Int32Array","_temp","_bufferLength","_bytesHashed","SHA256","_initState","dataLength","dataPos","hashBlocks","bytesHashed","left","bitLenHi","bitLenLo","padLength","state","bufferLength","K","w","v","d","u","gf","init","r","_9","_121665","car25519","o","sel25519","q","add","sub","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","square","scalarMult","z","unpack25519","x32","x16","inp","inv25519","pack25519","scalarMultBase","generateKeyPairFromSeed","seed","secretKey","publicKey","mySecretKey","theirPublicKey","rejectZero","zeros","anySignal","signals","controller","globalThis","AbortController","onAbort","abort","signal","removeEventListener","addEventListener","aborted","s","y","plural","ms","msAbs","isPlural","type","str","match","exec","parseFloat","toLowerCase","parse","long","abs","fmtLong","fmtShort","formatArgs","useColors","namespace","humanize","diff","color","lastC","save","namespaces","storage","setItem","removeItem","error","load","getItem","process","DEBUG","window","__nwjs","navigator","userAgent","document","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","RegExp","localStorage","localstorage","destroy","warned","warn","colors","debug","formatters","message","env","createDebug","prevTime","namespacesCache","enabledCache","enableOverride","enabled","curr","Date","prev","coerce","unshift","format","formatter","logFn","selectColor","extend","defineProperty","enumerable","configurable","get","delimiter","newDebug","toNamespace","regexp","substring","default","stack","disable","names","map","skips","enable","forEach","Denque","_head","_tail","_capacity","capacity","_capacityMask","_list","isArray","_fromArray","peekAt","peek","peekFront","peekBack","item","_growArray","pop","head","_shrinkArray","tail","removeOne","k","remove","count","removed","del_count","toArray","clear","temp","arg_len","arguments_index","leng","isEmpty","_copyArray","fullCopy","newArray","list","assign","obj","props","code","TypeError","_","ErrClass","create","getPrototypeOf","event_iterator_1","EventIterator","EventQueue","pullQueue","pushQueue","eventHandlers","isPaused","isStopped","resolution","done","placeholder","highWaterMark","highWater","stop","fail","rejection","catch","then","removeCallback","Symbol","asyncIterator","next","lowWaterMark","lowWater","return","listen","queue","event","freeze","has","hasOwnProperty","Events","EE","context","once","addListener","emitter","listener","_events","_eventsCount","clearEvent","__proto__","eventNames","events","getOwnPropertySymbols","concat","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","removeAllListeners","prefixed","ReflectOwnKeys","R","Reflect","ReflectApply","target","receiver","ownKeys","getOwnPropertyNames","NumberIsNaN","errorListener","resolver","eventTargetAgnosticAddListener","handler","flags","addErrorHandlerIfEventEmitter","_maxListeners","defaultMaxListeners","checkListener","_getMaxListeners","that","_addListener","prepend","existing","warning","newListener","onceWrapper","fired","wrapFn","_onceWrap","wrapped","unwrap","evlistener","arr","ret","unwrapListeners","arrayClone","copy","wrapListener","arg","RangeError","setMaxListeners","getMaxListeners","doError","er","prependListener","prependOnceListener","position","originalListener","spliceOne","rawListeners","hwm","top","btm","last","FixedFIFO","max","cache","_cache","word","includeBoundaries","v4","v6seg","v6","trim","v46Exact","v4exact","v6exact","ip","exact","root","ipv4Part","ipv4Regexes","fourOctet","threeOctet","twoOctet","longValue","octalRegex","hexRegex","zoneIndex","ipv6Part","ipv6Regexes","deprecatedTransitional","transitional","expandIPv6","indexOf","lastIndexOf","replacement","replacementCount","colonCount","lastColon","zoneId","substr","ref","results","matchCIDR","first","second","partSize","cidrBits","part","parseIntAuto","padPart","ipaddr","IPv4","octets","octet","SpecialRanges","unspecified","broadcast","multicast","linkLocal","loopback","carrierGradeNat","reserved","kind","other","cidrRange","prefixLengthFromSubnetMask","cidr","zerotable","range","subnetMatch","toByteArray","toIPv4MappedAddress","IPv6","toNormalizedString","broadcastAddressFromCIDR","parseCIDR","ipInterfaceOctets","subnetMaskOctets","subnetMaskFromPrefixLength","isIPv4","parser","isValid","isValidFourPartDecimal","networkAddressFromCIDR","maskLength","parsed","reverse","filledOctetCount","uniqueLocal","ipv4Mapped","rfc6145","rfc6052","teredo","isIPv4MappedAddress","toFixedLengthString","addr","suffix","toIPv4Address","high","low","toRFC5952String","regex","bestMatchIndex","bestMatchLength","isIPv6","native","fromByteArray","e2","address","rangeList","defaultName","rangeName","rangeSubnets","subnet","versions","electron","ipRegex","isIp","version","URLWithLegacySupport","URLSearchParams","defaultBase","relative","URL","url","urlParsed","location","protocolMap","defaultProtocol","protocol","base","host","isReactNative","product","super","pathname","search","auth","username","password","query","startsWith","hostname","href","origin","port","searchParams","createObjectURL","revokeObjectURL","toJSON","userPass","async","entry","thing","func","pushable","sources","output","setTimeout","all","FIFO","onEnd","onNext","ended","bufferNext","bufferError","writev","values","throw","_pushable","sorter","sort","limit","items","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","node","global","COMMON_JS","JS_SHA3_NO_COMMON_JS","AMD","define","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","ArrayBuffer","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","BITS","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","isView","createOutputMethod","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","methods","createKmacOutputMethod","createOutputMethods","method","createMethod","algorithms","bytepad","Kmac","methodNames","algorithm","methodName","newMethodName","blocks","finalized","blockCount","byteCount","outputBlocks","extraBytes","notString","lastByteIndex","right","encodeString","strs","paddingBytes","finalize","hex","arrayBuffer","Uint32Array","c0","c3","c4","c5","c6","c7","c8","c9","b16","b17","b18","b19","b20","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b40","b41","b42","b43","b44","b45","b46","b47","b48","b49","isOptionObject","propertyIsEnumerable","object","writable","defaultMergeOptions","concatArrays","ignoreUndefined","getEnumerableOwnPropertyKeys","symbols","symbol","clone","cloneArray","cloneOptionObject","mergeKeys","merged","config","merge","resultIndex","indices","filter","includes","option","_toConsumableArray","arr2","from","defaultTarget","mutableHandler","mutableTarget","setTarget","setHandler","Proxy","property","_len","getTarget","getHandler","proxy","Netmask","atob","chr","chr0","chrA","chra","ip2long","long2ip","dmax","net","maskLong","error1","bitmask","netLong","hostmask","contains","lastLong","forge","registerAlgorithm","mode","cipher","aes","Algorithm","startEncrypting","iv","_createCipher","decrypt","createEncryptionCipher","startDecrypting","createDecryptionCipher","initialize","encrypt","inBlock","outBlock","_updateBlock","_w","_init","tmp","util","createBuffer","putByte","getInt32","encryptOp","_expandKey","modes","ecb","cbc","cfb","ofb","gcm","sbox","isbox","rcon","mix","imix","xtime","e4","e8","sx","sx2","me","ime","ei","iNk","Nk","m0","m1","m2","m3","wnew","wi","Nr","toUpperCase","createDecipher","createCipher","ByteBuffer","asn1","_checkBufferLength","remaining","available","requested","Class","UNIVERSAL","APPLICATION","CONTEXT_SPECIFIC","PRIVATE","Type","NONE","BOOLEAN","INTEGER","BITSTRING","OCTETSTRING","NULL","OID","ODESC","EXTERNAL","REAL","ENUMERATED","EMBEDDED","UTF8","ROID","SEQUENCE","SET","PRINTABLESTRING","IA5STRING","UTCTIME","GENERALIZEDTIME","BMPSTRING","tagClass","constructed","composed","bitStringContents","original","excludeBitStringContents","equals","obj1","obj2","equal","includeBitStringContents","getBerValueLength","getByte","getInt","_fromDer","depth","longFormBytes","_getValueLength","strict","getBytes","decodeBitStrings","savedRead","savedRemaining","unused","used","tc","ex","getInt16","asn1Options","fromDer","parseAllBytes","toDer","useBitStringContents","putBytes","putBuffer","putInt16","lenBytes","oidToDer","oid","valueBytes","derToOid","utcTimeToDate","utc","date","year","MM","DD","hh","mm","ss","setUTCFullYear","setUTCHours","setTime","generalizedTimeToDate","gentime","YYYY","fff","isUTC","setFullYear","setHours","dateToUtcTime","rval","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","dateToGeneralizedTime","integerToDer","putSignedInt","integer","derToInteger","getSignedInt","validate","capture","errors","optional","captureAsn1","captureBitStringContents","captureBitStringValue","_nonLatinRegex","prettyPrint","level","indentation","indent","IA5String","subvalues","pki","oids","bytesToHex","decodeUtf8","api","_reverseAlphabets","alphabet","maxline","digits","at","_encodeWithByteBuffer","Buffer","getAlgorithm","BlockCipher","_finish","_input","_op","_decrypt","opts","compact","unpad","overflow","afterFinish","transformIV","ints","inc32","from64To32","num","_ints","_inBlock","_outBlock","putInt32","fillWithByte","truncate","_prev","_iv","_partialBlock","_partialOutput","_partialBytes","inputLength","partialBytes","_R","additionalData","_cipherLength","_tagLength","_tag","_hashBlock","_hashSubkey","componentBits","_m","generateHashTable","ivLength","_j0","ghash","_aDataLength","_s","lengths","multiply","z_i","v_i","lsb","tableMultiply","x_i","ah","multiplier","perInt","shft","generateSubHashTable","mid","half","m_i","m_j","des","_keys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","iterations","shifts","lefttmp","righttmp","_createKeys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","looping","endloop","loopinc","right1","right2","usePureJavaScript","hmac","_md","_ipadding","_opadding","md","keylen","blockLength","inner","getMac","dbits","jsbn","BigInteger","fromNumber","fromString","nbi","am3","xl","xh","am","appName","DB","DM","DV","FV","F1","F2","rr","vv","BI_RC","int2char","intAt","nbv","fromInt","nbits","Classic","Montgomery","mp","invDigit","mpl","mph","um","mt2","op_and","op_or","op_xor","op_andnot","lbit","cbit","NullExp","nNop","Barrett","q3","ONE","dlShiftTo","mu","divide","convert","compareTo","revert","reduce","divRemTo","mulTo","multiplyTo","sqrTo","squareTo","ZERO","subTo","copyTo","u0","clamp","drShiftTo","fromRadix","mi","sh","lShiftTo","bs","cbs","bm","ds","rShiftTo","pm","pt","ts","nsh","ys","y0","yt","qd","isEven","exp","negate","toRadix","km","modPowInt","multiplyUpperTo","multiplyLowerTo","dAddOffset","lowprimes","lplim","chunkSize","signum","cs","intValue","dMultiply","testBit","bitwiseTo","shiftLeft","isProbablePrime","nextBytes","op","changeBit","addTo","modInt","millerRabin","n1","subtract","getLowestSetBit","shiftRight","random","modPow","byteValue","shortValue","and","or","xor","andNot","not","bitCount","setBit","clearBit","flipBit","remainder","divideAndRemainder","k1","g2","is1","modInverse","ac","gcd","mgf","mgf1","generate","maskLen","_IN","id","_I_","pbe","encryptedPrivateKeyValidator","PBES2AlgorithmsValidator","pkcs12PbeParamsValidator","prfOidToMessageDigest","prfOid","prfAlgorithm","supported","prfAlgorithmToMessageDigest","sha512","encryptPrivateKeyInfo","saltSize","dkLen","encryptionAlgorithm","encryptedData","getBytesSync","countBytes","ivLen","encOid","cipherFn","dk","pkcs5","pbkdf2","hexToBytes","createPbkdf2Params","saltBytes","generatePkcs12Key","decryptPrivateKeyInfo","encryptionOid","getCipher","encryptionParams","encrypted","encryptedPrivateKeyToPem","epki","msg","pem","encryptedPrivateKeyFromPem","headerType","procType","encryptRsaPrivateKey","rsaKey","legacy","wrapRsaPrivateKey","privateKeyToAsn1","opensslDeriveBytes","dekInfo","parameters","decryptRsaPrivateKey","rc2","privateKeyFromAsn1","iter","sha1","passBuf","D","Slen","S","Plen","P","I","B","Inew","setAt","getCipherForPBES2","getCipherForPKCS12PBE","supportedOids","kdfOid","kdfSalt","kdfIterationCount","encIv","dIvLen","md5","digests","isNodejs","pbkdf2Sync","hLen","prf","u_c","u_c1","int32ToBytes","xorBytes","outer","setImmediate","foldHeader","header","insertSpace","candidate","insert","ltrim","contentDomain","headers","encode64","rMessage","rHeader","rCRLF","decode64","lines","li","line","nl","vi","pkcs1","rsa_mgf1","encode_rsa_oaep","label","mgf1Md","keyLength","maxLength","lHash","PS","PS_length","seedLength","dbMask","maskedDB","seedMask","maskedSeed","decode_rsa_oaep","em","expectedLength","db","lHashPrime","in_ps","is_0","error_mask","p7","pkcs7","_recipientFromAsn1","recipientInfoValidator","issuer","RDNAttributesAsArray","serialNumber","serial","toHex","encryptedContent","encAlgorithm","parameter","encParameter","content","encKey","_recipientsToAsn1","recipients","distinguishedNameToAsn1","attributes","_signerToAsn1","digestAlgorithm","authenticatedAttributesAsn1","signatureAlgorithm","signature","unauthenticatedAttributes","attrsAsn1","attr","_attributeToAsn1","contentType","messageDigest","signingTime","jan_1_1950","jan_1_2050","timestamp","_fromAsn1","validator","rawCapture","_decryptContent","ciph","messageFromPem","messageFromAsn1","messageToPem","pemObj","toAsn1","contentInfoValidator","envelopedData","createEnvelopedData","createEncryptedData","signedData","createSignedData","fromAsn1","certificates","crls","signers","digestAlgorithmIdentifiers","contentInfo","signerInfos","signedDataValidator","certs","certificateFromAsn1","certificateToAsn1","addSigner","signer","certificate","cert","certificateFromPem","privateKeyFromPem","sha256","sha384","authenticatedAttributes","rsaEncryption","encodeUtf8","detached","detachedContent","mds","ai","_signersToAsn1","addSignerInfos","addDigestAlgorithmIds","verify","addCertificate","addCertificateRevokationList","crl","encryptedDataValidator","envelopedDataValidator","infos","_recipientsFromAsn1","recipientInfos","ec","findRecipient","sAttr","rAttr","recipient","privKey","desCBC","addRecipient","keyLen","ciphFn","p7v","pkcs7asn1","encryptedContentInfoValidator","signerValidator","prime","GCD_30_DELTA","THIRTY","generateProbablePrime","rng","Worker","primeincFindPrimeWithoutWorkers","generateRandom","numWorkers","workers","workLoad","workerScript","estimateCores","cores","workerMessage","found","terminate","postMessage","primeincFindPrimeWithWorkers","primeincFindPrime","mrTests","getMillerRabinTests","millerRabinTests","maxBlockTime","_primeinc","deltaIdx","bits1","plugin","time","reseeds","generated","keyBytes","pools","_reseedSync","messageLength","_seed","needed","collect","seedFileSync","_2powK","seedBytes","formatKey","formatSeed","defaultSeedFile","globalScope","entropy","QuotaExceededError","pool","generateSync","increment","nextTick","seedFile","_reseed","collectInt","registerWorker","worker","pss","saltLength","sLen","salt_","pssobj","modBits","emBits","emLen","mHash","m_","ps","checkLen","jQuery","prng_aes","_prng_aes_output","_prng_aes_buffer","spawnPrng","_ctx","_navBytes","mousemove","clientX","clientY","keypress","charCode","createInstance","piTable","rol","ror","expandKey","effKeyBits","L","T","T1","T8","TM","mixRound","mashRound","_output","getInt16Le","runPlan","plan","putInt16Le","ptr","rsa","privateKeyValidator","rsaPrivateKeyValidator","rsaPublicKeyValidator","publicKeyValidator","digestInfoValidator","emsaPkcs1v15encode","oidBytes","digestInfo","_modPow","pub","dP","dQ","qInv","xp","xq","_encodePkcs1_v1_5","bt","eb","padByte","padNum","numZeros","padBytes","_decodePkcs1_v1_5","ml","_generateKeyPair","getPrime","pBits","qBits","p1","q1","phi","privateKey","setPrivateKey","setPublicKey","_bnToBytes","_getMillerRabinTests","_detectNodeCrypto","_detectSubtleCrypto","subtle","_detectSubtleMsCrypto","_intToUint8Array","yhex","ed","expected","xhex","createKeyPairGenerationState","eInt","pqState","stepKeyPairGenerationState","total","generateKeyPair","modulusLength","publicExponent","publicKeyEncoding","privateKeyEncoding","priv","publicKeyFromPem","generateKey","pair","exportKey","pkcs8","setRsaPublicKey","genOp","oncomplete","exportOp","onerror","keypair","generateKeyPairSync","scheme","schemeOptions","_parseAllDigestBytes","algorithmIdentifier","md2","sha224","setRsaPrivateKey","privateKeyModulus","privateKeyPublicExponent","privateKeyPrivateExponent","privateKeyPrime1","privateKeyPrime2","privateKeyExponent1","privateKeyExponent2","privateKeyCoefficient","privateKeyToRSAPrivateKey","publicKeyFromAsn1","publicKeyOid","rsaPublicKey","publicKeyModulus","publicKeyExponent","publicKeyToAsn1","publicKeyToSubjectPublicKeyInfo","publicKeyToRSAPublicKey","_initialized","_padding","fillString","fullMessageLength","messageLengthSize","messageLength64","int32s","encoding","_update","finalBlock","s2","_k","s0","maj","_states","messageLength128","hlen","t1_hi","t1_lo","t2_hi","t2_lo","s0_hi","s0_lo","s1_hi","ch_hi","maj_hi","maj_lo","a_hi","a_lo","b_hi","b_lo","c_hi","c_lo","d_hi","d_lo","e_hi","e_lo","f_hi","f_lo","g_hi","g_lo","h_hi","h_lo","w2","w7","w15","w16","baseN","_checkBitsParam","ByteStringBuffer","isArrayBuffer","isArrayBufferView","_constructedStringLength","browser","callbacks","stopPropagation","MutationObserver","now","createElement","observe","oldSetImmediate","setAttribute","_optimizeConstructedString","putString","putInt24","putInt24Le","putInt32Le","putInt","getInt24","getInt24Le","getInt32Le","DataBuffer","readOffset","growSize","writeOffset","accommodate","amount","setUint8","view","raw","text","utf16","setInt16","setInt8","setInt32","getInt8","getUint8","s1","s3","_base64","_base64Idx","_base58","chr1","chr2","chr3","enc1","enc2","enc3","enc4","unescape","encodeURIComponent","decodeURIComponent","escape","base58","deflate","inflate","_setStorageObject","_getStorageObject","_setItem","_getItem","_removeItem","empty","prop","_clearItems","_callStorageFunction","idx","clearItems","re","argi","lastIndex","formatNumber","number","decimals","dec_point","thousands_sep","toFixed","formatSize","bytesFromIP","bytesFromIPv4","bytesFromIPv6","blanks","bytesToIP","bytesToIPv4","bytesToIPv6","zeroGroups","zeroMaxGroup","group","hardwareConcurrency","Blob","blobUrl","st","et","sample","samples","avg","overlaps","overlap","_shortNames","x509CertificateValidator","rsassaPssParameterValidator","certificationRequestInfoValidator","certificationRequestValidator","_getAttribute","shortName","rdn","si","valueTagClass","CRIAttributesAsArray","seq","extensionRequest","extensions","certificateExtensionFromAsn1","_readSignatureParameters","fillDefaults","algorithmOid","hashOid","maskGenOid","maskGenHashOid","_createSignatureDigest","signatureOid","_verifySignature","sha1WithRSAEncryption","sha1WithRSASignature","signatureParameters","_dnToAsn1","attrs","_fillMissingFields","attribute","valueConstructed","certificateExtensionToAsn1","_fillMissingExtensionFields","extension","digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly","cA","pathLenConstraint","client","server","email","objsign","sslCA","emailCA","objCA","altNames","altName","comment","ski","generateSubjectKeyIdentifier","subjectKeyIdentifier","keyIdentifier","authorityCertIssuer","subSeq","fullNameGeneralNames","_signatureParametersToAsn1","_CRIAttributesToAsn1","csr","computeHash","certificateToPem","publicKeyToPem","publicKeyToRSAPublicKeyPem","getPublicKeyFingerprint","certificationRequestFromPem","certificationRequestFromAsn1","certificationRequestToPem","certificationRequestToAsn1","createCertificate","siginfo","validity","notBefore","notAfter","getField","sn","addField","setSubject","uniqueId","setIssuer","setExtensions","exts","getExtension","ext","tbsCertificate","getTBSCertificate","child","issued","expectedIssuer","actualIssuer","isIssuer","parent","iattr","sattr","verifySubjectKeyIdentifier","certVersion","certSerialNumber","certSignatureOid","certSignatureParams","certinfoSignatureOid","certinfoSignatureParams","certSignature","certValidity1UTCTime","certValidity2GeneralizedTime","certValidity3UTCTime","certValidity4GeneralizedTime","imd","ibytes","certIssuer","certIssuerUniqueId","smd","sbytes","certSubject","certSubjectUniqueId","certExtensions","certificateExtensionsFromAsn1","subjectPublicKeyInfo","extseq","critical","ev","gn","createCertificationRequest","csrVersion","csrSignatureOid","csrSignatureParams","csrSignature","certificationRequestInfo","certificationRequestInfoSubject","getAttribute","addAttribute","certificationRequestInfoAttributes","setAttributes","getCertificationRequestInfo","cri","_dateToAsn1","tbs","certificateExtensionsToAsn1","dn","createCaStore","caStore","getBySubject","ensureSubjectHasHash","getIssuer","hasCertificate","der1","listAllCertificates","certList","removeCertificate","certificateError","bad_certificate","unsupported_certificate","certificate_revoked","certificate_expired","certificate_unknown","unknown_ca","verifyCertificateChain","chain","validityCheckDate","selfSigned","parents","verified","se","keyUsage","basicConstraints","bcExt","keyUsageExt","vfd","Fifo","defer","_waitingConsumers","promise","_consume","nextConsumer","nextChunk","deferred","__importDefault","__esModule","netmask_1","ip_regex_1","is_ip_1","ipaddr_js_1","NETMASK_RANGES","ip_range","ipv6_check","ip_addr","ipv4_check","common","timeType","commonRe","json","nested","google","protobuf","Any","fields","type_url","Duration","seconds","nanos","Timestamp","Empty","Struct","keyType","Value","oneofs","oneof","nullValue","numberValue","stringValue","boolValue","structValue","listValue","NullValue","NULL_VALUE","ListValue","rule","DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue","FieldMask","paths","file","converter","Enum","genValuePartial_fromObject","gen","field","fieldIndex","resolvedType","typeDefault","repeated","fullName","isUnsigned","genValuePartial_toObject","fromObject","mtype","fieldsArray","safeProp","toObject","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","valuesById","unsigned","toNumber","arrayDefault","hasKs2","_fieldsArray","types","defaults","basic","packed","rfield","required","missing","wireType","mapKey","genTypePartial","ReflectionObject","className","Namespace","comments","valuesOptions","fromJSON","enm","toJSONOptions","keepComments","Boolean","isString","isReservedId","isReservedName","allow_alias","Field","ruleRe","isObject","defaultValue","Long","extensionField","declaringField","_packed","getOption","setOption","ifNotSet","resolved","lookupTypeOrEnum","proto3_optional","newBuffer","emptyObject","emptyArray","ctor","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","_configure","Type_","build","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","configure","Writer","BufferWriter","Reader","BufferReader","rpc","roots","tokenize","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","_nestedArray","clearCache","addJSON","nestedArray","nestedJson","getEnum","setOptions","onAdd","onRemove","resolveAll","lookup","filterTypes","parentAlreadyChecked","lookupEnum","lookupService","Service_","Enum_","defineProperties","_handleAdd","_handleRemove","setParsedOption","propName","opt","find","newValue","setProperty","newOpt","Root_","fieldNames","addFieldsToParent","oneofName","oneOfGetter","oneOfSetter","keepCase","base10Re","base10NegRe","base16Re","base16NegRe","base8Re","base8NegRe","numberRe","nameRe","typeRefRe","fqTypeRefRe","pkg","imports","weakImports","syntax","token","preferTrailingComment","tn","alternateCommentMode","skip","cmnt","isProto3","applyCase","camelCase","illegal","insideTryCatch","readString","readValue","acceptTypeRef","parseNumber","readRanges","acceptStrings","parseId","acceptNegative","parsePackage","parseImport","whichImports","parseSyntax","parseCommon","parseOption","parseType","parseEnum","service","ifBlock","commentText","parseMethod","parseService","reference","parseField","parseExtension","fnIf","fnElse","trailingLine","valueType","parseInlineOptions","parseMapField","parseOneOf","lcFirst","ucFirst","parseGroup","dummy","parseEnumValue","isCustom","parseOptionValue","objectResult","lastValue","prevValue","simpleValue","LongBits","indexOutOfRange","writeLength","create_array","isBuffer","readLongVarint","readFixed32_end","readFixed64","_slice","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","skipType","BufferReader_","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","files","SYNC","resolvePath","sync","cb","getBundledFileName","altname","queued","weak","readFileSync","isNode","exposeRe","tryHandleExtension","extendedType","sisterField","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","requestCtor","responseCtor","request","endedByRPC","_methodsArray","inherited","methodsArray","rpcService","isReserved","delimRe","stringDoubleRe","stringSingleRe","setCommentRe","setCommentAltRe","setCommentSplitRe","whitespaceRe","unescapeRe","unescapeMap","lastCommentLine","stringDelim","setComment","isLeading","lineEmpty","leading","commentOffset","isDoubleSlashCommentLine","startOffset","endOffset","findEndOfLine","lineText","cursor","repeat","isDoc","isLeadingComment","actual","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","wrapper","originalThis","fork","ldelim","typeName","bake","safePropBackslashRe","safePropQuoteRe","camelCaseRe","decorateRoot","decorateEnumIndex","setProp","zero","zzEncode","zeroHash","toLong","fromHash","toHash","part0","part1","part2","newError","CustomError","captureStackTrace","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","allocUnsafe","seenFirstField","invalid","genVerifyKey","genVerifyValue","oneofProp","Op","noop","State","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","BufferWriter_","writeStringBuffer","writeBytesBuffer","aa","ca","da","Set","ea","fa","ha","ia","ja","ka","la","ma","acceptsBooleans","attributeName","attributeNamespace","mustUseProperty","propertyName","sanitizeURL","removeEmptyString","ra","sa","ta","pa","qa","oa","removeAttribute","setAttributeNS","xlinkHref","ua","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","va","for","wa","ya","za","Aa","Ba","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","iterator","Ka","La","A","Ma","Na","Oa","prepareStackTrace","construct","displayName","Pa","render","Qa","$$typeof","_context","_payload","Ra","Sa","Ta","nodeName","Va","_valueTracker","getOwnPropertyDescriptor","getValue","setValue","stopTracking","Ua","Wa","checked","Xa","activeElement","Ya","defaultChecked","_wrapperState","initialChecked","Za","initialValue","controlled","ab","bb","ownerDocument","fb","selected","defaultSelected","disabled","gb","dangerouslySetInnerHTML","children","hb","ib","jb","textContent","kb","lb","mb","nb","namespaceURI","innerHTML","valueOf","firstChild","removeChild","appendChild","MSApp","execUnsafeLocalFunction","ob","lastChild","nodeType","nodeValue","pb","animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","qb","rb","sb","tb","menuitem","area","br","col","embed","hr","img","keygen","link","meta","param","track","wbr","ub","vb","is","wb","xb","srcElement","correspondingUseElement","parentNode","yb","zb","Ab","Bb","Cb","stateNode","Db","Eb","Fb","Gb","Hb","Ib","Jb","Kb","Lb","Mb","Nb","onError","Ob","Pb","Qb","Rb","Sb","Tb","Vb","alternate","Wb","memoizedState","dehydrated","Xb","Zb","sibling","current","Yb","$b","unstable_scheduleCallback","bc","unstable_cancelCallback","cc","unstable_shouldYield","dc","unstable_requestPaint","unstable_now","unstable_getCurrentPriorityLevel","fc","unstable_ImmediatePriority","gc","unstable_UserBlockingPriority","hc","unstable_NormalPriority","ic","unstable_LowPriority","jc","unstable_IdlePriority","kc","lc","oc","clz32","pc","qc","rc","sc","uc","pendingLanes","suspendedLanes","pingedLanes","entangledLanes","entanglements","vc","xc","yc","zc","Ac","eventTimes","Cc","C","Dc","Ec","Fc","Gc","Hc","Ic","Jc","Kc","Lc","Mc","Nc","Oc","Map","Pc","Qc","Rc","Sc","delete","pointerId","Tc","nativeEvent","blockedOn","domEventName","eventSystemFlags","targetContainers","Vc","Wc","priority","isDehydrated","containerInfo","Xc","Yc","dispatchEvent","Zc","$c","ad","bd","cd","ReactCurrentBatchConfig","dd","transition","fd","gd","hd","Uc","jd","kd","ld","nd","od","keyCode","pd","rd","_reactName","_targetInst","currentTarget","isDefaultPrevented","defaultPrevented","returnValue","isPropagationStopped","preventDefault","cancelBubble","persist","isPersistent","wd","xd","yd","sd","eventPhase","bubbles","cancelable","timeStamp","isTrusted","td","ud","detail","vd","Ad","screenX","screenY","pageX","pageY","ctrlKey","shiftKey","altKey","metaKey","getModifierState","zd","button","buttons","relatedTarget","fromElement","toElement","movementX","movementY","Bd","Dd","dataTransfer","Fd","Hd","animationName","elapsedTime","pseudoElement","Id","clipboardData","Jd","Ld","Md","Esc","Spacebar","Left","Up","Right","Down","Del","Win","Menu","Apps","Scroll","MozPrintableKey","Nd","Od","Alt","Control","Meta","Shift","Pd","Qd","locale","which","Rd","Td","width","height","pressure","tangentialPressure","tiltX","tiltY","twist","pointerType","isPrimary","Vd","touches","targetTouches","changedTouches","Xd","Yd","deltaX","wheelDeltaX","deltaY","wheelDeltaY","wheelDelta","deltaZ","deltaMode","Zd","$d","ae","be","documentMode","ce","de","fe","ge","he","ie","datetime","month","tel","week","ne","oe","pe","qe","te","ue","ve","we","xe","ye","ze","oninput","Ae","detachEvent","Be","Ce","attachEvent","De","Ee","Fe","He","Ie","Je","Ke","nextSibling","Le","compareDocumentPosition","Me","HTMLIFrameElement","contentWindow","Ne","contentEditable","Oe","focusedElem","selectionRange","selectionStart","selectionEnd","defaultView","getSelection","rangeCount","anchorNode","anchorOffset","focusNode","focusOffset","createRange","setStart","removeAllRanges","addRange","setEnd","element","scrollLeft","scrollTop","focus","Pe","Qe","Re","Se","Te","Ue","Ve","We","animationend","animationiteration","animationstart","transitionend","Xe","Ye","Ze","animation","$e","af","bf","cf","df","ef","ff","hf","lf","mf","nf","Ub","instance","of","pf","qf","rf","sf","passive","J","F","tf","uf","parentWindow","vf","wf","na","xa","$a","ba","je","char","ke","xf","yf","zf","Af","Bf","Cf","Df","Ef","__html","Ff","Gf","clearTimeout","Hf","Jf","queueMicrotask","If","Kf","Lf","Mf","previousSibling","Nf","Of","Pf","Qf","Rf","Sf","Tf","Uf","E","G","Vf","H","Wf","Xf","Yf","contextTypes","__reactInternalMemoizedUnmaskedChildContext","__reactInternalMemoizedMaskedChildContext","Zf","childContextTypes","$f","ag","bg","getChildContext","cg","__reactInternalMemoizedMergedChildContext","dg","eg","fg","gg","hg","jg","kg","lg","mg","ng","og","pg","qg","rg","sg","tg","ug","vg","wg","xg","yg","zg","Ag","Bg","elementType","deletions","Cg","pendingProps","treeContext","retryLane","Dg","Eg","Fg","Gg","memoizedProps","Hg","Ig","Jg","Kg","Lg","defaultProps","Mg","Ng","Og","Pg","Qg","Rg","_currentValue","Sg","childLanes","Tg","dependencies","firstContext","lanes","Ug","Vg","memoizedValue","Wg","Xg","Yg","interleaved","Zg","$g","updateQueue","baseState","firstBaseUpdate","lastBaseUpdate","shared","effects","bh","ch","eventTime","lane","payload","dh","eh","fh","gh","ih","jh","Component","refs","kh","nh","isMounted","_reactInternals","enqueueSetState","lh","mh","enqueueReplaceState","enqueueForceUpdate","oh","shouldComponentUpdate","isPureReactComponent","ph","contextType","updater","qh","componentWillReceiveProps","UNSAFE_componentWillReceiveProps","rh","getDerivedStateFromProps","getSnapshotBeforeUpdate","UNSAFE_componentWillMount","componentWillMount","componentDidMount","_owner","_stringRef","th","uh","vh","wh","yh","implementation","zh","Ah","Bh","Ch","Dh","Eh","Fh","Gh","Hh","Ih","tagName","Jh","Kh","Lh","M","Mh","revealOrder","Nh","Oh","_workInProgressVersionPrimary","Ph","ReactCurrentDispatcher","Qh","Rh","N","O","Sh","Th","Uh","Vh","Q","Wh","Xh","Yh","Zh","$h","bi","ci","baseQueue","di","fi","lastRenderedReducer","action","hasEagerState","eagerState","lastRenderedState","dispatch","gi","ii","ji","ki","getSnapshot","ni","lastEffect","stores","oi","pi","qi","ri","deps","ti","ui","xi","yi","zi","Ai","Bi","Ci","Di","Ei","Fi","Gi","Hi","Ii","Ji","readContext","useCallback","useContext","useEffect","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useReducer","useRef","useState","useDebugValue","useDeferredValue","useTransition","useMutableSource","useSyncExternalStore","useId","unstable_isNewReconciler","identifierPrefix","Ki","Li","Mi","Ni","WeakMap","Oi","Pi","Qi","Ri","getDerivedStateFromError","componentDidCatch","Si","componentStack","Ti","pingCache","Ui","Vi","Wi","Xi","ReactCurrentOwner","Yi","Zi","$i","aj","bj","cj","dj","ej","baseLanes","cachePool","transitions","fj","gj","hj","ij","jj","UNSAFE_componentWillUpdate","componentWillUpdate","componentDidUpdate","kj","lj","pendingContext","mj","Aj","Cj","Dj","nj","oj","pj","fallback","qj","rj","tj","dataset","dgst","uj","vj","_reactRetry","sj","subtreeFlags","wj","xj","isBackwards","rendering","renderingStartTime","tailMode","yj","Ej","Fj","Gj","wasMultiple","multiple","suppressHydrationWarning","onClick","onclick","createElementNS","autoFocus","createTextNode","Hj","Ij","Jj","Kj","U","Lj","WeakSet","V","Mj","W","Nj","Oj","Qj","Rj","Sj","Tj","Uj","Vj","Wj","insertBefore","_reactRootContainer","Xj","X","Yj","Zj","ak","onCommitFiberUnmount","componentWillUnmount","bk","ck","ek","fk","isHidden","gk","hk","display","ik","jk","kk","lk","__reactInternalSnapshotBeforeUpdate","Wk","mk","nk","ok","pk","Y","Z","qk","rk","sk","tk","uk","vk","wk","xk","yk","zk","Ak","Bk","Ck","Dk","Ek","callbackNode","expirationTimes","expiredLanes","wc","callbackPriority","ig","Fk","Gk","Hk","Ik","Jk","Kk","Lk","Mk","Ok","Pk","finishedWork","finishedLanes","Qk","timeoutHandle","Rk","Sk","Tk","Uk","Vk","mutableReadLanes","Bc","Pj","onCommitFiberRoot","mc","onRecoverableError","Xk","onPostCommitFiberRoot","Yk","Zk","isReactComponent","pendingChildren","mutableSourceEagerHydrationData","cl","pendingSuspenseBoundaries","dl","el","fl","gl","hl","il","jl","zj","$k","ll","reportError","_internalRoot","ol","pl","ql","sl","rl","unmount","unstable_scheduleHydration","querySelectorAll","form","tl","usingClientEntryPoint","ul","findFiberByHostInstance","bundleType","rendererPackageName","vl","rendererConfig","overrideHookState","overrideHookStateDeletePath","overrideHookStateRenamePath","overrideProps","overridePropsDeletePath","overridePropsRenamePath","setErrorHandler","setSuspenseHandler","scheduleUpdate","currentDispatcherRef","findHostInstanceByFiber","findHostInstancesForRefresh","scheduleRefresh","scheduleRoot","setRefreshHandler","getCurrentFiber","reconcilerVersion","__REACT_DEVTOOLS_GLOBAL_HOOK__","wl","isDisabled","supportsFiber","inject","createPortal","createRoot","unstable_strictMode","findDOMNode","flushSync","hydrate","hydrateRoot","hydratedSources","_getVersion","unmountComponentAtNode","unstable_batchedUpdates","unstable_renderSubtreeIntoContainer","checkDCE","__self","__source","jsx","jsxs","setState","forceUpdate","_status","_result","Children","only","Fragment","Profiler","PureComponent","StrictMode","Suspense","cloneElement","createContext","_currentValue2","_threadCount","Provider","Consumer","_defaultValue","_globalName","createFactory","createRef","forwardRef","isValidElement","lazy","memo","startTransition","unstable_act","Receptacle","toMS","_lookup","lastModified","ttl","expires","expire","record","refresh","oldRecord","timeout","getTime","Retimer","_started","_rescheduled","_scheduled","_args","_triggered","_timerWrapper","_schedule","_timer","reschedule","illegalRe","controlRe","reservedRe","windowsReservedRe","windowsTrailingRe","sanitize","sanitized","sortIndex","performance","startTime","expirationTime","priorityLevel","scheduling","isInputPending","MessageChannel","port2","port1","onmessage","unstable_Profiling","unstable_continueExecution","unstable_forceFrameRate","unstable_getFirstCallbackNode","unstable_next","unstable_pauseExecution","unstable_runWithPriority","delay","unstable_wrapCallback","intervals","setDelayedInterval","task","interval","_timeout","_runPeriodically","clearDelayedInterval","retimer","TimeoutController","_ms","setPrototypeOf","getLength","isHighSurrogate","codePoint","isLowSurrogate","segment","charLength","curByteLength","prevCodePoint","res","MAX_SAFE_INTEGER","oldOffset","INT","encodingLength","N1","N2","N3","N4","N5","N6","N7","N8","N9","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","getter","leafPrototypes","getProto","ns","def","definition","toStringTag","DefaultPubSubTopic","StoreCodecs","_0n","BigInt","_1n","_2n","_3n","_8n","POW_2_256","CURVE","Gx","Gy","beta","weistrass","USE_ENDOMORPHISM","JacobianPoint","Point","points","toInv","nums","scratch","lastMultiplied","acc","inverted","invert","reduceRight","invertBatch","toAffine","toAffineBatch","fromAffine","X1","Y1","Z1","X2","Y2","Z2","Z1Z1","Z2Z2","U1","U2","S1","S2","X3","Y3","Z3","HH","HHH","multiplyUnsafe","scalar","P0","normalizeScalar","k1neg","k2neg","k2","splitScalarEndo","k1p","k2p","precomputeWindow","windows","wNAF","affinePoint","BASE","_WINDOW_SIZE","precomputes","pointPrecomputes","normalizeZ","windowSize","maxNumber","shiftBy","wbits","pr","cached","point","fake","f1p","f2p","invZ","iz1","iz2","iz3","ax","ay","_setWindowSize","isShort","bytesToNumber","isValidFieldElement","_6n","_11n","_22n","_23n","_44n","_88n","pow2","b88","b176","b220","b223","sqrtMod","isYOdd","assertValidity","ensureBytes","fromCompressedHex","fromUncompressedHex","normalizePrivateKey","msgHash","recovery","truncateHash","normalizeSignature","fromHex","numTo32bStr","rinv","u1","u2","multiplyAndAddUnsafe","toRawBytes","isCompressed","toHexX","toRawX","aP","bQ","sum","sliceDER","parseDERInt","Signature","isUint8a","hexToNumber","sBytes","rBytesLeft","parseDERSignature","fromDER","isWithinCurveOrder","hasHighS","HALF","normalizeS","toDERRawBytes","toDERHex","sHex","numberToHexUnpadded","rHex","rLen","toCompactRawBytes","toCompactHex","concatBytes","arrays","every","hexes","padStart","uint8a","numTo32b","hexByte","byte","isSafeInteger","power","modulo","divNearest","POW_2_128","delta","HmacDrbg","fill","utils","hmacSha256","hmacSync","hmacSha256Sync","incr","reseedSync","kmdToSig","kBytes","sig","normalizePublicKey","fromCompact","getPublicKey","fromPrivateKey","isPub","bits2int","bits2octets","z1","z2","int2octets","initSigArgs","extraEntropy","seedArgs","finalizeSig","recSig","canonical","der","recovered","hashed","drbg","reseed","vopts","sinv","web","TAGGED_HASH_PREFIXES","isValidPrivateKey","privateAdd","tweak","privateNegate","pointAddScalar","pointMultiply","hashToPrivateKey","bytesLength","randomPrivateKey","messages","createHash","ckey","importKey","createHmac","sha256Sync","taggedHash","tagP","tagH","taggedHashSync","precompute","ALPHABET","BASE_MAP","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","it3","it4","vch","pbegin","pend","b58","it1","it2","Encoder","baseEncode","Decoder","baseDecode","codePointAt","prefixCodePoint","ComposedDecoder","decoders","Codec","baseX","basex","rfc4648","bitsPerChar","codes","written","SyntaxError","identity","TextDecoder","TextEncoder","base2","base8","base10","base16","base16upper","base32","base32upper","base32pad","base32padupper","base32hex","base32hexupper","base32hexpad","base32hexpadupper","base32z","base36","base36upper","base58btc","base58flickr","base64pad","base64url","base64urlpad","alphabetBytesToChars","alphabetCharsToBytes","base256emoji","byts","byt","encode_1","varint","encodeTo","int","sizeOffset","digestOffset","Digest","multihash","Hasher","sha","textEncoder","textDecoder","CID","asCID","_baseCache","hidden","readonly","toV0","DAG_PB_CODE","SHA_256_CODE","createV0","toV1","createV1","equalBytes","toStringV0","toStringV1","deprecate","IS_CID_DEPRECATION","cidSymbol","toBaseEncodedString","codec","multibaseName","encodeCID","cid","decodeFirst","specs","inspectBytes","prefixSize","multihashSize","multihashBytes","digestBytes","digestSize","multihashCode","initialBytes","parseCIDtoBytes","codeOffset","hashOffset","bases","identityBase","createCodec","ascii","latin1","bytesToUtf8","utf8ToBytes","byteArrays","totalLength","Symmetric","getSubtle","webcrypto","secp","keccak256","sha3","compressPublicKey","_permanentCensorErrors","_censorErrors","LogLevels","_logLevel","_globalLogger","_normalizeError","_checkNormalize","LogLevel","ErrorCode","HEX","Logger","_log","logLevel","throwArgumentError","levels","INFO","WARNING","makeError","UNKNOWN_ERROR","messageDetails","reason","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","condition","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","operation","checkSafeUint53","checkArgumentCount","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","checkAbstract","censorship","permanent","globalLogger","logger","isHexable","toHexString","addSlice","isBytesLike","isHexString","isBytes","arrayify","allowMissingPrefix","hexPad","HexCharacters","hexlify","arrayifyInteger","unarrayifyInteger","_encode","_decodeChildren","childOffset","decoded","_decode","consumed","BUFFER_OVERRUN","lengthLength","boundry","v6segment","functionTimeout","function_","wrappedFunction","isRegexp","flagMap","ignoreCase","multiline","dotAll","sticky","unicode","clonedRegexp","flag","isMatch","cloneRegexp","isIP","isV4","isV6","toBytes","sections","v4Buffer","uint8ArrayToString","argv","getProtocol","proto","row","resolvable","createProtocol","convertToString","ipBuff","ipString","getUint16","bytes2ip","bytes2port","bytes2str","bytes2mh","bytes2onion","bytes2mb","convertToBytes","ip2bytes","port2bytes","uint8ArrayFromString","uint8ArrayConcat","str2bytes","mh2bytes","portBuf","onion2bytes","onion32bytes","mbstr","anybaseDecoder","mb2bytes","setUint16","addrBytes","portBytes","ERR_INVALID_ID","decodeMessage","encodeMessage","lengthDelimited","CODEC_TYPES","KeyType","__KeyTypeValues","PublicKey","PrivateKey","enumeration","findValue","enumValue","_codec","Data","RSA","nativeCrypto","bigIntegerToUintBase64url","base64urlToBigInteger","base64urlToBuffer","aesGcm","deriveParams","rawKey","cryptoKey","deriveKey","errcode","unmarshalPrivateKey","derivePublicFromPrivate","jwKey","kty","convertKey","handle","fkey","jwk2pub","jwk2priv","exporter","ciphers","encryptedKey","RsaPublicKey","marshal","jwk","pbm","uint8ArrayEquals","RsaPrivateKey","_publicKey","genSecret","public","dp","dq","unmarshalRsaPrivateKey","alg","unmarshalRsaPublicKey","fromJwk","_255n","CURVE_ORDER","MAX_256B","SQRT_M1","SQRT_AD_MINUS_ONE","INVSQRT_A_MINUS_D","ONE_MINUS_D_SQ","D_MINUS_ONE_SQ","ExtendedPoint","assertExtPoint","X1Z2","X2Z1","Y1Z2","Y2Z1","T3","T2","isSmallOrder","isTorsionFree","fromRistrettoBytes","legacyRist","toRistrettoBytes","fromRistrettoHash","assertRstPoint","RistrettoPoint","ep","Ns","Ns_D_is_sq","uvRatio","s_","edIsNegative","Nt","W0","W1","W2","W3","bytes255ToNumberLE","R1","calcElligatorRistrettoMap","R2","emsg","numberTo32BytesLE","u1_2","u2_2","invertSqrt","Dx","Dy","invsqrt","D1","D2","zInv","_x","_y","one","two","normed","bytesToNumberLE","y2","isXOdd","getExtendedPublicKey","toX25519","u8","numberTo32BytesBE","pow_2_252_3","_5n","_10n","_20n","_40n","_80n","b80","b160","b240","b250","pow_p_5_8","v3","v7","vx2","root1","root2","useRoot1","useRoot2","noRoot","modlLE","adjustBytes25519","checkPrivateKey","getKeyFromHash","pointBytes","_sha512Sync","prepareVerification","SB","finishVerification","kA","TORSION_SUBGROUP","hashToPrivateScalar","sha512Sync","PRIVATE_KEY_BYTE_LENGTH","hashAndSign","privateKeyRaw","hashAndVerify","concatKeys","Ed25519PublicKey","ensureKey","Ed25519PrivateKey","unmarshalEd25519PrivateKey","privateKeyBytes","publicKeyBytes","unmarshalEd25519PublicKey","validatePublicKey","Secp256k1PublicKey","keysProtobuf","Secp256k1PrivateKey","unmarshalSecp256k1PrivateKey","unmarshalSecp256k1PublicKey","supportedKeys","ed25519","Ed25519","secp256k1","Secp256k1","unsupportedKey","typeToKey","unmarshalPublicKey","keysPBM","importer","isPeerId","baseDecoder","PeerIdImpl","toCID","peerIdFromString","RSAPeerIdImpl","Ed25519PeerIdImpl","Secp256k1PeerIdImpl","peerIdFromPeerId","peerIdFromBytes","peerIdFromCID","peerIdFromKeys","KeypairType","Secp256k1Keypair","_privateKey","privateKeyVerify","publicKeyVerify","hasPrivateKey","ERR_TYPE_NOT_IMPLEMENTED","createKeypair","tuplesToStringTuples","tuples","tup","protoFromTuple","tuplesToBytes","fromBytes","sizeForAddr","bytesToTuples","ParseError","bytesToString","cleanPath","stringTuplesToString","stringToBytes","stringToStringTuples","validateBytes","inspect","DNS_CODES","P2P_CODES","resolvers","Multiaddr","isMultiaddr","toOptions","protoCodes","transport","family","protos","protoNames","stringTuples","encapsulate","decapsulate","addrString","decapsulateCode","getPeerId","tuple","ipfs","peerIdStr","getPath","resolvableProto","errCode","nodeAddress","isThinWaistAddress","some","dbg","ENR","kvs","entries","enr","keypairType","peerId","createPeerIdFromKeypair","createKeypairFromPeerId","createV4","hexSeq","rlpEncodedBytes","RLP","encoded","decodeFromValues","RECORD_PREFIX","nodeId","pubKey","uncompressedPubkey","tcp","udp","ip6","tcp6","udp6","multiaddrs","multiaddrBytes","multiaddr","decodeMultiaddrs","multiaddrsBuf","dataView","encodeMultiaddrs","getLocationMultiaddr","isIpv6","endsWith","ipVal","isUdp","isTcp","protoName","protoVal","ipFamily","ipBytes","protocolBytes","multiaddrFromFields","setLocationMultiaddr","getFullMultiaddr","locationMultiaddr","getFullMultiaddrs","waku2","relay","store","lightPush","decodeWaku2","protocols","encodeWaku2","verifySignature","localeCompare","flat","encodeToValues","TimeoutError","AbortError","getDOMException","errorMessage","DOMException","getAbortedReason","pTimeout","milliseconds","timer","cancelablePromise","POSITIVE_INFINITY","customTimers","timeoutError","cancel","normalizeEmitter","pEvent","arrayPromise","rejectionEvents","multiArgs","resolveImmediately","onItem","arguments_","rejectHandler","rejectionEvent","pEventMultiple","findBufAndOffset","bufs","bufEnd","isUint8ArrayList","Uint8ArrayList","appendAll","append","consume","trunc","beginInclusive","endExclusive","_subList","bufStart","sliceEndsInBuf","bufInSlice","startIndex","endIndex","littleEndian","getBigInt64","setBigInt64","getUint32","setUint32","getBigUint64","setBigUint64","varintEncode","poolSize","minPoolSize","encodeLength","lengthEncoder","poolOffset","encodedLength","single","varintDecode","ReadModes","ReadHandlers","lengthDecoder","maxLengthLength","maxDataLength","onLength","onData","fromReader","varByteSource","splitLimit","calculateSize","getNext","objectMode","readableLength","rawPipe","fns","isIterable","isDuplex","sink","duplexPipelineFn","duplex","stream","sourceWrap","pipe","rest","selectRandomPeer","peers","getPeersForProtocol","libp2p","peerStore","peer","accessor","TWO_32","toBigInt","access","negative","signed","zigzag","strValue","LIMIT","fromBigInt","fieldDefs","encodeValue","fieldNumber","fieldDef","fieldNumberStr","repeats","fieldLength","valueLength","asBuf","strLen","WakuMessage","kdf","secret","outputLength","willBeResult","counters","countersSecret","willBeHashResult","hashResult","_hashResult","derive","privateKeyA","publicKeyB","px","privateA","publicB","publicKeyTo","ephemPrivateKey","sharedPx","encryptionKey","cipherText","ivCipherText","macKey","hmacSha256Sign","ephemPublicKey","cipherTextLength","cipherAndIv","msgMac","hmacSha256Verify","clearEncode","messagePayload","sigPrivKey","envelope","fieldSize","computeSizeOfPayloadSizeField","addPayloadSizeField","rawSize","paddingSize","expectedSize","findIndex","validateDataIntegrity","bytesSignature","recoveryId","clearDecode","sizeOfPayloadSizeField","getSizeOfPayloadSizeField","payloadSize","payloadSizeBytes","getPayloadSize","payloadStart","isSigned","isMessageSigned","getSignature","getHash","messageHash","_signature","fromSignature","ecRecoverPubKey","decryptAsymmetric","ecies","encryptSymmetric","clearText","symmetric","decryptSymmetric","ivStart","OneMillion","DecryptionMethod","_signaturePublicKey","contentTopic","encPublicKey","symKey","enc","version_1","timestampDeprecated","decryptionParams","protoBuf","decodeProto","signaturePublicKey","isDefined","dec","decodedResults","contentTopics","Asymmetric","payloadAsUtf8","rnds8","uuid","REGEX","byteToHex","rnds","FilterRequest","MessagePush","FilterRPC","ContentFilter","topic","contentFilters","requestId","subscribe","FilterCodec","WakuFilter","subscriptions","decryptionKeys","pubSubTopic","onRequest","pubsubTopic","createRequest","getPeer","newStream","lp","addCallback","unsubscribe","streamData","pushMessages","unsubscribeRequest","connections","connectionManager","getConnections","randomPeer","addDecryptionKey","deleteDecryptionKey","PushRequest","PushResponse","PushRPC","LightPushCodec","WakuLightPush","RelayCodecs","Index","PagingInfo","HistoryQuery","HistoryResponse","HistoryRPC","Direction","__DirectionValues","__ErrorValues","PageDirection","storeCodec","historyRpc","protoV2Beta3","protoV2Beta4","direction","pageDirection","BACKWARD","FORWARD","directionToProto","pagingInfo","pageSize","endTime","WakuStore","timeFilter","queryOpts","historyRpcQuery","createQuery","remoteAddr","reply","ERROR_NONE_UNSPECIFIED","pageMessages","protoMsg","responsePageSize","queryPageSize","codecs","Protocols","Waku","pubsub","pingKeepAliveTimers","relayKeepAliveTimers","pingKeepAlive","relayKeepAlive","startKeepAlive","remotePeer","stopKeepAlive","_protocols","Relay","Store","LightPush","Filter","dialProtocol","addPeerToAddressBook","addresses","addressBook","stopAllKeepAlives","isStarted","getLocalMultiaddrWithID","localMultiaddr","getMultiaddrs","pingPeriodSecs","relayPeriodSecs","setInterval","ping","wakuMsg","clearInterval","waitForRemotePeer","waku","timeoutMs","promises","getMeshPeers","waitForGossipSubPeerInMesh","waitForConnectedPeer","rejectReason","race","awaitTimeout","rejectOnTimeout","_resolve","Envelope","RecordEnvelope","payloadType","marshaled","Protobuf","uint8arraysEquals","domain","signData","formatSignaturePayload","envelopeData","createFromProtobuf","domainUint8Array","uint8arraysFromString","domainLength","payloadTypeLength","payloadLength","uint8arraysConcat","PeerRecord","AddressInfo","ENVELOPE_PAYLOAD_TYPE_PEER_RECORD","DOMAIN","CODEC","seqNumber","arrayEquals","trace","peerRecord","topologySymbol","TopologyImpl","onConnect","onDisconnect","registrar","disconnect","EventTarget","_EventEmitter_listeners","__classPrivateFieldGet","CustomEventPolyfill","Event","CustomEvent","MessageCache","gossip","historyCapacity","msgIdToStrFn","history","msgs","put","messageId","validated","msgIdStr","originatingPeers","iwantCounts","observeDuplicate","msgId","fromPeerIdStr","getWithIWantCount","getGossipIDs","topics","msgIdsByTopic","msgIds","RPC","cjs","FloodsubID","GossipsubIDv10","GossipsubIDv11","GossipsubMaxIHaveLength","createGossipRpc","control","graft","prune","ihave","iwant","shuffle","messageIdToString","StrictSign","StrictNoSign","SignaturePolicy","PublishConfigType","MessageAcceptance","RejectReason","ValidateError","MessageStatus","rejectReasonFromAcceptance","acceptance","Ignore","Reject","ERR_INVALID_PEER_SCORE_PARAMS","defaultPeerScoreParams","topicScoreCap","appSpecificScore","appSpecificWeight","IPColocationFactorWeight","IPColocationFactorThreshold","IPColocationFactorWhitelist","behaviourPenaltyWeight","behaviourPenaltyThreshold","behaviourPenaltyDecay","decayInterval","decayToZero","retainScore","defaultTopicScoreParams","topicWeight","timeInMeshWeight","timeInMeshQuantum","timeInMeshCap","firstMessageDeliveriesWeight","firstMessageDeliveriesDecay","firstMessageDeliveriesCap","meshMessageDeliveriesWeight","meshMessageDeliveriesDecay","meshMessageDeliveriesCap","meshMessageDeliveriesThreshold","meshMessageDeliveriesWindow","meshMessageDeliveriesActivation","meshFailurePenaltyWeight","meshFailurePenaltyDecay","invalidMessageDeliveriesWeight","invalidMessageDeliveriesDecay","createPeerScoreParams","topicScoreParams","createTopicScoreParams","validateTopicScoreParams","defaultPeerScoreThresholds","gossipThreshold","publishThreshold","graylistThreshold","acceptPXThreshold","opportunisticGraftThreshold","createPeerScoreThresholds","computeScore","pstats","peerIPs","score","tstats","topicParams","topicScore","inMesh","meshTime","p2","firstMessageDeliveries","meshMessageDeliveriesActive","meshMessageDeliveries","deficit","meshFailurePenalty","invalidMessageDeliveries","p5","ips","peersInIP","numPeersInIP","surplus","behaviourPenalty","excess","DeliveryRecordStatus","MessageDeliveries","records","ensureRecord","drec","unknown","firstSeen","isStartable","isInitializable","Components","started","setPeerId","addressManager","setAddressManager","setPeerStore","upgrader","setUpgrader","metrics","setMetrics","setRegistrar","setConnectionManager","transportManager","setTransportManager","connectionGater","setConnectionGater","contentRouting","setContentRouting","peerRouting","setPeerRouting","datastore","setDatastore","connectionProtector","setConnectionProtector","dht","setDHT","setPubSub","startable","beforeStart","afterStart","beforeStop","afterStop","getMetrics","getAddressManager","getPeerStore","getUpgrader","getRegistrar","getConnectionManager","getTransportManager","getConnectionGater","getContentRouting","getPeerRouting","getDatastore","getConnectionProtector","getDHT","getPubSub","PeerScore","validatePeerScoreParams","scoreCacheValidityMs","components","peerStats","_backgroundInterval","background","deliveryRecords","refreshScores","updateIPs","dumpPeerScoreStats","fromEntries","stats","connected","tparams","graftTime","removeIPs","scoreCache","scoreFnCalls","inc","cacheEntry","cacheUntil","scoreFnRuns","scoreCachedDelta","addPenalty","penalty","penaltyLabel","onScorePenalty","addPeer","getIPs","setIPs","removePeer","threshold","getPtopicStats","validateMessage","deliverMessage","markFirstMessageDelivery","markDuplicateMessageDelivery","rejectInvalidMessage","markInvalidMessageDelivery","rejectMessage","duplicateMessage","cap","validatedTime","deliveryDelayMs","isLateDelivery","onDuplicateMsgDelivery","newIPs","oldIPs","addNewIPs","xip","removeOldIPs","topicStats","IWantTracer","gossipsubIWantFollowupMs","requestMsByMsgExpire","requestMsByMsgSize","requestMsByMsg","addPromise","expireByPeer","iwantPromiseStarted","getBrokenPromises","brokenPromises","iwantPromiseBroken","trackMessage","iwantPromiseResolved","iwantPromiseResolvedPeers","maxMs","requestMs","iwantPromiseDeliveryTime","SimpleTimeCache","validityMs","validUntilMs","MessageSource","InclusionReason","ChurnReason","ScorePenalty","IHaveIgnoreReason","ScoreThreshold","hashName","keySize","dek","forgePbkdf2","forgeUtil","SignPrefix","msgIdFnStrictSign","sequenceNumber","seqno","seqnoBytes","msgIdFnStrictNoSign","computeScoreWeights","topicStrToLabel","byTopic","topicLabel","topicScores","p1w","p2w","p3w","p3bw","p4w","capF","ws","p5w","p6w","p7w","removeItemsFromSet","superSet","ineed","cond","subset","abortableSource","getIterator","nextAbortHandler","abortHandler","abortMessage","abortCode","isKnownAborter","onReturnError","returnOnAbort","abortable","abortableSink","abortableDuplex","prependAll","sublist","sliceStartInBuf","defaultEncoder","lengthBuf","ReadMode","defaultDecoder","LENGTH","dataLengthLength","DATA","OutboundStream","rawStream","errCallback","closeController","stat","close","InboundStream","GossipStatusCode","GossipSub","constants","stopped","heartbeatDuration","startTimer","heartbeat","finally","heartbeatTimeout","msToNextHeartbeat","hearbeatStartMs","heartbeatInterval","heartbeatSkipped","runHeartbeat","fallbackToFloodsub","floodPublish","doPX","directPeers","Dlo","Dhi","Dscore","Dout","Dlazy","fanoutTTL","minute","mcacheLength","mcacheGossip","seenTTL","prunePeers","pruneBackoff","graftFloodThreshold","opportunisticGraftPeers","opportunisticGraftTicks","directConnectTicks","scoreParams","scoreThresholds","globalSignaturePolicy","multicodecs","debugName","direct","seenCache","publishedMessageIds","msgIdFn","fastMsgIdFn","fastMsgIdCache","mcache","messageCache","dataTransform","metricsRegister","metricsTopicStrToLabel","maxMeshMessageDeliveriesWindowMs","topicParam","register","protocolsEnabled","gauge","help","labelNames","topicSubscriptionStatus","topicPeersCount","meshPeerCounts","meshPeerInclusionEvents","meshPeerChurnEvents","peersPerProtocol","histogram","buckets","asyncValidationResult","asyncValidationMcacheHit","rpcRecvBytes","rpcRecvCount","rpcRecvSubscription","rpcRecvMessage","rpcRecvControl","rpcRecvIHave","rpcRecvIWant","rpcRecvGraft","rpcRecvPrune","rpcRecvNotAccepted","rpcSentBytes","rpcSentCount","rpcSentSubscription","rpcSentMessage","rpcSentControl","rpcSentIHave","rpcSentIWant","rpcSentGraft","rpcSentPrune","msgPublishCount","msgPublishPeers","msgPublishPeersByGroup","msgPublishBytes","msgForwardCount","msgForwardPeers","msgReceivedPreValidation","msgReceivedStatus","msgReceivedInvalid","duplicateMsgDeliveryDelay","maxMeshMessageDeliveriesWindowSec","duplicateMsgLateDelivery","peersByScoreThreshold","avgMinMax","scoreWeights","scorePerMesh","scoringPenalties","ihaveRcvIgnored","ihaveRcvMsgids","ihaveRcvNotSeenMsgids","iwantRcvMsgids","iwantRcvDonthaveMsgids","gossipPromiseExpireSec","cacheSize","mcacheSize","toTopic","topicStr","onJoin","onLeave","onAddToMesh","onRemoveFromMesh","onReportValidationMcacheHit","hit","onReportValidation","onIhaveRcv","idonthave","onIwantRcv","iwantByTopic","iwantDonthave","onForwardMsg","tosendCount","onPublishMsg","tosendGroupCount","dataLen","peerGroup","floodsub","mesh","fanout","onMsgRecvPreValidation","onMsgRecvResult","onMsgRecvInvalid","onRpcRecv","rpcBytes","onRpcSent","registerScores","scores","graylist","publish","registerScoreWeights","sw","wsTopic","registerScorePerMesh","scoreByPeer","peersPerTopicLabel","peersInMesh","meshScores","addCollect","onScrapeMetrics","gossipTracer","maxInboundStreams","maxOutboundStreams","getPeers","publishConfig","signaturePolicy","author","getPublishConfigFromPeerId","outboundInflightQueue","connection","createOutboundStream","addrs","multicodec","onIncomingStream","topology","onPeerConnected","onPeerDisconnected","registrarTopologyIds","directPeerInitial","connect","unregister","outboundStream","streamsOutbound","inboundStream","streamsInbound","heartbeatTimer","fanoutLastpub","peerhave","iasked","backoff","outbound","createInboundStream","floodsubPeers","sendSubscriptions","priorInboundStream","pipePeerReadStream","acceptFromWhitelist","peersInTopic","getSubscribers","getTopics","awaitRpcHandler","handleReceivedRpc","acceptFrom","subOpt","handleReceivedSubscription","handleReceivedMessagePromise","handleReceivedMessage","awaitRpcMessageHandler","handleControlMessage","topicSet","rpcMsg","validationResult","validateReceivedMessage","asyncValidation","emitSelf","propagationSource","forwardMessage","fastMsgIdStr","msgIdCached","valid","fromPeerId","rpcMsgPreSign","validateToRawMessage","transformedData","inboundTransform","topicValidator","topicValidators","getScore","toPeer","sendRpc","controlMsg","handleIHave","handleIWant","handleGraft","handlePrune","messagesAccepted","acceptUntil","topicID","messageIDs","iask","iwantList","floodCutoff","addBackoff","makePrune","doAddBackoff","pxConnect","applyIwantPenalties","clearBackoff","heartbeatTicks","toconnect","peerID","signedPeerRecord","eid","consumePeerRecord","openConnection","getTopologies","wasSubscribed","leave","toAdd","fanoutPeers","fanoutCount","getRandomGossipPeers","sendGraft","meshPeers","sendPrune","selectPeersToForward","excludePeers","tosend","selectPeersToPublish","newFanoutPeers","rawMsg","outboundTransform","buildRawMessage","willSendToSelf","allowPublishToZeroPeers","reportMessageValidationResult","ctrl","piggybackControl","piggybackGossip","outRpc","tograft","toprune","noPX","pruning","emitGossip","peersToGossipByTopic","gossipIDsByTopic","peersToGossip","doEmitGossip","candidateToGossip","factor","peerMessageIDs","pushGossip","flush","controlIHaveMsgs","xid","getRawEnvelope","directConnect","candidateMeshPeers","shuffledPeers","peerStreams","prunePeer","graftPeer","newMeshPeers","removeFirstNItemsFromSet","peersArray","rotate","peersList","medianIndex","medianScore","lastpb","topicPeers","candidateFanoutPeers","sendGraftPrune","backoffSize","peerIdStrs","swPeer","swPeerTopic","swTopic","computeAllPeersScoreWeights","WakuRelay","observers","addObserver","deleteObserver","callbackFn","pDefer","handshake","sourcePromise","sinkErr","sinkPromise","pbStream","shake","lpReader","readLP","readPB","writeLP","writePB","piped","NOISE_MSG_MAX_LENGTH_BYTES","DUMP_SESSION_KEYS","stablelib","hashSHA256","getHKDF","ikm","expand","generateX25519KeyPair","x25519","generateX25519KeyPairFromSeed","generateX25519SharedKey","chaCha20Poly1305Encrypt","seal","chaCha20Poly1305Decrypt","uint16BEEncode","uint16BEDecode","encode0","encode1","decode0","decode1","NoiseHandshakePayload","NoiseHandshakePayloadProto","getPayload","localPeer","staticPublicKey","earlyData","signedPayload","signPayload","getHandshakePayload","earlyDataPayload","libp2pPublicKey","identityKey","identitySig","createHandshakePayload","getPeerIdFromPayload","decodePayload","verifySignedPayload","noiseStaticKey","payloadPeerId","generatedPayload","isValidPublicKey","keyLogger","logLocalStaticKeys","logLocalEphemeralKeys","logRemoteStaticKey","rs","logRemoteEphemeralKey","logCipherState","session","cs1","cs2","getUint64","Nonce","assertValue","AbstractHandshake","encryptWithAd","decryptWithAd","hasKey","isEmptyKey","createEmptyKey","encryptAndHash","mixHash","encryptedMessage","decryptAndHash","derivedU8","mixKey","tempK","initializeKey","initializeSymmetric","protocolName","protocolNameBytes","hashProtocolName","tempk1","tempk2","writeMessageRegular","readMessageRegular","IK","initSession","initiator","prologue","psk","hs","initializeInitiator","initializeResponder","sendMessage","messageBuffer","writeMessageA","writeMessageB","recvMessage","readMessageA","readMessageB","spk","valid1","valid2","FailedIKError","initialMsg","IKHandshake","isInitiator","staticKeypair","remoteStaticKey","remoteEarlyData","receivedMsg","receivedMessageBuffer","decodedPayload","setRemoteEarlyData","getCS","getLocalEphemeralKeys","encryption","UnexpectedPeerError","InvalidCryptoExchangeError","InvalidCryptoTransmissionError","XX","writeMessageC","readMessageC","ephemeral","resultingBuffer","resultingPlaintext","resultingValid","XXHandshake","xx","encode2","decode2","getRemoteStaticKey","XXFallbackHandshake","ephemeralKeys","exchange","mapIterable","PeerMap","PeerSet","predicate","PeerList","peerIds","KeyCache","resetStorage","Noise","staticNoiseKey","useNoisePipes","staticKeys","wrappedConnection","performHandshake","conn","createSecureConnection","tryIK","performXXHandshake","ikHandshake","performIKHandshake","performXXFallbackHandshake","propose","stage0","stage1","secure","user","duplexPair","network","encryptStream","decrypted","decryptStream","MessageTypes","MessageTypeNames","InitiatorMessageTypes","NEW_STREAM","MESSAGE","MESSAGE_INITIATOR","CLOSE","CLOSE_INITIATOR","RESET","RESET_INITIATOR","ReceiverMessageTypes","MESSAGE_RECEIVER","CLOSE_RECEIVER","RESET_RECEIVER","POOL_SIZE","_pool","_poolOffset","_headerInfo","_decodeHeader","readVarInt","REST","MAX_MSG_SIZE","ERR_STREAM_RESET","TrackedMap","system","component","metric","updateComponentMetric","deleted","trackedMap","printMessage","MplexStreamMuxer","_streamId","_streams","initiators","receivers","_createSink","_createSource","streams","registry","_newStream","_newReceiverStream","maxMsgSize","abortController","resetController","Types","externalId","streamName","endErr","sourceEnded","sinkEnded","sinkSunk","timeline","onSinkEnd","closeRead","closeWrite","uint8ArrayList","toSend","metadata","createStream","onStreamEnd","abortSignals","maxSize","checkSize","restrictSize","_handleIncoming","pushableV","maxBufferSize","maxStreamBufferSize","Mplex","createStreamMuxer","socket","cleanup","handleOpen","handleErr","closeOnEnd","ready","wasClean","connectedSource","binaryType","isConnected","connError","cleanUp","cont","onOpen","onMessage","remoteAddress","remotePort","CONNECTING","OPEN","http","https","wsurl","WebSocket","websocket","reduceValue","Reducers","ip4","assumeHttp","explicitPort","tcpUri","dnsaddr","dns4","dns6","p2p","wss","isEnvWithDom","isElectron","detectElectron","isBrowser","isElectronMain","isElectronRenderer","release","isWebWorker","importScripts","WorkerGlobalScope","socketToMaConn","maConn","DNS4","DNS6","DNSADDR","DNS","IP","TCP","UDP","UTP","QUIC","WebSockets","WebSocketsSecure","HTTP","HTTPS","WebRTCStar","WebRTCDirect","Reliable","_P2P","_Circuit","CircuitRecursive","Circuit","makeMatchesFunction","partialMatch","matches","pnames","testMa","mafmt","_connect","upgradeOutbound","cOpts","errorPromise","errfn","rawSocket","toUri","createListener","filters","sortAll","iterable","pathSepS","pathSepB","pathSep","Key","_buf","uint8Array","nanoid","less","list1","list2","withNamespaces","baseNamespace","namespaceType","namespaceValue","isAncestorOf","isDecendantOf","isTopLevel","MemoryDatastore","batch","puts","dels","commit","drain","putMany","deleteMany","it","_all","orders","take","queryKeys","_allKeys","storeAddresses","uniquePeers","seen","requirePeers","DefaultPeerRouting","routers","refreshManagerInit","refreshManager","_findClosestPeersTask","timeoutId","bootDelay","getClosestPeers","router","findPeer","NOT_FOUND","CompoundContentRouting","findProviders","provide","NOT_STARTED_YET","nVals","gotValues","idStr","peerIdFromMultiaddr","defaultAddressFilter","DefaultAddressManager","announce","observed","announceFilter","getListenAddrs","getAnnounceAddrs","getObservedAddrs","addObservedAddr","getAddresses","getAddrs","addrSet","VisibilityChangeEmitter","visibilityChange","_initializeVisibilityVarNames","_addVisibilityChangeListener","mozHidden","msHidden","webkitHidden","_handleVisibilityChange","isVisible","visible","LatencyMonitor","latencyCheckIntervalMs","dataEmitIntervalMs","asyncTestFn","latencyRandomPercentage","latencyCheckMultiply","latencyCheckSubtract","hrtime","getDeltaMS","latencyData","initLatencyData","visibilityChangeEmitter","pageInFocus","_startTimers","_emitSummary","_stopTimers","checkLatencyID","checkLatency","emitIntervalID","unref","summary","getSummary","latency","minMs","avgMs","totalMs","lengthMs","randomness","localData","deltaOffset","deltaMS","NEGATIVE_INFINITY","CLOSING","CLOSED","DialRequest","dialAction","dialer","tokens","getTokens","tokenHolder","dialAbortControllers","completedDials","any","releaseToken","isPrivate","isIpPrivate","publicAddressesFirst","isAPrivate","isBPrivate","isCertified","METRICS","METRICS_COMPONENT","Dialer","addressSorter","maxAddrsToDial","dialTimeout","maxDialsPerPeer","maxParallelDials","pendingDials","pendingDialTargets","dial","pendingTarget","denyDialPeer","dialTarget","_createCancellableDialTarget","pendingDial","_createPendingDial","cancellablePromise","_createDialTarget","knownAddrs","denyDialMultiaddr","supportedAddrs","transportForMultiaddr","dialRequest","timeoutController","run","resolvedMultiaddrs","_resolveRecord","nm","newM","defaultOptions","maxConnections","minConnections","maxData","maxSentData","maxReceivedData","maxEventLoopDelay","pollInterval","autoDialInterval","movingAverageInterval","METRICS_SYSTEM","DefaultConnectionManager","mergeOptions","_checkMetrics","latencyMonitor","startupReconnectTimeout","inbound","conns","allStreams","counts","_onLatencyMeasure","keepAlivePeers","getTags","connectOnStartupController","_close","tasks","connectionList","movingAverages","getGlobal","getMovingAverages","received","dataReceived","movingAverage","_checkMaxLimit","sent","dataSent","_onConnect","storedConns","keyBook","numConnections","toPrune","storedConn","existingConnections","peerConnections","trackedConnection","getAll","STATUS","_maybePruneConnections","peerValues","tags","sortedConnections","peerAValue","peerBValue","toClose","AutoDialler","running","_autoDial","autoDialTimeout","allPeers","CircuitRelay","Status","__StatusValues","__TypeValues","Peer","srcPeer","dstPeer","streamToMaConnection","mapSource","RELAY_CODEC","writeResponse","streamHandler","validateAddrs","HOP","HOP_DST_MULTIADDR_INVALID","STOP_DST_MULTIADDR_INVALID","HOP_SRC_MULTIADDR_INVALID","STOP_SRC_MULTIADDR_INVALID","StreamHandler","handleHop","hopRequest","circuit","hopEnabled","CircuitPB","destinationPeer","destinationConnections","hopActive","stopRequest","destinationStream","sourceStream","_onProtocol","hop","virtualConnection","canHop","handleCanHop","handleStop","localAddr","upgradeInbound","relayAddr","destinationAddr","relayId","destinationId","errMsg","relayPeer","disconnectOnFailure","relayConnection","Errors","listeningAddrs","relayPeerStr","relayPeerId","relayConn","relayedAddr","namespaceToCid","HOP_METADATA_KEY","HOP_METADATA_VALUE","RELAY_RENDEZVOUS_NS","AutoRelay","maxListeners","listenRelays","_onProtocolChange","_onPeerDisconnected","supportsHop","metadataBook","_addListenRelay","_removeListenRelay","remoteAddrs","_listenOnAvailableHopRelays","peersToIgnore","knownHopsToDial","_tryToListenOnRelay","provider","autoRelay","_advertiseService","advertise","privates","CMS","keychain","plain","findKeyByName","getPrivateKey","getFullYear","serverAuth","clientAuth","codeSigning","emailProtection","timeStamping","certificateForKey","cmsData","cms","keyId","asyncCompare","findAsync","findKeyById","missingKeys","infoPrefix","NIST","iterationCount","validateKeyName","randomDelay","DsName","DsInfoName","KeyChain","pass","dsname","importPeer","keyInfo","kid","export","listKeys","oldName","newName","oldDsname","newDsname","oldInfoName","newInfoName","oldPass","newPass","oldDek","newDek","keyAsPEM","DefaultMovingAverage","timespan","variance","deviation","forecast","alpha","previousTime","sqrt","createMovingAverage","DefaultStats","frequencyLastTime","frequencyAccumulators","computeThrottleMaxQueueSize","computeThrottleTimeout","movingAverageIntervals","initialCounters","_resetComputeTimeout","_nextTimeout","urgency","_applyOp","_updateFrequency","latestTime","timeDiff","_updateFrequencyFor","timeDiffMS","hz","directionToEvent","in","DefaultMetrics","statsInit","globalStats","protocolStats","oldPeers","LRU","maxOldPeersRetention","_onMessage","systems","getComponentMetrics","systemMetrics","componentMetrics","calculate","forPeer","idString","getProtocols","forProtocol","updatePlaceholder","placeholderString","placeholderStats","peerIdString","existingStats","mergedStats","trackStream","each","pReflect","isFulfilled","isRejected","_classPrivateFieldInitSpec","privateMap","privateCollection","_classExtractFieldDescriptor","_classPrivateFieldSet","descriptor","_classPrivateFieldGet","_defineProperty","Node","Queue","enqueue","dequeue","pLimit","concurrency","activeCount","generator","pendingCount","clearQueue","pSettle","DefaultTransportManager","transports","faultTolerance","FaultTolerance","FATAL_ALL","getTransports","couldNotListen","NO_FATAL","PROTOCOL_ID","NewLine","writeAll","buffers","select","shakeStream","multistream","ConnectionImpl","getStreams","_getStreams","_closing","addStream","removeStream","DefaultRegistrar","topologies","_onDisconnect","protoBook","protocolList","peerProtocols","oldProtocols","added","findOutgoingStreamLimit","countStreams","streamCount","DefaultUpgrader","connectionEncryption","encrypter","muxers","muxer","inboundUpgradeTimeout","encryptedConn","upgradedConn","muxerFactory","cryptoProtocol","setPeer","proxyPeer","abortableStream","denyInboundConnection","mutableProxy","protectedConn","protector","protect","_encryptInbound","denyInboundEncryptedConnection","multiplexed","_multiplexInbound","denyInboundUpgradedConnection","_createConnection","remotePeerId","denyOutboundConnection","toB58String","_encryptOutbound","denyOutboundEncryptedConnection","_multiplexOutbound","denyOutboundUpgradedConnection","muxedStream","mss","incomingLimit","findIncomingStreamLimit","_onStream","outgoingLimit","_timeline","upgraded","errConnectionNotMultiplexed","multiplexer","secureInbound","secureOutbound","Identify","protocolVersion","agentVersion","listenAddrs","observedAddr","AGENT_VERSION","IdentifyService","identifyProtocolStr","protocolPrefix","identifyPushProtocolStr","identify","pushToPeerStore","_handleIdentify","_handlePush","maxPushIncomingStreams","maxPushOutgoingStreams","unhandle","pushes","maxIdentifyMessageSize","_identify","cleanObservedAddr","getCleanMultiaddr","peerData","peerRecordEnvelope","FetchRequest","FetchResponse","identifier","StatusCode","__StatusCodeValues","FetchService","lookupFunctions","handleMessage","OK","ERROR","errmsg","_getLookupFunction","registerLookupFunction","unregisterLookupFunction","PingService","isLoopback","DEFAULT_TTL","highPort","NatManager","externalAddress","localAddress","description","keepAlive","gateway","_start","_getClient","publicIp","externalIp","isPrivateIp","publicPort","localPort","fromNodeAddress","upnpNat","PeerRecordUpdater","DHTPeerRouting","closer","EVENT_NAME","allowAll","PeerStoreAddressBook","addressFilter","lock","writeLock","updatedPeer","storedEnvelope","storedRecord","filterMultiaddrs","patchOrCreate","oldMultiaddrs","readLock","hasPeer","mergeOrCreate","PeerStoreKeyBook","updatedKey","uint8arrayEquals","oldPublicKey","PeerStoreMetadataBook","oldMetadata","existingValue","patch","PeerStoreProtoBook","protocolSet","Address","Metadata","_PriorityQueue_queue","PriorityQueue","comparator","step","lowerBound","_PQueue_instances","_PQueue_carryoverConcurrencyCount","_PQueue_isIntervalIgnored","_PQueue_intervalCount","_PQueue_intervalCap","_PQueue_interval","_PQueue_intervalEnd","_PQueue_intervalId","_PQueue_timeoutId","_PQueue_queue","_PQueue_queueClass","_PQueue_pendingCount","_PQueue_concurrency","_PQueue_isPaused","_PQueue_throwOnTimeout","_PQueue_doesIntervalAllowAnother_get","_PQueue_doesConcurrentAllowAnother_get","_PQueue_next","_PQueue_emitEvents","_PQueue_onResumeInterval","_PQueue_isIntervalPaused_get","_PQueue_tryToStartAnother","_PQueue_initializeIntervalIfNeeded","_PQueue_onInterval","_PQueue_processQueue","_PQueue_onEvent","__classPrivateFieldSet","PQueue","_a","_b","_c","_d","carryoverConcurrencyCount","intervalCap","autoStart","queueClass","throwOnTimeout","newConcurrency","functions","pause","sizeBy","canInitializeInterval","job","WORKER_REQUEST_READ_LOCK","WORKER_RELEASE_READ_LOCK","MASTER_GRANT_READ_LOCK","WORKER_REQUEST_WRITE_LOCK","WORKER_RELEASE_WRITE_LOCK","MASTER_GRANT_WRITE_LOCK","observable","handleWorkerLockRequest","masterEvent","releaseType","grantType","requestEvent","MessageEvent","releaseEventListener","releaseEvent","makeWorkerLockRequest","responseEvent","singleProcess","mutexes","createReleaseable","createMortice","observer","isWorker","impl","masterQueue","readQueue","localReadQueue","readPromise","onIdle","createMutex","NAMESPACE_COMMON","PersistentStore","mortice","_peerIdToDatastoreKey","b32key","PeerPB","addressSet","_patch","_merge","addrStr","base32Str","Tags","Tag","expiry","PersistentPeerStore","providedValue","unexpiredTags","DHTContentRouting","providers","AutoDialer","globalFetch","globalHeaders","Headers","Request","Response","buildResource","serverResolver","recordType","resource","req","nativeFetch","accept","getCacheKey","maxCache","_TXTcache","_servers","_request","_abortControllers","getServers","_getShuffledServers","newServers","setServers","servers","rrType","resolve4","resolve6","resolveTxt","Answer","TTL","dnsaddrCode","DefaultConfig","noAnnounce","autoDial","Resolver","nat","active","PeerIdProto","createFromPrivKey","marshalPublicKey","marshalPrivateKey","DummyDHT","wan","DHT_DISABLED","lan","DummyPubSub","PUBSUB_DISABLED","Libp2pNode","initializables","filterMultiaddrForPeer","services","configureComponent","streamMuxers","keychainOpts","generateOptions","identifyService","peerRouters","onDiscoveryPeer","contentRouters","fetchService","pingService","autoDialer","peerDiscovery","servce","peerSet","closeConnections","peerInfo","peerKey","createLibp2pNode","createEd25519PeerId","resultingOptions","ERR_TRANSPORTS_REQUIRED","CONN_ENCRYPTION_REQUIRED","LIBP2P_FORCE_PNET","ERR_PROTECTOR_REQUIRED","validateConfig","getPseudoRandomSubset","wantedNumber","randInt","PeerDiscoveryStaticPeers","DefaultInterval","maxPeers","peerMas","_startTimer","_returnPeers","Fleet","fleets","createWaku","libp2pOptions","defaultBootstrap","nodes","fleet","Prod","Test","getPredefinedBootstrapNodes","wakuRelay","createLibp2p","filterAll","defaultLibp2p","wakuStore","wakuLightPush","wakuFilter","ProtoChatMessage","setWaku","React","wakuStatus","setWakuStatus","setMessages","processMessages","retrievedMessages","currentMessages","queryHistory","Messages","wakuMessage","nick","timestampInt","formatDate","toLocaleString","day","hour","hour12","ReactDOM","getElementById"],"sourceRoot":""} \ No newline at end of file diff --git a/store-reactjs-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs b/store-reactjs-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs new file mode 100644 index 0000000..6e40160 --- /dev/null +++ b/store-reactjs-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs @@ -0,0 +1 @@ +"use strict";!function(e,t){"function"===typeof define&&define.amd?define(["protobufjs/minimal"],t):"function"===typeof require&&"object"===typeof module&&module&&module.exports&&(module.exports=t(require("protobufjs/minimal")))}(0,(function(e){var t=e.Reader,r=e.Writer,o=e.util,n=e.roots.default||(e.roots.default={});return n.RPC=function(){function s(e){if(this.subscriptions=[],this.messages=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:s.subscriptions&&s.subscriptions.length||(s.subscriptions=[]),s.subscriptions.push(n.RPC.SubOpts.decode(e,e.uint32()));break;case 2:s.messages&&s.messages.length||(s.messages=[]),s.messages.push(n.RPC.Message.decode(e,e.uint32()));break;case 3:s.control=n.RPC.ControlMessage.decode(e,e.uint32());break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC)return e;var t=new n.RPC;if(e.subscriptions){if(!Array.isArray(e.subscriptions))throw TypeError(".RPC.subscriptions: array expected");t.subscriptions=[];for(var r=0;r>>3){case 1:s.subscribe=e.bool();break;case 2:s.topic=e.string();break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.SubOpts)return e;var t=new n.RPC.SubOpts;return null!=e.subscribe&&(t.subscribe=Boolean(e.subscribe)),null!=e.topic&&(t.topic=String(e.topic)),t},s.toObject=function(e,t){t||(t={});var r={};return null!=e.subscribe&&e.hasOwnProperty("subscribe")&&(r.subscribe=e.subscribe,t.oneofs&&(r._subscribe="subscribe")),null!=e.topic&&e.hasOwnProperty("topic")&&(r.topic=e.topic,t.oneofs&&(r._topic="topic")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s.Message=function(){function s(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:a.from=e.bytes();break;case 2:a.data=e.bytes();break;case 3:a.seqno=e.bytes();break;case 4:a.topic=e.string();break;case 5:a.signature=e.bytes();break;case 6:a.key=e.bytes();break;default:e.skipType(7&i)}}if(!a.hasOwnProperty("topic"))throw o.ProtocolError("missing required 'topic'",{instance:a});return a},s.fromObject=function(e){if(e instanceof n.RPC.Message)return e;var t=new n.RPC.Message;return null!=e.from&&("string"===typeof e.from?o.base64.decode(e.from,t.from=o.newBuffer(o.base64.length(e.from)),0):e.from.length&&(t.from=e.from)),null!=e.data&&("string"===typeof e.data?o.base64.decode(e.data,t.data=o.newBuffer(o.base64.length(e.data)),0):e.data.length&&(t.data=e.data)),null!=e.seqno&&("string"===typeof e.seqno?o.base64.decode(e.seqno,t.seqno=o.newBuffer(o.base64.length(e.seqno)),0):e.seqno.length&&(t.seqno=e.seqno)),null!=e.topic&&(t.topic=String(e.topic)),null!=e.signature&&("string"===typeof e.signature?o.base64.decode(e.signature,t.signature=o.newBuffer(o.base64.length(e.signature)),0):e.signature.length&&(t.signature=e.signature)),null!=e.key&&("string"===typeof e.key?o.base64.decode(e.key,t.key=o.newBuffer(o.base64.length(e.key)),0):e.key.length&&(t.key=e.key)),t},s.toObject=function(e,t){t||(t={});var r={};return t.defaults&&(r.topic=""),null!=e.from&&e.hasOwnProperty("from")&&(r.from=t.bytes===String?o.base64.encode(e.from,0,e.from.length):t.bytes===Array?Array.prototype.slice.call(e.from):e.from,t.oneofs&&(r._from="from")),null!=e.data&&e.hasOwnProperty("data")&&(r.data=t.bytes===String?o.base64.encode(e.data,0,e.data.length):t.bytes===Array?Array.prototype.slice.call(e.data):e.data,t.oneofs&&(r._data="data")),null!=e.seqno&&e.hasOwnProperty("seqno")&&(r.seqno=t.bytes===String?o.base64.encode(e.seqno,0,e.seqno.length):t.bytes===Array?Array.prototype.slice.call(e.seqno):e.seqno,t.oneofs&&(r._seqno="seqno")),null!=e.topic&&e.hasOwnProperty("topic")&&(r.topic=e.topic),null!=e.signature&&e.hasOwnProperty("signature")&&(r.signature=t.bytes===String?o.base64.encode(e.signature,0,e.signature.length):t.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,t.oneofs&&(r._signature="signature")),null!=e.key&&e.hasOwnProperty("key")&&(r.key=t.bytes===String?o.base64.encode(e.key,0,e.key.length):t.bytes===Array?Array.prototype.slice.call(e.key):e.key,t.oneofs&&(r._key="key")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s.ControlMessage=function(){function s(e){if(this.ihave=[],this.iwant=[],this.graft=[],this.prune=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:s.ihave&&s.ihave.length||(s.ihave=[]),s.ihave.push(n.RPC.ControlIHave.decode(e,e.uint32()));break;case 2:s.iwant&&s.iwant.length||(s.iwant=[]),s.iwant.push(n.RPC.ControlIWant.decode(e,e.uint32()));break;case 3:s.graft&&s.graft.length||(s.graft=[]),s.graft.push(n.RPC.ControlGraft.decode(e,e.uint32()));break;case 4:s.prune&&s.prune.length||(s.prune=[]),s.prune.push(n.RPC.ControlPrune.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlMessage)return e;var t=new n.RPC.ControlMessage;if(e.ihave){if(!Array.isArray(e.ihave))throw TypeError(".RPC.ControlMessage.ihave: array expected");t.ihave=[];for(var r=0;r>>3){case 1:s.topicID=e.string();break;case 2:s.messageIDs&&s.messageIDs.length||(s.messageIDs=[]),s.messageIDs.push(e.bytes());break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlIHave)return e;var t=new n.RPC.ControlIHave;if(null!=e.topicID&&(t.topicID=String(e.topicID)),e.messageIDs){if(!Array.isArray(e.messageIDs))throw TypeError(".RPC.ControlIHave.messageIDs: array expected");t.messageIDs=[];for(var r=0;r>>3===1)s.messageIDs&&s.messageIDs.length||(s.messageIDs=[]),s.messageIDs.push(e.bytes());else e.skipType(7&a)}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlIWant)return e;var t=new n.RPC.ControlIWant;if(e.messageIDs){if(!Array.isArray(e.messageIDs))throw TypeError(".RPC.ControlIWant.messageIDs: array expected");t.messageIDs=[];for(var r=0;r>>3===1)s.topicID=e.string();else e.skipType(7&a)}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlGraft)return e;var t=new n.RPC.ControlGraft;return null!=e.topicID&&(t.topicID=String(e.topicID)),t},s.toObject=function(e,t){t||(t={});var r={};return null!=e.topicID&&e.hasOwnProperty("topicID")&&(r.topicID=e.topicID,t.oneofs&&(r._topicID="topicID")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s.ControlPrune=function(){function s(e){if(this.peers=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:s.topicID=e.string();break;case 2:s.peers&&s.peers.length||(s.peers=[]),s.peers.push(n.RPC.PeerInfo.decode(e,e.uint32()));break;case 3:s.backoff=e.uint64();break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlPrune)return e;var t=new n.RPC.ControlPrune;if(null!=e.topicID&&(t.topicID=String(e.topicID)),e.peers){if(!Array.isArray(e.peers))throw TypeError(".RPC.ControlPrune.peers: array expected");t.peers=[];for(var r=0;r>>0,e.backoff.high>>>0).toNumber(!0))),t},s.toObject=function(e,t){t||(t={});var r={};if((t.arrays||t.defaults)&&(r.peers=[]),null!=e.topicID&&e.hasOwnProperty("topicID")&&(r.topicID=e.topicID,t.oneofs&&(r._topicID="topicID")),e.peers&&e.peers.length){r.peers=[];for(var s=0;s>>0,e.backoff.high>>>0).toNumber(!0):e.backoff,t.oneofs&&(r._backoff="backoff")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s.PeerInfo=function(){function s(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:s.peerID=e.bytes();break;case 2:s.signedPeerRecord=e.bytes();break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.PeerInfo)return e;var t=new n.RPC.PeerInfo;return null!=e.peerID&&("string"===typeof e.peerID?o.base64.decode(e.peerID,t.peerID=o.newBuffer(o.base64.length(e.peerID)),0):e.peerID.length&&(t.peerID=e.peerID)),null!=e.signedPeerRecord&&("string"===typeof e.signedPeerRecord?o.base64.decode(e.signedPeerRecord,t.signedPeerRecord=o.newBuffer(o.base64.length(e.signedPeerRecord)),0):e.signedPeerRecord.length&&(t.signedPeerRecord=e.signedPeerRecord)),t},s.toObject=function(e,t){t||(t={});var r={};return null!=e.peerID&&e.hasOwnProperty("peerID")&&(r.peerID=t.bytes===String?o.base64.encode(e.peerID,0,e.peerID.length):t.bytes===Array?Array.prototype.slice.call(e.peerID):e.peerID,t.oneofs&&(r._peerID="peerID")),null!=e.signedPeerRecord&&e.hasOwnProperty("signedPeerRecord")&&(r.signedPeerRecord=t.bytes===String?o.base64.encode(e.signedPeerRecord,0,e.signedPeerRecord.length):t.bytes===Array?Array.prototype.slice.call(e.signedPeerRecord):e.signedPeerRecord,t.oneofs&&(r._signedPeerRecord="signedPeerRecord")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s}(),n})); \ No newline at end of file diff --git a/web-chat/asset-manifest.json b/web-chat/asset-manifest.json new file mode 100644 index 0000000..132defe --- /dev/null +++ b/web-chat/asset-manifest.json @@ -0,0 +1,14 @@ +{ + "files": { + "main.css": "/web-chat/static/css/main.b267dcda.css", + "main.js": "/web-chat/static/js/main.1d6d6520.js", + "static/media/rpc.cjs": "/web-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs", + "index.html": "/web-chat/index.html", + "main.b267dcda.css.map": "/web-chat/static/css/main.b267dcda.css.map", + "main.1d6d6520.js.map": "/web-chat/static/js/main.1d6d6520.js.map" + }, + "entrypoints": [ + "static/css/main.b267dcda.css", + "static/js/main.1d6d6520.js" + ] +} \ No newline at end of file diff --git a/web-chat/index.html b/web-chat/index.html new file mode 100644 index 0000000..99d999a --- /dev/null +++ b/web-chat/index.html @@ -0,0 +1 @@ +Waku v2 chat app
    \ No newline at end of file diff --git a/web-chat/manifest.json b/web-chat/manifest.json new file mode 100644 index 0000000..042f1b7 --- /dev/null +++ b/web-chat/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "Waku v2 chat app", + "name": "Chat app powered by js-waku", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/web-chat/robots.txt b/web-chat/robots.txt new file mode 100644 index 0000000..e9e57dc --- /dev/null +++ b/web-chat/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/web-chat/static/css/main.b267dcda.css b/web-chat/static/css/main.b267dcda.css new file mode 100644 index 0000000..88d4a29 --- /dev/null +++ b/web-chat/static/css/main.b267dcda.css @@ -0,0 +1,2 @@ +:where(html){line-height:1.15}:where(h1){-webkit-margin-after:.67em;-webkit-margin-before:.67em;font-size:2em;margin-block-end:.67em;margin-block-start:.67em}:where(dl,ol,ul) :where(dl,ol,ul){-webkit-margin-after:0;-webkit-margin-before:0;margin-block-end:0;margin-block-start:0}:where(hr){box-sizing:initial;color:inherit;height:0}:where(pre){font-family:monospace,monospace;font-size:1em}:where(abbr[title]){text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted}:where(b,strong){font-weight:bolder}:where(code,kbd,samp){font-family:monospace,monospace;font-size:1em}:where(small){font-size:80%}:where(table){border-color:currentColor;text-indent:0}:where(button,input,select){margin:0}:where(button){text-transform:none}:where(button,input:is([type=button i],[type=reset i],[type=submit i])){-webkit-appearance:button}:where(progress){vertical-align:initial}:where(select){text-transform:none}:where(textarea){margin:0}:where(input[type=search i]){-webkit-appearance:textfield;outline-offset:-2px}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}::-webkit-input-placeholder{color:inherit;opacity:.54}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}:where(button,input:is([type=button i],[type=color i],[type=reset i],[type=submit i]))::-moz-focus-inner{border-style:none;padding:0}:where(button,input:is([type=button i],[type=color i],[type=reset i],[type=submit i]))::-moz-focusring{outline:1px dotted ButtonText}:where(:-moz-ui-invalid){box-shadow:none}:where(dialog){background-color:#fff;border:solid;color:#000;height:-moz-fit-content;height:-webkit-fit-content;height:fit-content;left:0;margin:auto;padding:1em;position:absolute;right:0;width:-moz-fit-content;width:-webkit-fit-content;width:fit-content}:where(dialog:not([open])){display:none}:where(summary){display:list-item}body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;margin:0}code{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}.room-row{margin-left:20px;text-align:left}.room-row:after{clear:both;content:"";display:table}.chat-room{margin:2px}.App{text-align:center}.App-logo{height:40vmin;pointer-events:none}@media (prefers-reduced-motion:no-preference){.App-logo{animation:App-logo-spin 20s linear infinite}}.App-header{align-items:center;background-color:#282c34;color:#fff;display:flex;flex-direction:column;font-size:calc(10px + 2vmin);justify-content:center;min-height:100vh}.App-link{color:#61dafb}@keyframes App-logo-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}} +/*# sourceMappingURL=main.b267dcda.css.map*/ \ No newline at end of file diff --git a/web-chat/static/css/main.b267dcda.css.map b/web-chat/static/css/main.b267dcda.css.map new file mode 100644 index 0000000..0d2d2f7 --- /dev/null +++ b/web-chat/static/css/main.b267dcda.css.map @@ -0,0 +1 @@ +{"version":3,"file":"static/css/main.b267dcda.css","mappings":"AAOA,aACE,gBACF,CAUA,WAEE,0BAAwB,CACxB,2BAA0B,CAF1B,aAAc,CACd,sBAAwB,CACxB,wBACF,CASA,kCACE,sBAAmB,CACnB,uBAAqB,CADrB,kBAAmB,CACnB,oBACF,CAOA,WACE,kBAAuB,CACvB,aAAc,CACd,QACF,CAOA,YACE,+BAAiC,CACjC,aACF,CASA,oBACE,yBAA0B,CAC1B,wCAAiC,CAAjC,gCACF,CAMA,iBACE,kBACF,CAOA,sBACE,+BAAiC,CACjC,aACF,CAMA,cACE,aACF,CAUA,cACE,yBAA0B,CAC1B,aACF,CASA,4BACE,QACF,CAMA,eACE,mBACF,CAMA,wEACE,yBACF,CAMA,iBACE,sBACF,CAMA,eACE,mBACF,CAMA,iBACE,QACF,CAOA,6BACE,4BAA6B,CAC7B,mBACF,CAMA,wDAEE,WACF,CAMA,4BACE,aAAc,CACd,WACF,CAMA,4BACE,uBACF,CAOA,6BACE,yBAA0B,CAC1B,YACF,CAMA,yGACE,iBAAkB,CAClB,SACF,CAMA,uGACE,6BACF,CAMA,yBACE,eACF,CASA,eACE,qBAAuB,CACvB,YAAa,CACb,UAAY,CACZ,uBAAwB,CACxB,0BAAmB,CAAnB,kBAAmB,CACnB,MAAO,CACP,WAAY,CACZ,WAAY,CACZ,iBAAkB,CAClB,OAAQ,CACR,sBAAuB,CACvB,yBAAkB,CAAlB,iBACF,CAEA,2BACE,YACF,CAMA,gBACE,iBACF,CCrQA,KAKE,kCAAmC,CACnC,iCAAkC,CAJlC,mIAEY,CAHZ,QAMF,CAEA,KACE,uEAEF,CAEA,UAEE,gBAAiB,CADjB,eAEF,CAEA,gBACE,UAAW,CACX,UAAW,CACX,aACF,CAEA,WACE,UACF,CC7BA,KACE,iBACF,CAEA,UACE,aAAc,CACd,mBACF,CAEA,8CACE,UACE,2CACF,CACF,CAEA,YAKE,kBAAmB,CAJnB,wBAAyB,CAOzB,UAAY,CALZ,YAAa,CACb,qBAAsB,CAGtB,4BAA6B,CAD7B,sBAAuB,CAJvB,gBAOF,CAEA,UACE,aACF,CAEA,yBACE,GACE,sBACF,CACA,GACE,uBACF,CACF","sources":["../node_modules/@csstools/normalize.css/normalize.css","index.css","App.css"],"sourcesContent":["/* Document\n * ========================================================================== */\n\n/**\n * 1. Correct the line height in all browsers.\n */\n\n:where(html) {\n line-height: 1.15; /* 1 */\n}\n\n/* Sections\n * ========================================================================== */\n\n/**\n * Correct the font size and margin on `h1` elements within `section` and\n * `article` contexts in Chrome, Edge, Firefox, and Safari.\n */\n\n:where(h1) {\n font-size: 2em;\n margin-block-end: 0.67em;\n margin-block-start: 0.67em;\n}\n\n/* Grouping content\n * ========================================================================== */\n\n/**\n * Remove the margin on nested lists in Chrome, Edge, and Safari.\n */\n\n:where(dl, ol, ul) :where(dl, ol, ul) {\n margin-block-end: 0;\n margin-block-start: 0;\n}\n\n/**\n * 1. Add the correct box sizing in Firefox.\n * 2. Correct the inheritance of border color in Firefox.\n */\n\n:where(hr) {\n box-sizing: content-box; /* 1 */\n color: inherit; /* 2 */\n height: 0; /* 1 */\n}\n\n/**\n * 1. Correct the inheritance and scaling of font size in all browsers.\n * 2. Correct the odd `em` font sizing in all browsers.\n */\n\n:where(pre) {\n font-family: monospace, monospace; /* 1 */\n font-size: 1em; /* 2 */\n}\n\n/* Text-level semantics\n * ========================================================================== */\n\n/**\n * Add the correct text decoration in Safari.\n */\n\n:where(abbr[title]) {\n text-decoration: underline;\n text-decoration: underline dotted;\n}\n\n/**\n * Add the correct font weight in Chrome, Edge, and Safari.\n */\n\n:where(b, strong) {\n font-weight: bolder;\n}\n\n/**\n * 1. Correct the inheritance and scaling of font size in all browsers.\n * 2. Correct the odd `em` font sizing in all browsers.\n */\n\n:where(code, kbd, samp) {\n font-family: monospace, monospace; /* 1 */\n font-size: 1em; /* 2 */\n}\n\n/**\n * Add the correct font size in all browsers.\n */\n\n:where(small) {\n font-size: 80%;\n}\n\n/* Tabular data\n * ========================================================================== */\n\n/**\n * 1. Correct table border color in Chrome, Edge, and Safari.\n * 2. Remove text indentation from table contents in Chrome, Edge, and Safari.\n */\n\n:where(table) {\n border-color: currentColor; /* 1 */\n text-indent: 0; /* 2 */\n}\n\n/* Forms\n * ========================================================================== */\n\n/**\n * Remove the margin on controls in Safari.\n */\n\n:where(button, input, select) {\n margin: 0;\n}\n\n/**\n * Remove the inheritance of text transform in Firefox.\n */\n\n:where(button) {\n text-transform: none;\n}\n\n/**\n * Correct the inability to style buttons in iOS and Safari.\n */\n\n:where(button, input:is([type=\"button\" i], [type=\"reset\" i], [type=\"submit\" i])) {\n -webkit-appearance: button;\n}\n\n/**\n * Add the correct vertical alignment in Chrome, Edge, and Firefox.\n */\n\n:where(progress) {\n vertical-align: baseline;\n}\n\n/**\n * Remove the inheritance of text transform in Firefox.\n */\n\n:where(select) {\n text-transform: none;\n}\n\n/**\n * Remove the margin in Firefox and Safari.\n */\n\n:where(textarea) {\n margin: 0;\n}\n\n/**\n * 1. Correct the odd appearance in Chrome, Edge, and Safari.\n * 2. Correct the outline style in Safari.\n */\n\n:where(input[type=\"search\" i]) {\n -webkit-appearance: textfield; /* 1 */\n outline-offset: -2px; /* 2 */\n}\n\n/**\n * Correct the cursor style of increment and decrement buttons in Safari.\n */\n\n::-webkit-inner-spin-button,\n::-webkit-outer-spin-button {\n height: auto;\n}\n\n/**\n * Correct the text style of placeholders in Chrome, Edge, and Safari.\n */\n\n::-webkit-input-placeholder {\n color: inherit;\n opacity: 0.54;\n}\n\n/**\n * Remove the inner padding in Chrome, Edge, and Safari on macOS.\n */\n\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n\n/**\n * 1. Correct the inability to style upload buttons in iOS and Safari.\n * 2. Change font properties to `inherit` in Safari.\n */\n\n::-webkit-file-upload-button {\n -webkit-appearance: button; /* 1 */\n font: inherit; /* 2 */\n}\n\n/**\n * Remove the inner border and padding of focus outlines in Firefox.\n */\n\n:where(button, input:is([type=\"button\" i], [type=\"color\" i], [type=\"reset\" i], [type=\"submit\" i]))::-moz-focus-inner {\n border-style: none;\n padding: 0;\n}\n\n/**\n * Restore the focus outline styles unset by the previous rule in Firefox.\n */\n\n:where(button, input:is([type=\"button\" i], [type=\"color\" i], [type=\"reset\" i], [type=\"submit\" i]))::-moz-focusring {\n outline: 1px dotted ButtonText;\n}\n\n/**\n * Remove the additional :invalid styles in Firefox.\n */\n\n:where(:-moz-ui-invalid) {\n box-shadow: none;\n}\n\n/* Interactive\n * ========================================================================== */\n\n/*\n * Add the correct styles in Safari.\n */\n\n:where(dialog) {\n background-color: white;\n border: solid;\n color: black;\n height: -moz-fit-content;\n height: fit-content;\n left: 0;\n margin: auto;\n padding: 1em;\n position: absolute;\n right: 0;\n width: -moz-fit-content;\n width: fit-content;\n}\n\n:where(dialog:not([open])) {\n display: none;\n}\n\n/*\n * Add the correct display in all browsers.\n */\n\n:where(summary) {\n display: list-item;\n}\n","@import-normalize; /* bring in normalize.css styles */\n\nbody {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n monospace;\n}\n\n.room-row {\n text-align: left;\n margin-left: 20px;\n}\n\n.room-row:after {\n clear: both;\n content: \"\";\n display: table;\n}\n\n.chat-room{\n margin: 2px;\n}\n",".App {\n text-align: center;\n}\n\n.App-logo {\n height: 40vmin;\n pointer-events: none;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n .App-logo {\n animation: App-logo-spin infinite 20s linear;\n }\n}\n\n.App-header {\n background-color: #282c34;\n min-height: 100vh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n font-size: calc(10px + 2vmin);\n color: white;\n}\n\n.App-link {\n color: #61dafb;\n}\n\n@keyframes App-logo-spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/web-chat/static/js/main.1d6d6520.js b/web-chat/static/js/main.1d6d6520.js new file mode 100644 index 0000000..98dd424 --- /dev/null +++ b/web-chat/static/js/main.1d6d6520.js @@ -0,0 +1,3 @@ +/*! For license information please see main.1d6d6520.js.LICENSE.txt */ +(()=>{var __webpack_modules__={7711:(e,t,r)=>{"use strict";var n=r(7441),i={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},o={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},s={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},a={};function c(e){return n.isMemo(e)?s:a[e.$$typeof]||i}a[n.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},a[n.Memo]=s;var l=Object.defineProperty,u=Object.getOwnPropertyNames,d=Object.getOwnPropertySymbols,h=Object.getOwnPropertyDescriptor,f=Object.getPrototypeOf,p=Object.prototype;e.exports=function e(t,r,n){if("string"!==typeof r){if(p){var i=f(r);i&&i!==p&&e(t,i,n)}var s=u(r);d&&(s=s.concat(d(r)));for(var a=c(t),g=c(r),y=0;y{"use strict";e.exports=function(e,t){var r=new Array(arguments.length-1),n=0,i=2,o=!0;for(;i{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),i=new Array(123),o=0;o<64;)i[n[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;r.encode=function(e,t,r){for(var i,o=null,s=[],a=0,c=0;t>2],i=(3&l)<<4,c=1;break;case 1:s[a++]=n[i|l>>4],i=(15&l)<<2,c=2;break;case 2:s[a++]=n[i|l>>6],s[a++]=n[63&l],c=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0)}return c&&(s[a++]=n[i],s[a++]=61,1===c&&(s[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};var s="invalid encoding";r.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c1)break;if(void 0===(l=i[l]))throw Error(s);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(s);return r-o},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},3297:e=>{"use strict";function t(e,r){"string"===typeof e&&(r=e,e=void 0);var n=[];function i(e){if("string"!==typeof e){var r=o();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var s=Object.keys(e),a=new Array(s.length+1),c=new Array(s.length),l=0;l{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n{"use strict";e.exports=o;var n=r(7206),i=r(7172)("fs");function o(e,t,r){return"function"===typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&i&&i.readFile?i.readFile(e,(function(n,i){return n&&"undefined"!==typeof XMLHttpRequest?o.xhr(e,t,r):n?r(n):r(null,t.binary?i:i.toString("utf8"))})):o.xhr(e,t,r):n(o,this,e,t)}o.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var i=0;i{"use strict";function t(e){return"undefined"!==typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3]}function o(e,n,i){t[0]=e,n[i]=r[3],n[i+1]=r[2],n[i+2]=r[1],n[i+3]=r[0]}function s(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?i:o,e.writeFloatBE=n?o:i,e.readFloatLE=n?s:a,e.readFloatBE=n?a:s}():function(){function t(e,t,r,n){var i=t<0?1:0;if(i&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((i<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((i<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var o=Math.floor(Math.log(t)/Math.LN2);e((i<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,r,n)}}function s(e,t,r){var n=e(t,r),i=2*(n>>31)+1,o=n>>>23&255,s=8388607&n;return 255===o?s?NaN:i*(1/0):0===o?1401298464324817e-60*i*s:i*Math.pow(2,o-150)*(s+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=s.bind(null,i),e.readFloatBE=s.bind(null,o)}(),"undefined"!==typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function i(e,n,i){t[0]=e,n[i]=r[0],n[i+1]=r[1],n[i+2]=r[2],n[i+3]=r[3],n[i+4]=r[4],n[i+5]=r[5],n[i+6]=r[6],n[i+7]=r[7]}function o(e,n,i){t[0]=e,n[i]=r[7],n[i+1]=r[6],n[i+2]=r[5],n[i+3]=r[4],n[i+4]=r[3],n[i+5]=r[2],n[i+6]=r[1],n[i+7]=r[0]}function s(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?i:o,e.writeDoubleBE=n?o:i,e.readDoubleLE=n?s:a,e.readDoubleBE=n?a:s}():function(){function t(e,t,r,n,i,o){var s=n<0?1:0;if(s&&(n=-n),0===n)e(0,i,o+t),e(1/n>0?0:2147483648,i,o+r);else if(isNaN(n))e(0,i,o+t),e(2146959360,i,o+r);else if(n>17976931348623157e292)e(0,i,o+t),e((s<<31|2146435072)>>>0,i,o+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,i,o+t),e((s<<31|a/4294967296)>>>0,i,o+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,i,o+t),e((s<<31|c+1023<<20|1048576*a&1048575)>>>0,i,o+r)}}}function s(e,t,r,n,i){var o=e(n,i+t),s=e(n,i+r),a=2*(s>>31)+1,c=s>>>20&2047,l=4294967296*(1048575&s)+o;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=s.bind(null,i,0,4),e.readDoubleBE=s.bind(null,o,4,0)}(),e}function r(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function o(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},7172:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},7468:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},i=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),i="";r&&(i=t.shift()+"/");for(var o=0;o0&&".."!==t[o-1]?t.splice(--o,2):r?t.splice(o,1):++o:"."===t[o]?t.splice(o,1):++o;return i+t.join("/")};r.resolve=function(e,t,r){return r||(t=i(t)),n(t)?t:(r||(e=i(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?i(e+"/"+t):t)}},8236:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,i=n>>>1,o=null,s=n;return function(r){if(r<1||r>i)return e(r);s+r>n&&(o=e(n),s=0);var a=t.call(o,s,s+=r);return 7&s&&(s=1+(7|s)),a}}},3861:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?o[s++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[s++]=55296+(n>>10),o[s++]=56320+(1023&n)):o[s++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))},r.write=function(e,t,r){for(var n,i,o=r,s=0;s>6|192,t[r++]=63&n|128):55296===(64512&n)&&56320===(64512&(i=e.charCodeAt(s+1)))?(n=65536+((1023&n)<<10)+(1023&i),++s,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-o}},6232:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(5073);function i(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>8,t[r+1]=e>>>0,t}function o(e,t,r){return void 0===t&&(t=new Uint8Array(2)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t}function s(e,t){return void 0===t&&(t=0),e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function a(e,t){return void 0===t&&(t=0),(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function c(e,t){return void 0===t&&(t=0),e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function l(e,t){return void 0===t&&(t=0),(e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t])>>>0}function u(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>24,t[r+1]=e>>>16,t[r+2]=e>>>8,t[r+3]=e>>>0,t}function d(e,t,r){return void 0===t&&(t=new Uint8Array(4)),void 0===r&&(r=0),t[r+0]=e>>>0,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24,t}function h(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),u(e/4294967296>>>0,t,r),u(e>>>0,t,r+4),t}function f(e,t,r){return void 0===t&&(t=new Uint8Array(8)),void 0===r&&(r=0),d(e>>>0,t,r),d(e/4294967296>>>0,t,r+4),t}t.readInt16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])<<16>>16},t.readUint16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])>>>0},t.readInt16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])<<16>>16},t.readUint16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])>>>0},t.writeUint16BE=i,t.writeInt16BE=i,t.writeUint16LE=o,t.writeInt16LE=o,t.readInt32BE=s,t.readUint32BE=a,t.readInt32LE=c,t.readUint32LE=l,t.writeUint32BE=u,t.writeInt32BE=u,t.writeUint32LE=d,t.writeInt32LE=d,t.readInt64BE=function(e,t){void 0===t&&(t=0);var r=s(e,t),n=s(e,t+4);return 4294967296*r+n-4294967296*(n>>31)},t.readUint64BE=function(e,t){return void 0===t&&(t=0),4294967296*a(e,t)+a(e,t+4)},t.readInt64LE=function(e,t){void 0===t&&(t=0);var r=c(e,t);return 4294967296*c(e,t+4)+r-4294967296*(r>>31)},t.readUint64LE=function(e,t){void 0===t&&(t=0);var r=l(e,t);return 4294967296*l(e,t+4)+r},t.writeUint64BE=h,t.writeInt64BE=h,t.writeUint64LE=f,t.writeInt64LE=f,t.readUintBE=function(e,t,r){if(void 0===r&&(r=0),e%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,o=e/8+r-1;o>=r;o--)n+=t[o]*i,i*=256;return n},t.readUintLE=function(e,t,r){if(void 0===r&&(r=0),e%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(e/8>t.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,o=r;o=i;s--)r[s]=t/o&255,o*=256;return r},t.writeUintLE=function(e,t,r,i){if(void 0===r&&(r=new Uint8Array(e/8)),void 0===i&&(i=0),e%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!n.isSafeInteger(t))throw new Error("writeUintLE value must be an integer");for(var o=1,s=i;s{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(6232),i=r(9116);function o(e,t,r){for(var i=1634760805,o=857760878,s=2036477234,a=1797285236,c=r[3]<<24|r[2]<<16|r[1]<<8|r[0],l=r[7]<<24|r[6]<<16|r[5]<<8|r[4],u=r[11]<<24|r[10]<<16|r[9]<<8|r[8],d=r[15]<<24|r[14]<<16|r[13]<<8|r[12],h=r[19]<<24|r[18]<<16|r[17]<<8|r[16],f=r[23]<<24|r[22]<<16|r[21]<<8|r[20],p=r[27]<<24|r[26]<<16|r[25]<<8|r[24],g=r[31]<<24|r[30]<<16|r[29]<<8|r[28],y=t[3]<<24|t[2]<<16|t[1]<<8|t[0],m=t[7]<<24|t[6]<<16|t[5]<<8|t[4],v=t[11]<<24|t[10]<<16|t[9]<<8|t[8],b=t[15]<<24|t[14]<<16|t[13]<<8|t[12],w=i,E=o,S=s,_=a,C=c,T=l,I=u,A=d,k=h,R=f,P=p,D=g,N=y,O=m,x=v,L=b,M=0;M<20;M+=2)C=(C^=k=k+(N=(N^=w=w+C|0)>>>16|N<<16)|0)>>>20|C<<12,T=(T^=R=R+(O=(O^=E=E+T|0)>>>16|O<<16)|0)>>>20|T<<12,I=(I^=P=P+(x=(x^=S=S+I|0)>>>16|x<<16)|0)>>>20|I<<12,A=(A^=D=D+(L=(L^=_=_+A|0)>>>16|L<<16)|0)>>>20|A<<12,I=(I^=P=P+(x=(x^=S=S+I|0)>>>24|x<<8)|0)>>>25|I<<7,A=(A^=D=D+(L=(L^=_=_+A|0)>>>24|L<<8)|0)>>>25|A<<7,T=(T^=R=R+(O=(O^=E=E+T|0)>>>24|O<<8)|0)>>>25|T<<7,C=(C^=k=k+(N=(N^=w=w+C|0)>>>24|N<<8)|0)>>>25|C<<7,T=(T^=P=P+(L=(L^=w=w+T|0)>>>16|L<<16)|0)>>>20|T<<12,I=(I^=D=D+(N=(N^=E=E+I|0)>>>16|N<<16)|0)>>>20|I<<12,A=(A^=k=k+(O=(O^=S=S+A|0)>>>16|O<<16)|0)>>>20|A<<12,C=(C^=R=R+(x=(x^=_=_+C|0)>>>16|x<<16)|0)>>>20|C<<12,A=(A^=k=k+(O=(O^=S=S+A|0)>>>24|O<<8)|0)>>>25|A<<7,C=(C^=R=R+(x=(x^=_=_+C|0)>>>24|x<<8)|0)>>>25|C<<7,I=(I^=D=D+(N=(N^=E=E+I|0)>>>24|N<<8)|0)>>>25|I<<7,T=(T^=P=P+(L=(L^=w=w+T|0)>>>24|L<<8)|0)>>>25|T<<7;n.writeUint32LE(w+i|0,e,0),n.writeUint32LE(E+o|0,e,4),n.writeUint32LE(S+s|0,e,8),n.writeUint32LE(_+a|0,e,12),n.writeUint32LE(C+c|0,e,16),n.writeUint32LE(T+l|0,e,20),n.writeUint32LE(I+u|0,e,24),n.writeUint32LE(A+d|0,e,28),n.writeUint32LE(k+h|0,e,32),n.writeUint32LE(R+f|0,e,36),n.writeUint32LE(P+p|0,e,40),n.writeUint32LE(D+g|0,e,44),n.writeUint32LE(N+y|0,e,48),n.writeUint32LE(O+m|0,e,52),n.writeUint32LE(x+v|0,e,56),n.writeUint32LE(L+b|0,e,60)}function s(e,t,r,n,s){if(void 0===s&&(s=0),32!==e.length)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,t++;if(n>0)throw new Error("ChaCha: counter overflow")}t.streamXOR=s,t.stream=function(e,t,r,n){return void 0===n&&(n=0),i.wipe(r),s(e,t,r,r,n)}},3642:(e,t,r)=>{"use strict";var n=r(8284),i=r(5629),o=r(9116),s=r(6232),a=r(8770);t.Cv=32,t.WH=12,t.pg=16;var c=new Uint8Array(16),l=function(){function e(e){if(this.nonceLength=t.WH,this.tagLength=t.pg,e.length!==t.Cv)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return e.prototype.seal=function(e,t,r,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var a=new Uint8Array(32);n.stream(this._key,s,a,4);var c,l=t.length+this.tagLength;if(i){if(i.length!==l)throw new Error("ChaCha20Poly1305: incorrect destination length");c=i}else c=new Uint8Array(l);return n.streamXOR(this._key,s,t,c,4),this._authenticate(c.subarray(c.length-this.tagLength,c.length),a,c.subarray(0,c.length-this.tagLength),r),o.wipe(s),c},e.prototype.open=function(e,t,r,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(t.length0&&a.update(c.subarray(n.length%16))),a.update(r),r.length%16>0&&a.update(c.subarray(r.length%16));var l=new Uint8Array(8);n&&s.writeUint64LE(n.length,l),a.update(l),s.writeUint64LE(r.length,l),a.update(l);for(var u=a.digest(),d=0;d{"use strict";function r(e,t){if(e.length!==t.length)return 0;for(var r=0,n=0;n>>8}Object.defineProperty(t,"__esModule",{value:!0}),t.select=function(e,t,r){return~(e-1)&t|e-1&r},t.lessOrEqual=function(e,t){return(0|e)-(0|t)-1>>>31&1},t.compare=r,t.equal=function(e,t){return 0!==e.length&&0!==t.length&&0!==r(e,t)}},1412:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSerializableHash=function(e){return"undefined"!==typeof e.saveState&&"undefined"!==typeof e.restoreState&&"undefined"!==typeof e.cleanSavedState}},2497:(e,t,r)=>{"use strict";var n=r(5499),i=r(9116),o=function(){function e(e,t,r,i){void 0===r&&(r=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var o=n.hmac(this._hash,r,t);this._hmac=new n.HMAC(e,o),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return e.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(0===e)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},e.prototype.expand=function(e){for(var t=new Uint8Array(e),r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(1412),i=r(8770),o=r(9116),s=function(){function e(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var r=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(r).clean():r.set(t);for(var i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mul=Math.imul||function(e,t){var r=65535&e,n=65535&t;return r*n+((e>>>16&65535)*n+r*(t>>>16&65535)<<16>>>0)|0},t.add=function(e,t){return e+t|0},t.sub=function(e,t){return e-t|0},t.rotl=function(e,t){return e<>>32-t},t.rotr=function(e,t){return e<<32-t|e>>>t},t.isInteger=Number.isInteger||function(e){return"number"===typeof e&&isFinite(e)&&Math.floor(e)===e},t.MAX_SAFE_INTEGER=9007199254740991,t.isSafeInteger=function(e){return t.isInteger(e)&&e>=-t.MAX_SAFE_INTEGER&&e<=t.MAX_SAFE_INTEGER}},5629:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(8770),i=r(9116);t.DIGEST_LENGTH=16;var o=function(){function e(e){this.digestLength=t.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=8191&r;var n=e[2]|e[3]<<8;this._r[1]=8191&(r>>>13|n<<3);var i=e[4]|e[5]<<8;this._r[2]=7939&(n>>>10|i<<6);var o=e[6]|e[7]<<8;this._r[3]=8191&(i>>>7|o<<9);var s=e[8]|e[9]<<8;this._r[4]=255&(o>>>4|s<<12),this._r[5]=s>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=8191&(s>>>14|a<<2);var c=e[12]|e[13]<<8;this._r[7]=8065&(a>>>11|c<<5);var l=e[14]|e[15]<<8;this._r[8]=8191&(c>>>8|l<<8),this._r[9]=l>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return e.prototype._blocks=function(e,t,r){for(var n=this._fin?0:2048,i=this._h[0],o=this._h[1],s=this._h[2],a=this._h[3],c=this._h[4],l=this._h[5],u=this._h[6],d=this._h[7],h=this._h[8],f=this._h[9],p=this._r[0],g=this._r[1],y=this._r[2],m=this._r[3],v=this._r[4],b=this._r[5],w=this._r[6],E=this._r[7],S=this._r[8],_=this._r[9];r>=16;){var C=e[t+0]|e[t+1]<<8;i+=8191&C;var T=e[t+2]|e[t+3]<<8;o+=8191&(C>>>13|T<<3);var I=e[t+4]|e[t+5]<<8;s+=8191&(T>>>10|I<<6);var A=e[t+6]|e[t+7]<<8;a+=8191&(I>>>7|A<<9);var k=e[t+8]|e[t+9]<<8;c+=8191&(A>>>4|k<<12),l+=k>>>1&8191;var R=e[t+10]|e[t+11]<<8;u+=8191&(k>>>14|R<<2);var P=e[t+12]|e[t+13]<<8;d+=8191&(R>>>11|P<<5);var D=e[t+14]|e[t+15]<<8,N=0,O=N;O+=i*p,O+=o*(5*_),O+=s*(5*S),O+=a*(5*E),N=(O+=c*(5*w))>>>13,O&=8191,O+=l*(5*b),O+=u*(5*v),O+=d*(5*m),O+=(h+=8191&(P>>>8|D<<8))*(5*y);var x=N+=(O+=(f+=D>>>5|n)*(5*g))>>>13;x+=i*g,x+=o*p,x+=s*(5*_),x+=a*(5*S),N=(x+=c*(5*E))>>>13,x&=8191,x+=l*(5*w),x+=u*(5*b),x+=d*(5*v),x+=h*(5*m),N+=(x+=f*(5*y))>>>13,x&=8191;var L=N;L+=i*y,L+=o*g,L+=s*p,L+=a*(5*_),N=(L+=c*(5*S))>>>13,L&=8191,L+=l*(5*E),L+=u*(5*w),L+=d*(5*b),L+=h*(5*v);var M=N+=(L+=f*(5*m))>>>13;M+=i*m,M+=o*y,M+=s*g,M+=a*p,N=(M+=c*(5*_))>>>13,M&=8191,M+=l*(5*S),M+=u*(5*E),M+=d*(5*w),M+=h*(5*b);var B=N+=(M+=f*(5*v))>>>13;B+=i*v,B+=o*m,B+=s*y,B+=a*g,N=(B+=c*p)>>>13,B&=8191,B+=l*(5*_),B+=u*(5*S),B+=d*(5*E),B+=h*(5*w);var U=N+=(B+=f*(5*b))>>>13;U+=i*b,U+=o*v,U+=s*m,U+=a*y,N=(U+=c*g)>>>13,U&=8191,U+=l*p,U+=u*(5*_),U+=d*(5*S),U+=h*(5*E);var F=N+=(U+=f*(5*w))>>>13;F+=i*w,F+=o*b,F+=s*v,F+=a*m,N=(F+=c*y)>>>13,F&=8191,F+=l*g,F+=u*p,F+=d*(5*_),F+=h*(5*S);var V=N+=(F+=f*(5*E))>>>13;V+=i*E,V+=o*w,V+=s*b,V+=a*v,N=(V+=c*m)>>>13,V&=8191,V+=l*y,V+=u*g,V+=d*p,V+=h*(5*_);var K=N+=(V+=f*(5*S))>>>13;K+=i*S,K+=o*E,K+=s*w,K+=a*b,N=(K+=c*v)>>>13,K&=8191,K+=l*m,K+=u*y,K+=d*g,K+=h*p;var j=N+=(K+=f*(5*_))>>>13;j+=i*_,j+=o*S,j+=s*E,j+=a*w,N=(j+=c*b)>>>13,j&=8191,j+=l*v,j+=u*m,j+=d*y,j+=h*g,i=O=8191&(N=(N=((N+=(j+=f*p)>>>13)<<2)+N|0)+(O&=8191)|0),o=x+=N>>>=13,s=L&=8191,a=M&=8191,c=B&=8191,l=U&=8191,u=F&=8191,d=V&=8191,h=K&=8191,f=j&=8191,t+=16,r-=16}this._h[0]=i,this._h[1]=o,this._h[2]=s,this._h[3]=a,this._h[4]=c,this._h[5]=l,this._h[6]=u,this._h[7]=d,this._h[8]=h,this._h[9]=f},e.prototype.finish=function(e,t){void 0===t&&(t=0);var r,n,i,o,s=new Uint16Array(10);if(this._leftover){for(o=this._leftover,this._buffer[o++]=1;o<16;o++)this._buffer[o]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(r=this._h[1]>>>13,this._h[1]&=8191,o=2;o<10;o++)this._h[o]+=r,r=this._h[o]>>>13,this._h[o]&=8191;for(this._h[0]+=5*r,r=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=r,r=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=r,s[0]=this._h[0]+5,r=s[0]>>>13,s[0]&=8191,o=1;o<10;o++)s[o]=this._h[o]+r,r=s[o]>>>13,s[o]&=8191;for(s[9]-=8192,n=(1^r)-1,o=0;o<10;o++)s[o]&=n;for(n=~n,o=0;o<10;o++)this._h[o]=this._h[o]&n|s[o];for(this._h[0]=65535&(this._h[0]|this._h[1]<<13),this._h[1]=65535&(this._h[1]>>>3|this._h[2]<<10),this._h[2]=65535&(this._h[2]>>>6|this._h[3]<<7),this._h[3]=65535&(this._h[3]>>>9|this._h[4]<<4),this._h[4]=65535&(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14),this._h[5]=65535&(this._h[6]>>>2|this._h[7]<<11),this._h[6]=65535&(this._h[7]>>>5|this._h[8]<<8),this._h[7]=65535&(this._h[8]>>>8|this._h[9]<<5),i=this._h[0]+this._pad[0],this._h[0]=65535&i,o=1;o<8;o++)i=(this._h[o]+this._pad[o]|0)+(i>>>16)|0,this._h[o]=65535&i;return e[t+0]=this._h[0]>>>0,e[t+1]=this._h[0]>>>8,e[t+2]=this._h[1]>>>0,e[t+3]=this._h[1]>>>8,e[t+4]=this._h[2]>>>0,e[t+5]=this._h[2]>>>8,e[t+6]=this._h[3]>>>0,e[t+7]=this._h[3]>>>8,e[t+8]=this._h[4]>>>0,e[t+9]=this._h[4]>>>8,e[t+10]=this._h[5]>>>0,e[t+11]=this._h[5]>>>8,e[t+12]=this._h[6]>>>0,e[t+13]=this._h[6]>>>8,e[t+14]=this._h[7]>>>0,e[t+15]=this._h[7]>>>8,this._finished=!0,this},e.prototype.update=function(e){var t,r=0,n=e.length;if(this._leftover){(t=16-this._leftover)>n&&(t=n);for(var i=0;i=16&&(t=n-n%16,this._blocks(e,r,t),r+=t,n-=t),n){for(i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.randomStringForEntropy=t.randomString=t.randomUint32=t.randomBytes=t.defaultRandomSource=void 0;const n=r(933),i=r(6232),o=r(9116);function s(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.defaultRandomSource;return r.randomBytes(e)}t.defaultRandomSource=new n.SystemRandomSource,t.randomBytes=s,t.randomUint32=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t.defaultRandomSource;const r=s(4,e),n=(0,i.readUint32LE)(r);return(0,o.wipe)(r),n};const a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function c(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.defaultRandomSource;if(r.length<2)throw new Error("randomString charset is too short");if(r.length>256)throw new Error("randomString charset is too long");let i="";const c=r.length,l=256-256%c;for(;e>0;){const t=s(Math.ceil(256*e/l),n);for(let n=0;n0;n++){const o=t[n];o1&&void 0!==arguments[1]?arguments[1]:a,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.defaultRandomSource;const i=Math.ceil(e/(Math.log(r.length)/Math.LN2));return c(i,r,n)}},8136:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserRandomSource=void 0;t.BrowserRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;const e="undefined"!==typeof self?self.crypto||self.msCrypto:null;e&&void 0!==e.getRandomValues&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");const t=new Uint8Array(e);for(let r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NodeRandomSource=void 0;const n=r(9116);t.NodeRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;{const e=r(5883);e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");const r=new Uint8Array(e);for(let n=0;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SystemRandomSource=void 0;const n=r(8136),i=r(8188);t.SystemRandomSource=class{constructor(){return this.isAvailable=!1,this.name="",this._source=new n.BrowserRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Browser")):(this._source=new i.NodeRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Node")):void 0)}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}}},4888:(e,t,r)=>{"use strict";var n=r(6232),i=r(9116);t.k=32,t.cn=64;var o=function(){function e(){this.digestLength=t.k,this.blockSize=t.cn,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return e.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},e.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},e.prototype.clean=function(){i.wipe(this._buffer),i.wipe(this._temp),this.reset()},e.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var r=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[r++],t--;this._bufferLength===this.blockSize&&(a(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(r=a(this._temp,this._state,e,r,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[r++],t--;return this},e.prototype.finish=function(e){if(!this._finished){var t=this._bytesHashed,r=this._bufferLength,i=t/536870912|0,o=t<<3,s=t%64<56?64:128;this._buffer[r]=128;for(var c=r+1;c0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},e.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},e.prototype.cleanSavedState=function(e){i.wipe(e.state),e.buffer&&i.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},e}();t.mE=o;var s=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function a(e,t,r,i,o){for(;o>=64;){for(var a=t[0],c=t[1],l=t[2],u=t[3],d=t[4],h=t[5],f=t[6],p=t[7],g=0;g<16;g++){var y=i+4*g;e[g]=n.readUint32BE(r,y)}for(g=16;g<64;g++){var m=e[g-2],v=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,b=((m=e[g-15])>>>7|m<<25)^(m>>>18|m<<14)^m>>>3;e[g]=(v+e[g-7]|0)+(b+e[g-16]|0)}for(g=0;g<64;g++){v=(((d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7))+(d&h^~d&f)|0)+(p+(s[g]+e[g]|0)|0)|0,b=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&c^a&l^c&l)|0;p=f,f=h,h=d,d=u+v|0,u=l,l=c,c=a,a=v+b|0}t[0]+=a,t[1]+=c,t[2]+=l,t[3]+=u,t[4]+=d,t[5]+=h,t[6]+=f,t[7]+=p,i+=64,o-=64}return i}t.vp=function(e){var t=new o;t.update(e);var r=t.digest();return t.clean(),r}},9116:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wipe=function(e){for(var t=0;t{"use strict";t.gi=t.Au=t._w=t.KS=t.kz=void 0;const n=r(6271),i=r(9116);function o(e){const t=new Float64Array(16);if(e)for(let r=0;r=0;--o){const e=r[o>>>3]>>>(7&o)&1;l(i,s,e),l(p,g,e),u(y,i,p),d(i,i,p),u(p,s,g),d(s,s,g),f(g,y),f(m,i),h(i,p,i),h(p,s,y),u(y,i,p),d(i,i,p),f(s,i),d(p,g,m),h(i,p,a),u(i,i,g),h(p,p,i),h(i,g,m),h(g,s,n),f(s,y),l(i,s,e),l(p,g,e)}for(let o=0;o<16;o++)n[o+16]=i[o],n[o+32]=p[o],n[o+48]=s[o],n[o+64]=g[o];const v=n.subarray(32),b=n.subarray(16);!function(e,t){const r=o();for(let n=0;n<16;n++)r[n]=t[n];for(let n=253;n>=0;n--)f(r,r),2!==n&&4!==n&&h(r,r,t);for(let n=0;n<16;n++)e[n]=r[n]}(v,v),h(b,b,v);const w=new Uint8Array(32);return function(e,t){const r=o(),n=o();for(let i=0;i<16;i++)n[i]=t[i];c(n),c(n),c(n);for(let i=0;i<2;i++){r[0]=n[0]-65517;for(let t=1;t<15;t++)r[t]=n[t]-65535-(r[t-1]>>16&1),r[t-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);const e=r[15]>>16&1;r[14]&=65535,l(n,r,1-e)}for(let i=0;i<16;i++)e[2*i]=255&n[i],e[2*i+1]=n[i]>>8}(w,b),w}function g(e){return p(e,s)}function y(e){if(e.length!==t.KS)throw new Error("x25519: seed must be ".concat(t.KS," bytes"));const r=new Uint8Array(e);return{publicKey:g(r),secretKey:r}}t._w=y,t.Au=function(e){const t=(0,n.randomBytes)(32,e),r=y(t);return(0,i.wipe)(t),r},t.gi=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(e.length!==t.kz)throw new Error("X25519: incorrect secret key length");if(r.length!==t.kz)throw new Error("X25519: incorrect public key length");const i=p(e,r);if(n){let e=0;for(let t=0;t{function t(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)t&&t.removeEventListener&&t.removeEventListener("abort",r)}for(const n of e)if(n&&n.addEventListener){if(n.aborted){r();break}n.addEventListener("abort",r)}return t.signal}e.exports=t,e.exports.anySignal=t},2951:e=>{e.exports=e=>t=>(r,n)=>{0===r&&t(0,((t,r)=>{n(t,1===t?e(r):r)}))}},2042:e=>{e.exports=function(){let e=[];return(t,r)=>{if(0===t){const t=r;e.push(t),t(0,(r=>{if(2===r){const r=e.indexOf(t);r>-1&&e.splice(r,1)}}))}else{const n=e.slice(0);for(let i,o=0,s=n.length;o-1&&i(t,r)}}}},312:e=>{var t=1e3,r=60*t,n=60*r,i=24*n,o=7*i,s=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*o;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var o=Math.abs(e);if(o>=i)return a(e,o,i,"day");if(o>=n)return a(e,o,n,"hour");if(o>=r)return a(e,o,r,"minute");if(o>=t)return a(e,o,t,"second");return e+" ms"}(e):function(e){var o=Math.abs(e);if(o>=i)return Math.round(e/i)+"d";if(o>=n)return Math.round(e/n)+"h";if(o>=r)return Math.round(e/r)+"m";if(o>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},8392:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(r){}!e&&"undefined"!==typeof process&&"env"in process&&(e={NODE_ENV:"production",PUBLIC_URL:"/web-chat",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.DEBUG);return e},t.useColors=function(){if("undefined"!==typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!==typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!==typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!==typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(8472)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}},8472:(e,t,r)=>{e.exports=function(e){function t(e){let r,i,o,s=null;function a(){for(var e=arguments.length,n=new Array(e),i=0;i{if("%%"===e)return"%";l++;const i=t.formatters[r];if("function"===typeof i){const t=n[l];e=i.call(o,t),n.splice(l,1),l--}return e})),t.formatArgs.call(o,n);const u=o.log||t.log;u.apply(o,n)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"===typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+("undefined"===typeof r?":":r)+e);return n.log=this.log,n}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"===typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";function t(e,t){t=t||{};this._head=0,this._tail=0,this._capacity=t.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}t.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}},t.prototype.get=function(e){return this.peekAt(e)},t.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},t.prototype.peekFront=function(){return this.peek()},t.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(t.prototype,"length",{get:function(){return this.size()}}),t.prototype.size=function(){return this._head===this._tail?0:this._headthis._capacity&&this.pop(),this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},t.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),r}},t.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var i,o=this._list[t];if(e0;i--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(i=r-1-e;i>0;i--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return o}}},t.prototype.remove=function(e,t){var r,n=e,i=t;if(n===(0|n)&&this._head!==this._tail){var o=this.size(),s=this._list.length;if(!(n>=o||n<-o||t<1)){if(n<0&&(n+=o),1===t||!t)return(r=new Array(1))[0]=this.removeOne(n),r;if(0===n&&n+t>=o)return r=this.toArray(),this.clear(),r;var a;for(n+t>o&&(t=o-n),r=new Array(t),a=0;a0;a--)this._list[n=n+1+s&this._capacityMask]=void 0;return r}if(0===e){for(this._head=this._head+t+s&this._capacityMask,a=t-1;a>0;a--)this._list[n=n+1+s&this._capacityMask]=void 0;return r}if(n0;a--)this.unshift(this._list[n=n-1+s&this._capacityMask]);for(n=this._head-1+s&this._capacityMask;i>0;)this._list[n=n-1+s&this._capacityMask]=void 0,i--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+s&this._capacityMask,a=o-(t+e);a>0;a--)this.push(this._list[n++]);for(n=this._tail;i>0;)this._list[n=n+1+s&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=s>>>2&&this._shrinkArray(),r}}},t.prototype.splice=function(e,t){var r=e;if(r===(0|r)){var n=this.size();if(r<0&&(r+=n),!(r>n)){if(arguments.length>2){var i,o,s,a=arguments.length,c=this._list.length,l=2;if(!n||r0&&(this._head=this._head+r+c&this._capacityMask)):(s=this.remove(r,t),this._head=this._head+r+c&this._capacityMask);a>l;)this.unshift(arguments[--a]);for(i=r;i>0;i--)this.unshift(o[i-1])}else{var u=(o=new Array(n-(r+t))).length;for(i=0;ithis._tail){for(t=this._head;t>>=1,this._capacityMask>>>=1},e.exports=t},7963:e=>{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,n){if(!e||"string"===typeof e)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"===typeof r&&(n=r,r=""),r&&(n.code=r);try{return t(e,n)}catch(i){n.message=e.message,n.stack=e.stack;const r=function(){};r.prototype=Object.create(Object.getPrototypeOf(e));return t(new r,n)}}},3634:(e,t,r)=>{"use strict";const n=r(5413);t.zN=n.EventIterator,n.EventIterator},5413:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn("EventIterator queue reached ".concat(this.pushQueue.length," items")))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e){let{highWaterMark:t=100,lowWaterMark:n=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new r;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},7143:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,s){if("function"!==typeof n)throw new TypeError("The listener must be a function");var a=new i(n,o||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i{"use strict";var t,r="object"===typeof Reflect?Reflect:null,n=r&&"function"===typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"===typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!==e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,o),n(r)}function o(){"function"===typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}g(e,t,o,{once:!0}),"error"!==t&&function(e,t,r){"function"===typeof e.on&&g(e,"error",t,r)}(e,i,{once:!0})}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!==typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function l(e,t,r,n){var i,o,s,l;if(a(r),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]),void 0===s)s=o[t]=r,++e._eventsCount;else if("function"===typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(i=c(e))>0&&s.length>i&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,l=u,console&&console.warn&&console.warn(l)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=u.bind(n);return i.listener=r,n.wrapFn=i,i}function h(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"===typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(void 0===c)return!1;if("function"===typeof c)n(c,this,t);else{var l=c.length,u=p(c,l);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},o.prototype.listeners=function(e){return h(this,e,!0)},o.prototype.rawListeners=function(e){return h(this,e,!1)},o.listenerCount=function(e,t){return"function"===typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},o.prototype.listenerCount=f,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},1167:e=>{e.exports=class{constructor(e){if(!(e>0)||0!==(e-1&e))throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}}},5125:(e,t,r)=>{const n=r(1167);e.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head}push(e){if(!this.head.push(e)){const t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){const e=this.tail.shift();if(void 0===e&&this.tail.next){const e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}},4737:e=>{e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,o){r[i]=o,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},8974:e=>{"use strict";const t="[a-fA-F\\d:]",r=e=>e&&e.includeBoundaries?"(?:(?<=\\s|^)(?=".concat(t,")|(?<=").concat(t,")(?=\\s|$))"):"",n="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",i="[a-fA-F\\d]{1,4}",o="\n(?:\n(?:".concat(i,":){7}(?:").concat(i,"|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:").concat(i,":){6}(?:").concat(n,"|:").concat(i,"|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:").concat(i,":){5}(?::").concat(n,"|(?::").concat(i,"){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:").concat(i,":){4}(?:(?::").concat(i,"){0,1}:").concat(n,"|(?::").concat(i,"){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:").concat(i,":){3}(?:(?::").concat(i,"){0,2}:").concat(n,"|(?::").concat(i,"){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:").concat(i,":){2}(?:(?::").concat(i,"){0,3}:").concat(n,"|(?::").concat(i,"){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:").concat(i,":){1}(?:(?::").concat(i,"){0,4}:").concat(n,"|(?::").concat(i,"){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::").concat(i,"){0,5}:").concat(n,"|(?::").concat(i,"){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n").replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),s=new RegExp("(?:^".concat(n,"$)|(?:^").concat(o,"$)")),a=new RegExp("^".concat(n,"$")),c=new RegExp("^".concat(o,"$")),l=e=>e&&e.exact?s:new RegExp("(?:".concat(r(e)).concat(n).concat(r(e),")|(?:").concat(r(e)).concat(o).concat(r(e),")"),"g");l.v4=e=>e&&e.exact?a:new RegExp("".concat(r(e)).concat(n).concat(r(e)),"g"),l.v6=e=>e&&e.exact?c:new RegExp("".concat(r(e)).concat(o).concat(r(e)),"g"),e.exports=l},7201:function(e){!function(t){"use strict";const r="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^".concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"$"),"i"),threeOctet:new RegExp("^".concat(r,"\\.").concat(r,"\\.").concat(r,"$"),"i"),twoOctet:new RegExp("^".concat(r,"\\.").concat(r,"$"),"i"),longValue:new RegExp("^".concat(r,"$"),"i")},i=new RegExp("^0[0-7]+$","i"),o=new RegExp("^0x[a-f0-9]+$","i"),s="%[0-9a-z]{1,}",a="(?:[0-9a-f]+::?)+",c={zoneIndex:new RegExp(s,"i"),native:new RegExp("^(::)?(".concat(a,")?([0-9a-f]+)?(::)?(").concat(s,")?$"),"i"),deprecatedTransitional:new RegExp("^(?:::)(".concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"(").concat(s,")?)$"),"i"),transitional:new RegExp("^((?:".concat(a,")|(?:::)(?:").concat(a,")?)").concat(r,"\\.").concat(r,"\\.").concat(r,"\\.").concat(r,"(").concat(s,")?$"),"i")};function l(e,t){if(e.indexOf("::")!==e.lastIndexOf("::"))return null;let r,n,i=0,o=-1,s=(e.match(c.zoneIndex)||[])[0];for(s&&(s=s.substring(1),e=e.replace(/%.+$/,""));(o=e.indexOf(":",o+1))>=0;)i++;if("::"===e.substr(0,2)&&i--,"::"===e.substr(-2,2)&&i--,i>t)return null;for(n=t-i,r=":";n--;)r+="0:";return":"===(e=e.replace("::",r))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){const t=e.split(":"),r=[];for(let e=0;e0;){if(i=r-n,i<0&&(i=0),e[o]>>i!==t[o]>>i)return!1;n-=r,o+=1}return!0}function d(e){if(o.test(e))return parseInt(e,16);if("0"===e[0]&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw new Error("ipaddr: cannot parse ".concat(e," as octal"))}return parseInt(e,10)}function h(e,t){for(;e.length=0;n-=1){if(i=this.octets[n],!(i in r))return null;if(o=r[i],t&&0!==o)return null;8!==o&&(t=!0),e+=o}return 32-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return f.IPv6.parse("::ffff:".concat(this.toString()))},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(".")},e}(),f.IPv4.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let o=0;for(;o<4;)i.push(parseInt(r[o],10)|255^parseInt(n[o],10)),o++;return new this(i)}catch(t){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.isIPv4=function(e){return null!==this.parser(e)},f.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(t){return!1}},f.IPv4.isValidFourPartDecimal=function(e){return!(!f.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},f.IPv4.networkAddressFromCIDR=function(e){let t,r,n,i,o;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),o=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(o[r],10)),r++;return new this(i)}catch(s){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.parse=function(e){const t=this.parser(e);if(null===t)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(t)},f.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){const e=parseInt(t[2]);if(e>=0&&e<=32){const r=[this.parse(t[1]),e];return Object.defineProperty(r,"toString",{value:function(){return this.join("/")}}),r}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},f.IPv4.parser=function(e){let t,r,i;if(t=e.match(n.fourOctet))return function(){const e=t.slice(1,6),n=[];for(let t=0;t4294967295||i<0)throw new Error("ipaddr: address outside defined range");return function(){const e=[];let t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e}().reverse()}return(t=e.match(n.twoOctet))?function(){const e=t.slice(1,4),r=[];if(i=d(e[1]),i>16777215||i<0)throw new Error("ipaddr: address outside defined range");return r.push(d(e[0])),r.push(i>>16&255),r.push(i>>8&255),r.push(255&i),r}():(t=e.match(n.threeOctet))?function(){const e=t.slice(1,5),r=[];if(i=d(e[2]),i>65535||i<0)throw new Error("ipaddr: address outside defined range");return r.push(d(e[0])),r.push(d(e[1])),r.push(i>>8&255),r.push(255&i),r}():null},f.IPv4.subnetMaskFromPrefixLength=function(e){if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");const t=[0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r=0;o-=1){if(n=this.parts[o],!(n in r))return null;if(i=r[n],t&&0!==i)return null;16!==i&&(t=!0),e+=i}return 128-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e;const t=[],r=this.parts;for(let n=0;n>8),t.push(255&e);return t},e.prototype.toFixedLengthString=function(){const e=function(){const e=[];for(let t=0;t>8,255&t,r>>8,255&r])},e.prototype.toNormalizedString=function(){const e=function(){const e=[];for(let t=0;ti&&(n=r.index,i=r[0].length);return i<0?t:"".concat(t.substring(0,n),"::").concat(t.substring(n+i))},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e}(),f.IPv6.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let o=0;for(;o<16;)i.push(parseInt(r[o],10)|255^parseInt(n[o],10)),o++;return new this(i)}catch(t){throw new Error("ipaddr: the address does not have IPv6 CIDR format (".concat(t,")"))}},f.IPv6.isIPv6=function(e){return null!==this.parser(e)},f.IPv6.isValid=function(e){if("string"===typeof e&&-1===e.indexOf(":"))return!1;try{const t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch(t){return!1}},f.IPv6.networkAddressFromCIDR=function(e){let t,r,n,i,o;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),o=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<16;)i.push(parseInt(n[r],10)&parseInt(o[r],10)),r++;return new this(i)}catch(s){throw new Error("ipaddr: the address does not have IPv6 CIDR format (".concat(s,")"))}},f.IPv6.parse=function(e){const t=this.parser(e);if(null===t.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(t.parts,t.zoneId)},f.IPv6.parseCIDR=function(e){let t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]),t>=0&&t<=128))return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},f.IPv6.parser=function(e){let t,r,n,i,o,s;if(n=e.match(c.deprecatedTransitional))return this.parser("::ffff:".concat(n[1]));if(c.native.test(e))return l(e,8);if((n=e.match(c.transitional))&&(s=n[6]||"",t=l(n[1].slice(0,-1)+s,6),t.parts)){for(o=[parseInt(n[2]),parseInt(n[3]),parseInt(n[4]),parseInt(n[5])],r=0;r128)throw new Error("ipaddr: invalid IPv6 prefix length");const t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r{e.exports=function(){return"undefined"!==typeof window&&"object"===typeof window.process&&"renderer"===window.process.type||(!("undefined"===typeof process||"object"!==typeof process.versions||!process.versions.electron)||"object"===typeof navigator&&"string"===typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}},6791:(e,t,r)=>{"use strict";const{URLWithLegacySupport:n,format:i,URLSearchParams:o,defaultBase:s}=r(5732),a=r(9640);e.exports={URL:n,URLSearchParams:o,format:i,relative:a,defaultBase:s}},9640:(e,t,r)=>{"use strict";const{URLWithLegacySupport:n,format:i}=r(5732);e.exports=function(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0,a=r.protocol?r.protocol.replace(":",""):"http";a=(o[a]||s||a)+":";try{t=new n(e)}catch(l){t={}}const c=Object.assign({},r,{protocol:a||t.protocol,host:r.host||t.host});return new n(e,i(c)).toString()}},5732:e=>{"use strict";const t="undefined"!==typeof navigator&&"ReactNative"===navigator.product;const r=self.URL,n=t?"http://localhost":self.location?self.location.protocol+"//"+self.location.host:"";e.exports={URLWithLegacySupport:class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n;this.super=new r(e,t),this.path=this.pathname+this.search,this.auth=this.username&&this.password?this.username+":"+this.password:null,this.query=this.search&&this.search.startsWith("?")?this.search.slice(1):null}get hash(){return this.super.hash}get host(){return this.super.host}get hostname(){return this.super.hostname}get href(){return this.super.href}get origin(){return this.super.origin}get password(){return this.super.password}get pathname(){return this.super.pathname}get port(){return this.super.port}get protocol(){return this.super.protocol}get search(){return this.super.search}get searchParams(){return this.super.searchParams}get username(){return this.super.username}set hash(e){this.super.hash=e}set host(e){this.super.host=e}set hostname(e){this.super.hostname=e}set href(e){this.super.href=e}set password(e){this.super.password=e}set pathname(e){this.super.pathname=e}set port(e){this.super.port=e}set protocol(e){this.super.protocol=e}set search(e){this.super.search=e}set username(e){this.super.username=e}static createObjectURL(e){return r.createObjectURL(e)}static revokeObjectURL(e){r.revokeObjectURL(e)}toJSON(){return this.super.toJSON()}toString(){return this.super.toString()}format(){return this.toString()}},URLSearchParams:self.URLSearchParams,defaultBase:n,format:function(e){if("string"===typeof e){return new r(e).toString()}if(!(e instanceof r)){const t=e.username&&e.password?"".concat(e.username,":").concat(e.password,"@"):"",r=e.auth?e.auth+"@":"",n=e.port?":"+e.port:"",i=e.protocol?e.protocol+"//":"",o=e.host||"",s=e.hostname||"",a=e.search||(e.query?"?"+e.query:""),c=e.hash||"",l=e.pathname||"",u=e.path||l+a;return"".concat(i).concat(t||r).concat(o||s+n).concat(u).concat(c)}}}},464:e=>{"use strict";e.exports=async e=>{const t=[];for await(const r of e)t.push(r);return t}},9272:e=>{"use strict";e.exports=async e=>{for await(const t of e);}},2393:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)await t(r)&&(yield r)}},4744:e=>{"use strict";e.exports=async e=>{for await(const t of e)return t}},1309:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)await t(r),yield r}},7889:e=>{"use strict";e.exports=async function*(e,t){for await(const r of e)yield t(r)}},6155:(e,t,r)=>{"use strict";const n=r(9202);e.exports=async function*(){for(var e=arguments.length,t=new Array(e),r=0;r{try{await Promise.all(t.map((async e=>{for await(const t of e)i.push(t)}))),i.end()}catch(e){i.end(e)}}),0),yield*i}},9202:(e,t,r)=>{const n=r(5125);e.exports=e=>{let t;"function"===typeof(e=e||{})?(t=e,e={}):t=e.onEnd;let r,i,o,s=new n;const a=e=>i?i(e):(s.push(e),r),c=e=>o?r:a({done:!1,value:e}),l=e=>o?r:(o=!0,e?(e=>(s=new n,i?i({error:e}):(s.push({error:e}),r)))(e):a({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:()=>{if(!s.isEmpty()){if(e.writev){let e;const t=[];for(;!s.isEmpty();){if(e=s.shift(),e.error)throw e.error;t.push(e.value)}return{done:e.done,value:t}}const t=s.shift();if(t.error)throw t.error;return t}return o?{done:!0}:new Promise(((t,n)=>{i=o=>(i=null,o.error?n(o.error):e.writev&&!o.done?t({done:o.done,value:[o.value]}):t(o),r)}))},return:()=>(s=new n,l(),{done:!0}),throw:e=>(l(e),{done:!0}),push:c,end:l},!t)return r;const u=r;return r={[Symbol.asyncIterator](){return this},next:()=>u.next(),throw:e=>(u.throw(e),t&&(t(e),t=null),{done:!0}),return:()=>(u.return(),t&&(t(),t=null),{done:!0}),push:c,end:e=>(u.end(e),t&&(t(e),t=null),r)},r}},2035:(e,t,r)=>{"use strict";const n=r(464);e.exports=async function*(e,t){const r=await n(e);yield*r.sort(t)}},5959:e=>{"use strict";e.exports=async function*(e,t){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}},7898:(e,t,r)=>{var n;!function(){"use strict";var i="input is invalid type",o="object"===typeof window,s=o?window:{};s.JS_SHA3_NO_WINDOW&&(o=!1);var a=!o&&"object"===typeof self;!s.JS_SHA3_NO_NODE_JS&&"object"===typeof process&&process.versions&&process.versions.node?s=r.g:a&&(s=self);var c=!s.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!s.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!==typeof ArrayBuffer,d="0123456789abcdef".split(""),h=[4,1024,262144,67108864],f=[0,8,16,24],p=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],v={128:168,256:136};!s.JS_SHA3_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!u||!s.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"===typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});for(var b=function(e,t,r){return function(n){return new x(e,t,e).update(n)[r]()}},w=function(e,t,r){return function(n,i){return new x(e,t,i).update(n)[r]()}},E=function(e,t,r){return function(t,n,i,o){return I["cshake"+e].update(t,n,i,o)[r]()}},S=function(e,t,r){return function(t,n,i,o){return I["kmac"+e].update(t,n,i,o)[r]()}},_=function(e,t,r,n){for(var i=0;i>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function L(e,t,r){x.call(this,e,t,r)}x.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(i);if(null===e)throw new Error(i);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!u||!ArrayBuffer.isView(e)))throw new Error(i);t=!0}for(var n,o,s=this.blocks,a=this.byteCount,c=e.length,l=this.blockCount,d=0,h=this.s;d>2]|=e[d]<>2]|=o<>2]|=(192|o>>6)<>2]|=(128|63&o)<=57344?(s[n>>2]|=(224|o>>12)<>2]|=(128|o>>6&63)<>2]|=(128|63&o)<>2]|=(240|o>>18)<>2]|=(128|o>>12&63)<>2]|=(128|o>>6&63)<>2]|=(128|63&o)<=a){for(this.start=n-a,this.block=s[l],n=0;n>=8);r>0;)i.unshift(r),r=255&(e>>=8),++n;return t?i.push(n):i.unshift(n),this.update(i),i.length},x.prototype.encodeString=function(e){var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(i);if(null===e)throw new Error(i);if(u&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!u||!ArrayBuffer.isView(e)))throw new Error(i);t=!0}var n=0,o=e.length;if(t)n=o;else for(var s=0;s=57344?n+=3:(a=65536+((1023&a)<<10|1023&e.charCodeAt(++s)),n+=4)}return n+=this.encode(8*n),this.update(e),n},x.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+d[15&e]+d[e>>12&15]+d[e>>8&15]+d[e>>20&15]+d[e>>16&15]+d[e>>28&15]+d[e>>24&15];s%t===0&&(M(r),o=0)}return i&&(e=r[o],a+=d[e>>4&15]+d[15&e],i>1&&(a+=d[e>>12&15]+d[e>>8&15]),i>2&&(a+=d[e>>20&15]+d[e>>16&15])),a},x.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,o=0,s=0,a=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);s>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r===0&&M(n)}return o&&(e=a<<2,t=n[s],c[e]=255&t,o>1&&(c[e+1]=t>>8&255),o>2&&(c[e+2]=t>>16&255)),c},L.prototype=new x,L.prototype.finalize=function(){return this.encode(this.outputBits,!0),x.prototype.finalize.call(this)};var M=function(e){var t,r,n,i,o,s,a,c,l,u,d,h,f,g,y,m,v,b,w,E,S,_,C,T,I,A,k,R,P,D,N,O,x,L,M,B,U,F,V,K,j,z,q,H,W,G,Q,$,Y,X,J,Z,ee,te,re,ne,ie,oe,se,ae,ce,le,ue;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],s=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],d=e[7]^e[17]^e[27]^e[37]^e[47],t=(h=e[8]^e[18]^e[28]^e[38]^e[48])^(s<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|s>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|l>>>31),r=o^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=s^(u<<1|d>>>31),r=a^(d<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(h<<1|f>>>31),r=l^(f<<1|h>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(i<<1|o>>>31),r=d^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],y=e[1],G=e[11]<<4|e[10]>>>28,Q=e[10]<<4|e[11]>>>28,R=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,q=e[41]<<18|e[40]>>>14,L=e[2]<<1|e[3]>>>31,M=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,$=e[22]<<10|e[23]>>>22,Y=e[23]<<10|e[22]>>>22,D=e[33]<<13|e[32]>>>19,N=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,B=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,b=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,X=e[34]<<15|e[35]>>>17,J=e[35]<<15|e[34]>>>17,O=e[45]<<29|e[44]>>>3,x=e[44]<<29|e[45]>>>3,T=e[6]<<28|e[7]>>>4,I=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,V=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,H=e[8]<<27|e[9]>>>5,W=e[9]<<27|e[8]>>>5,A=e[18]<<20|e[19]>>>12,k=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,se=e[28]<<7|e[29]>>>25,K=e[38]<<8|e[39]>>>24,j=e[39]<<8|e[38]>>>24,_=e[48]<<14|e[49]>>>18,C=e[49]<<14|e[48]>>>18,e[0]=g^~m&b,e[1]=y^~v&w,e[10]=T^~A&R,e[11]=I^~k&P,e[20]=L^~B&F,e[21]=M^~U&V,e[30]=H^~G&$,e[31]=W^~Q&Y,e[40]=te^~ne&oe,e[41]=re^~ie&se,e[2]=m^~b&E,e[3]=v^~w&S,e[12]=A^~R&D,e[13]=k^~P&N,e[22]=B^~F&K,e[23]=U^~V&j,e[32]=G^~$&X,e[33]=Q^~Y&J,e[42]=ne^~oe&ae,e[43]=ie^~se&ce,e[4]=b^~E&_,e[5]=w^~S&C,e[14]=R^~D&O,e[15]=P^~N&x,e[24]=F^~K&z,e[25]=V^~j&q,e[34]=$^~X&Z,e[35]=Y^~J&ee,e[44]=oe^~ae&le,e[45]=se^~ce&ue,e[6]=E^~_&g,e[7]=S^~C&y,e[16]=D^~O&T,e[17]=N^~x&I,e[26]=K^~z&L,e[27]=j^~q&M,e[36]=X^~Z&H,e[37]=J^~ee&W,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=_^~g&m,e[9]=C^~y&v,e[18]=O^~T&A,e[19]=x^~I&k,e[28]=z^~L&B,e[29]=q^~M&U,e[38]=Z^~H&G,e[39]=ee^~W&Q,e[48]=le^~te&ne,e[49]=ue^~re&ie,e[0]^=p[n],e[1]^=p[n+1]};if(c)e.exports=I;else{for(k=0;kObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},l=e=>{const t=[];for(const r in e)i.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)o.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{s(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{s(t,r,u(e[r]))})),t}(e):e}const d=(e,t,r,n)=>(r.forEach((r=>{"undefined"===typeof t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?s(e,r,h(e[r],t[r],n)):s(e,r,u(t[r])))})),e);function h(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?((e,t,r)=>{let n=e.slice(0,0),o=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!a.includes(e))),r)})),n})(e,t,r):n(t)&&n(e)?d(e,t,l(t),r):u(t)}e.exports=function(){const e=h(u(c),this!==a&&this||{},c);let t={_:{}};for(var r=arguments.length,i=new Array(r),o=0;o{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},8193:e=>{var t=1e3,r=60*t,n=60*r,i=24*n,o=7*i,s=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*o;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var o=Math.abs(e);if(o>=i)return a(e,o,i,"day");if(o>=n)return a(e,o,n,"hour");if(o>=r)return a(e,o,r,"minute");if(o>=t)return a(e,o,t,"second");return e+" ms"}(e):function(e){var o=Math.abs(e);if(o>=i)return Math.round(e/i)+"d";if(o>=n)return Math.round(e/n)+"h";if(o>=r)return Math.round(e/r)+"m";if(o>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},486:e=>{"use strict";function t(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,i,o,s,a;for(t=[],i=o=0;o<=3&&0!==e.length;i=++o){if(i>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}s=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(s)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},i=(n=function(e){return e.charCodeAt(0)})("0"),s=n("a"),o=n("A"),r=function(e){var t,r,a,c,l;for(c=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),l=a;a>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-s)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-o)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,i;if("string"!==typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"===typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(o){throw o,new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(o){throw o,new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"===typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},8605:(e,t,r)=>{var n=r(392);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.aes.Algorithm(e,t)}))}r(3397),r(4533),r(3877),e.exports=n.aes=n.aes||{},n.aes.startEncrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!1,mode:n});return i.start(t),i},n.aes.createEncryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!1,mode:t})},n.aes.startDecrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!0,mode:n});return i.start(t),i},n.aes.createDecryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!0,mode:t})},n.aes.Algorithm=function(e,t){u||d();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return f(r._w,e,t,!1)},decrypt:function(e,t){return f(r._w,e,t,!0)}}}),r._init=!1},n.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!==typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(n.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=n.util.createBuffer();for(var i=0;i>>=2;for(i=0;i>8^255&d^99,o[g]=d,s[d]=g,f=(h=e[d])<<24^d<<16^d<<8^d^h,p=((r=e[g])^(n=e[r])^(i=e[n]))<<24^(g^i)<<16^(g^n^i)<<8^g^r^i;for(var m=0;m<4;++m)c[m][g]=f,l[m][d]=p,f=f<<24|f>>>8,p=p<<24|p>>>8;0===g?g=y=1:(g=r^e[e[e[r^i]]],y^=e[e[y]])}}function h(e,t){for(var r,n=e.slice(0),i=1,s=n.length,c=4*(s+6+1),u=s;u>>16&255]<<24^o[r>>>8&255]<<16^o[255&r]<<8^o[r>>>24]^a[i]<<24,i++):s>6&&u%s===4&&(r=o[r>>>24]<<24^o[r>>>16&255]<<16^o[r>>>8&255]<<8^o[255&r]),n[u]=n[u-s]^r;if(t){for(var d,h=l[0],f=l[1],p=l[2],g=l[3],y=n.slice(0),m=(u=0,(c=n.length)-4);u>>24]]^f[o[d>>>16&255]]^p[o[d>>>8&255]]^g[o[255&d]];n=y}return n}function f(e,t,r,n){var i,a,u,d,h,f,p,g,y,m,v,b,w=e.length/4-1;n?(i=l[0],a=l[1],u=l[2],d=l[3],h=s):(i=c[0],a=c[1],u=c[2],d=c[3],h=o),f=t[0]^e[0],p=t[n?3:1]^e[1],g=t[2]^e[2],y=t[n?1:3]^e[3];for(var E=3,S=1;S>>24]^a[p>>>16&255]^u[g>>>8&255]^d[255&y]^e[++E],v=i[p>>>24]^a[g>>>16&255]^u[y>>>8&255]^d[255&f]^e[++E],b=i[g>>>24]^a[y>>>16&255]^u[f>>>8&255]^d[255&p]^e[++E],y=i[y>>>24]^a[f>>>16&255]^u[p>>>8&255]^d[255&g]^e[++E],f=m,p=v,g=b;r[0]=h[f>>>24]<<24^h[p>>>16&255]<<16^h[g>>>8&255]<<8^h[255&y]^e[++E],r[n?3:1]=h[p>>>24]<<24^h[g>>>16&255]<<16^h[y>>>8&255]<<8^h[255&f]^e[++E],r[2]=h[g>>>24]<<24^h[y>>>16&255]<<16^h[f>>>8&255]<<8^h[255&p]^e[++E],r[n?1:3]=h[y>>>24]<<24^h[f>>>16&255]<<16^h[p>>>8&255]<<8^h[255&g]^e[++E]}function p(e){var t,r="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var o=null;r instanceof n.util.ByteBuffer&&(o=r,r={}),(r=r||{}).output=o,r.iv=e,i.call(t,r)},t}},5049:(e,t,r)=>{var n=r(392);r(3877),r(2886);var i=e.exports=n.asn1=n.asn1||{};function o(e,t,r){if(r>t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}i.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},i.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},i.create=function(e,t,r,o,s){if(n.util.isArray(o)){for(var a=[],c=0;ct){if(n.strict){var p=new Error("Too few bytes to read ASN.1 value.");throw p.available=e.length(),p.remaining=t,p.requested=f,p}f=t}var g=32===(32&c);if(g)if(d=[],void 0===f)for(;;){if(o(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}a=e.length(),d.push(s(e,t,r+1,n)),t-=a-e.length()}else for(;f>0;)a=e.length(),d.push(s(e,f,r+1,n)),t-=a-e.length(),f-=a-e.length();if(void 0===d&&l===i.Class.UNIVERSAL&&u===i.Type.BITSTRING&&(h=e.bytes(f)),void 0===d&&n.decodeBitStrings&&l===i.Class.UNIVERSAL&&u===i.Type.BITSTRING&&f>1){var y=e.read,m=t,v=0;if(u===i.Type.BITSTRING&&(o(e,t,1),v=e.getByte(),t--),0===v)try{a=e.length();var b=s(e,t,r+1,{strict:!0,decodeBitStrings:!0}),w=a-e.length();t-=w,u==i.Type.BITSTRING&&w++;var E=b.tagClass;w!==f||E!==i.Class.UNIVERSAL&&E!==i.Class.CONTEXT_SPECIFIC||(d=[b])}catch(_){}void 0===d&&(e.read=y,t=m)}if(void 0===d){if(void 0===f){if(n.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");f=t}if(u===i.Type.BMPSTRING)for(d="";f>0;f-=2)o(e,t,2),d+=String.fromCharCode(e.getInt16()),t-=2;else d=e.getBytes(f),t-=f}var S=void 0===h?null:{bitStringContents:h};return i.create(l,u,g,d,S)}i.fromDer=function(e,t){void 0===t&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"===typeof t&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.length(),i=s(e,e.length(),0,t);if(t.parseAllBytes&&0!==e.length()){var o=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw o.byteCount=r,o.remaining=e.length(),o}return i},i.toDer=function(e){var t=n.util.createBuffer(),r=e.tagClass|e.type,o=n.util.createBuffer(),s=!1;if("bitStringContents"in e&&(s=!0,e.original&&(s=i.equals(e,e.original))),s)o.putBytes(e.bitStringContents);else if(e.composed){e.constructed?r|=32:o.putByte(0);for(var a=0;a1&&(0===e.value.charCodeAt(0)&&0===(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128===(128&e.value.charCodeAt(1)))?o.putBytes(e.value.substr(1)):o.putBytes(e.value);if(t.putByte(r),o.length()<=127)t.putByte(127&o.length());else{var c=o.length(),l="";do{l+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|l.length);for(a=l.length-1;a>=0;--a)t.putByte(l.charCodeAt(a))}return t.putBuffer(o),t},i.oidToDer=function(e){var t,r,i,o,s=e.split("."),a=n.util.createBuffer();a.putByte(40*parseInt(s[0],10)+parseInt(s[1],10));for(var c=2;c>>=7,t||(o|=128),r.push(o),t=!1}while(i>0);for(var l=r.length-1;l>=0;--l)a.putByte(r[l])}return a},i.derToOid=function(e){var t;"string"===typeof e&&(e=n.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var i=0;e.length()>0;)i<<=7,128&(r=e.getByte())?i+=127&r:(t+="."+(i+r),i=0);return t},i.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),o=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),l=10;"+"!==c&&"-"!==c&&(a=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(r,n,i),t.setUTCHours(o,s,a,0),l&&("+"===(c=e.charAt(l))||"-"===c)){var u=60*parseInt(e.substr(l+1,2),10)+parseInt(e.substr(l+4,2),10);u*=6e4,"+"===c?t.setTime(+t-u):t.setTime(+t+u)}return t},i.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),o=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,l=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var d=e.length-5,h=e.charAt(d);"+"!==h&&"-"!==h||(l=60*parseInt(e.substr(d+1,2),10)+parseInt(e.substr(d+4,2),10),l*=6e4,"+"===h&&(l*=-1),u=!0);return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(r,n,i),t.setUTCHours(o,s,a,c),t.setTime(+t+l)):(t.setFullYear(r,n,i),t.setHours(o,s,a,c)),t},i.dateToUtcTime=function(e){if("string"===typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},i.derToInteger=function(e){"string"===typeof e&&(e=n.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},i.validate=function(e,t,r,o){var s=!1;if(e.tagClass!==t.tagClass&&"undefined"!==typeof t.tagClass||e.type!==t.type&&"undefined"!==typeof t.type)o&&(e.tagClass!==t.tagClass&&o.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&o.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||"undefined"===typeof t.constructed){if(s=!0,t.value&&n.util.isArray(t.value))for(var a=0,c=0;s&&c0&&(o+="\n");for(var s="",c=0;c1?o+="0x"+n.util.bytesToHex(e.value.slice(1)):o+="(none)",e.value.length>0){var h=e.value.charCodeAt(0);1==h?o+=" (1 unused bit shown)":h>1&&(o+=" ("+h+" unused bits shown)")}}else if(e.type===i.Type.OCTETSTRING)a.test(e.value)||(o+="("+e.value+") "),o+="0x"+n.util.bytesToHex(e.value);else if(e.type===i.Type.UTF8)try{o+=n.util.decodeUtf8(e.value)}catch(p){if("URI malformed"!==p.message)throw p;o+="0x"+n.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===i.Type.PRINTABLESTRING||e.type===i.Type.IA5String?o+=e.value:a.test(e.value)?o+="0x"+n.util.bytesToHex(e.value):0===e.value.length?o+="[null]":o+=e.value}return o}},5754:e=>{var t={};e.exports=t;var r={};t.encode=function(e,t,r){if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==r&&"number"!==typeof r)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var i=0,o=t.length,s=t.charAt(0),a=[0];for(i=0;i0;)a.push(l%o),l=l/o|0}for(i=0;0===e[i]&&i=0;--i)n+=t[a[i]]}else n=function(e,t){var r=0,n=t.length,i=t.charAt(0),o=[0];for(r=0;r0;)o.push(a%n),a=a/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[o[r]];return c}(e,t);if(r){var u=new RegExp(".{1,"+r+"}","g");n=n.match(u).join("\r\n")}return n},t.decode=function(e,t){if("string"!==typeof e)throw new TypeError('"input" must be a string.');if("string"!==typeof t)throw new TypeError('"alphabet" must be a string.');var n=r[t];if(!n){n=r[t]=[];for(var i=0;i>=8;for(;u>0;)a.push(255&u),u>>=8}for(var d=0;e[d]===s&&d{var n=r(392);r(3877),e.exports=n.cipher=n.cipher||{},n.cipher.algorithms=n.cipher.algorithms||{},n.cipher.createCipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!1})},n.cipher.createDecipher=function(e,t){var r=e;if("string"===typeof r&&(r=n.cipher.getAlgorithm(r))&&(r=r()),!r)throw new Error("Unsupported algorithm: "+e);return new n.cipher.BlockCipher({algorithm:r,key:t,decrypt:!0})},n.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),n.cipher.algorithms[e]=t},n.cipher.getAlgorithm=function(e){return(e=e.toUpperCase())in n.cipher.algorithms?n.cipher.algorithms[e]:null};var i=n.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};i.prototype.start=function(e){e=e||{};var t={};for(var r in e)t[r]=e[r];t.decrypt=this._decrypt,this._finish=!1,this._input=n.util.createBuffer(),this.output=e.output||n.util.createBuffer(),this.mode.start(t)},i.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},i.prototype.finish=function(e){!e||"ECB"!==this.mode.name&&"CBC"!==this.mode.name||(this.mode.pad=function(t){return e(this.blockSize,t,!1)},this.mode.unpad=function(t){return e(this.blockSize,t,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t))&&(this._finish=!0,this.update(),!(this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))&&!(this.mode.afterFinish&&!this.mode.afterFinish(this.output,t)))}},4533:(e,t,r)=>{var n=r(392);r(3877),n.cipher=n.cipher||{};var i=e.exports=n.cipher.modes=n.cipher.modes||{};function o(e,t){if("string"===typeof e&&(e=n.util.createBuffer(e)),n.util.isArray(e)&&e.length>4){var r=e;e=n.util.createBuffer();for(var i=0;i0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},i.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=o(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},i.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},i.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=o(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=o(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0)e.read-=this.blockSize;else for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},i.ofb.prototype.decrypt=i.ofb.prototype.encrypt,i.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0},i.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=o(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},i.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}s(this._inBlock)},i.ctr.prototype.decrypt=i.ctr.prototype.encrypt,i.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=n.util.createBuffer(),this._partialBytes=0,this._R=3774873600},i.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,r=n.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?n.util.createBuffer(e.additionalData):n.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=n.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var i=r.length();if(12===i)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(a(8*i)))}this._inBlock=this._j0.slice(0),s(this._inBlock),this._partialBytes=0,t=n.util.createBuffer(t),this._aDataLength=a(8*t.length());var o=t.length()%this.blockSize;for(o&&t.fillWithByte(0,this.blockSize-o),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},i.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(o=this.blockSize-o),this._partialOutput.clear();for(i=0;i0&&this._partialOutput.getBytes(this._partialBytes),o>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),s(this._inBlock)},i.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),s(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},i.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=e[r/8|0]>>>4*(7-r%8)&15,i=this._m[r][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},i.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},i.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,i=16*r,o=new Array(i),s=0;s>>1,i=new Array(r);i[n]=e.slice(0);for(var o=n>>>1;o>0;)this.pow(i[2*o],i[o]=[]),o>>=1;for(o=2;o{var n=r(392);function i(e,t){n.cipher.registerAlgorithm(e,(function(){return new n.des.Algorithm(e,t)}))}r(3397),r(4533),r(3877),e.exports=n.des=n.des||{},n.des.startEncrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createEncryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!1,mode:t})},n.des.startDecrypting=function(e,t,r,n){var i=p({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return i.start(t),i},n.des.createDecryptionCipher=function(e,t){return p({key:e,output:null,decrypt:!0,mode:t})},n.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return f(r._keys,e,t,!1)},decrypt:function(e,t){return f(r._keys,e,t,!0)}}}),r._init=!1},n.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=n.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=function(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],i=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],o=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],d=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],h=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],p=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],g=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],y=e.length()>8?3:1,m=[],v=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],b=0,w=0;w>>4^S))<<4,E^=t=65535&((S^=t)>>>-16^E),E^=(t=858993459&(E>>>2^(S^=t<<-16)))<<2,E^=t=65535&((S^=t)>>>-16^E),E^=(t=1431655765&(E>>>1^(S^=t<<-16)))<<1,E^=t=16711935&((S^=t)>>>8^E),t=(E^=(t=1431655765&(E>>>1^(S^=t<<8)))<<1)<<8|(S^=t)>>>20&240,E=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var _=0;_>>26,S=S<<2|S>>>26):(E=E<<1|E>>>27,S=S<<1|S>>>27),S&=-15;var C=r[(E&=-15)>>>28]|n[E>>>24&15]|i[E>>>20&15]|o[E>>>16&15]|s[E>>>12&15]|a[E>>>8&15]|c[E>>>4&15],T=l[S>>>28]|u[S>>>24&15]|d[S>>>20&15]|h[S>>>16&15]|f[S>>>12&15]|p[S>>>8&15]|g[S>>>4&15];t=65535&(T>>>16^C),m[b++]=C^t,m[b++]=T^t<<16}}return m}(t),this._init=!0}},i("DES-ECB",n.cipher.modes.ecb),i("DES-CBC",n.cipher.modes.cbc),i("DES-CFB",n.cipher.modes.cfb),i("DES-OFB",n.cipher.modes.ofb),i("DES-CTR",n.cipher.modes.ctr),i("3DES-ECB",n.cipher.modes.ecb),i("3DES-CBC",n.cipher.modes.cbc),i("3DES-CFB",n.cipher.modes.cfb),i("3DES-OFB",n.cipher.modes.ofb),i("3DES-CTR",n.cipher.modes.ctr);var o=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],s=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],a=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],c=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],l=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],u=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],d=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],h=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function f(e,t,r,n){var i,f,p=32===e.length?3:9;i=3===p?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],y=t[1];g^=(f=252645135&(g>>>4^y))<<4,g^=(f=65535&(g>>>16^(y^=f)))<<16,g^=f=858993459&((y^=f)>>>2^g),g^=f=16711935&((y^=f<<2)>>>8^g),g=(g^=(f=1431655765&(g>>>1^(y^=f<<8)))<<1)<<1|g>>>31,y=(y^=f)<<1|y>>>31;for(var m=0;m>>4|y<<28)^e[w+1];f=g,g=y,y=f^(s[E>>>24&63]|c[E>>>16&63]|u[E>>>8&63]|h[63&E]|o[S>>>24&63]|a[S>>>16&63]|l[S>>>8&63]|d[63&S])}f=g,g=y,y=f}y=y>>>1|y<<31,y^=f=1431655765&((g=g>>>1|g<<31)>>>1^y),y^=(f=16711935&(y>>>8^(g^=f<<1)))<<8,y^=(f=858993459&(y>>>2^(g^=f)))<<2,y^=f=65535&((g^=f)>>>16^y),y^=f=252645135&((g^=f<<16)>>>4^y),g^=f<<4,r[0]=g,r[1]=y}function p(e){var t,r="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),i=(t=e.decrypt?n.cipher.createDecipher(r,e.key):n.cipher.createCipher(r,e.key)).start;return t.start=function(e,r){var o=null;r instanceof n.util.ByteBuffer&&(o=r,r={}),(r=r||{}).output=o,r.iv=e,i.call(t,r)},t}},392:e=>{e.exports={options:{usePureJavaScript:!1}}},878:(e,t,r)=>{var n=r(392);r(29),r(3877),(e.exports=n.hmac=n.hmac||{}).create=function(){var e=null,t=null,r=null,i=null,o={start:function(o,s){if(null!==o)if("string"===typeof o){if(!((o=o.toLowerCase())in n.md.algorithms))throw new Error('Unknown hash algorithm "'+o+'"');t=n.md.algorithms[o].create()}else t=o;if(null===s)s=e;else{if("string"===typeof s)s=n.util.createBuffer(s);else if(n.util.isArray(s)){var a=s;s=n.util.createBuffer();for(var c=0;ct.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),r=n.util.createBuffer(),i=n.util.createBuffer(),l=s.length();for(c=0;c{var n,i=r(392);e.exports=i.jsbn=i.jsbn||{};function o(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function s(){return new o(null)}function a(e,t,r,n,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var c=16383&this.data[e],l=this.data[e++]>>14,u=a*c+l*s;i=((c=s*c+((16383&u)<<14)+r.data[n]+i)>>28)+(u>>14)+a*l,r.data[n++]=268435455&c}return i}i.jsbn.BigInteger=o,"undefined"===typeof navigator?(o.prototype.am=a,n=28):"Microsoft Internet Explorer"==navigator.appName?(o.prototype.am=function(e,t,r,n,i,o){for(var s=32767&t,a=t>>15;--o>=0;){var c=32767&this.data[e],l=this.data[e++]>>15,u=a*c+l*s;i=((c=s*c+((32767&u)<<15)+r.data[n]+(1073741823&i))>>>30)+(u>>>15)+a*l+(i>>>30),r.data[n++]=1073741823&c}return i},n=30):"Netscape"!=navigator.appName?(o.prototype.am=function(e,t,r,n,i,o){for(;--o>=0;){var s=t*this.data[e++]+r.data[n]+i;i=Math.floor(s/67108864),r.data[n++]=67108863&s}return i},n=26):(o.prototype.am=a,n=28),o.prototype.DB=n,o.prototype.DM=(1<>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function g(e){this.m=e}function y(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function _(){}function C(e){return e}function T(e){this.r2=s(),this.q3=s(),o.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}g.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},y.prototype.convert=function(e){var t=s();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(o.ZERO)>0&&this.m.subTo(t,t),t},y.prototype.revert=function(e){var t=s();return e.copyTo(t),this.reduce(t),t},y.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},y.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},o.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},o.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},o.prototype.fromString=function(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,s=0;--n>=0;){var a=8==r?255&e[n]:h(e,n);a<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==s?this.data[this.t++]=a:s+r>this.DB?(this.data[this.t-1]|=(a&(1<>this.DB-s):this.data[this.t-1]|=a<=this.DB&&(s-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},o.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s},o.prototype.drShiftTo=function(e,t){for(var r=e;r=0;--r)t.data[r+s+1]=this.data[r]>>i|a,a=(this.data[r]&o)<=0;--r)t.data[r]=0;t.data[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()},o.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,o=(1<>n;for(var s=r+1;s>n;n>0&&(t.data[this.t-r-1]|=(this.s&o)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()},o.prototype.multiplyTo=function(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()},o.prototype.divRemTo=function(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(u,a),i.lShiftTo(u,r)):(n.copyTo(a),i.copyTo(r));var d=a.t,h=a.data[d-1];if(0!=h){var f=h*(1<1?a.data[d-2]>>this.F2:0),g=this.FV/f,y=(1<=0&&(r.data[r.t++]=1,r.subTo(w,r)),o.ONE.dlShiftTo(d,w),w.subTo(a,a);a.t=0;){var E=r.data[--v]==h?this.DM:Math.floor(r.data[v]*g+(r.data[v-1]+m)*y);if((r.data[v]+=a.am(0,E,r,b,0,d))0&&r.rShiftTo(u,r),c<0&&o.ZERO.subTo(r,r)}}},o.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},o.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},o.prototype.exp=function(e,t){if(e>4294967295||e<1)return o.ONE;var r=s(),n=s(),i=t.convert(this),a=p(e)-1;for(i.copyTo(r);--a>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var c=r;r=n,n=c}return t.revert(r)},o.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,o=d(r));s>=0;)a>(a+=this.DB-t)):(r=this.data[s]>>(a-=t)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=d(r));return i?o:"0"},o.prototype.negate=function(){var e=s();return o.ZERO.subTo(this,e),e},o.prototype.abs=function(){return this.s<0?this.negate():this},o.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0},o.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+p(this.data[this.t-1]^this.s&this.DM)},o.prototype.mod=function(e){var t=s();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(o.ZERO)>0&&e.subTo(t,t),t},o.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new g(t):new y(t),this.exp(e,r)},o.ZERO=f(0),o.ONE=f(1),_.prototype.convert=C,_.prototype.revert=C,_.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},_.prototype.sqrTo=function(e,t){e.squareTo(t)},T.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=s();return e.copyTo(t),this.reduce(t),t},T.prototype.revert=function(e){return e},T.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},T.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},T.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var I=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],A=(1<<26)/I[I.length-1];o.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},o.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=f(r),i=s(),o=s(),a="";for(this.divRemTo(n,i,o);i.signum()>0;)a=(r+o.intValue()).toString(e).substr(1)+a,i.divRemTo(n,i,o);return o.intValue().toString(e)+a},o.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,s=0,a=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(a,0),s=0,a=0))}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(a,0)),i&&o.ZERO.subTo(this,this)},o.prototype.fromNumber=function(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(o.ONE.shiftLeft(e-1),v,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(o.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()},o.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},o.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},o.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r.data[--i]=0;for(n=r.t-this.t;i=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n0)if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r},o.prototype.millerRabin=function(e){var t=this.subtract(o.ONE),r=t.getLowestSetBit();if(r<=0)return!1;for(var n,i=t.shiftRight(r),s={nextBytes:function(e){for(var t=0;t=0);var c=n.modPow(i,this);if(0!=c.compareTo(o.ONE)&&0!=c.compareTo(t)){for(var l=1;l++>24},o.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},o.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},o.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},o.prototype.equals=function(e){return 0==this.compareTo(e)},o.prototype.min=function(e){return this.compareTo(e)<0?this:e},o.prototype.max=function(e){return this.compareTo(e)>0?this:e},o.prototype.and=function(e){var t=s();return this.bitwiseTo(e,m,t),t},o.prototype.or=function(e){var t=s();return this.bitwiseTo(e,v,t),t},o.prototype.xor=function(e){var t=s();return this.bitwiseTo(e,b,t),t},o.prototype.andNot=function(e){var t=s();return this.bitwiseTo(e,w,t),t},o.prototype.not=function(){for(var e=s(),t=0;t=this.t?0!=this.s:0!=(this.data[t]&1<1){var d=s();for(n.sqrTo(a[1],d);c<=u;)a[c]=s(),n.mulTo(d,a[c-2],a[c]),c+=2}var h,m,v=e.t-1,b=!0,w=s();for(i=p(e.data[v])-1;v>=0;){for(i>=l?h=e.data[v]>>i-l&u:(h=(e.data[v]&(1<0&&(h|=e.data[v-1]>>this.DB+i-l)),c=r;0==(1&h);)h>>=1,--c;if((i-=c)<0&&(i+=this.DB,--v),b)a[h].copyTo(o),b=!1;else{for(;c>1;)n.sqrTo(o,w),n.sqrTo(w,o),c-=2;c>0?n.sqrTo(o,w):(m=o,o=w,w=m),n.mulTo(w,a[h],o)}for(;v>=0&&0==(e.data[v]&1<=0?(r.subTo(n,r),t&&i.subTo(a,i),s.subTo(c,s)):(n.subTo(r,n),t&&a.subTo(i,a),c.subTo(s,c))}return 0!=n.compareTo(o.ONE)?o.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},o.prototype.pow=function(e){return this.exp(e,new _)},o.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)return t;for(i0&&(t.rShiftTo(o,t),r.rShiftTo(o,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r},o.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=I[I.length-1]){for(t=0;t{var n=r(392);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},1746:(e,t,r)=>{var n=r(392);r(7263),e.exports=n.mgf=n.mgf||{},n.mgf.mgf1=n.mgf1},7263:(e,t,r)=>{var n=r(392);r(3877),n.mgf=n.mgf||{},(e.exports=n.mgf.mgf1=n.mgf1=n.mgf1||{}).create=function(e){return{generate:function(t,r){for(var i=new n.util.ByteBuffer,o=Math.ceil(r/e.digestLength),s=0;s{var n=r(392);n.pki=n.pki||{};var i=e.exports=n.pki.oids=n.oids=n.oids||{};function o(e,t){i[e]=t,i[t]=e}function s(e,t){i[e]=t}o("1.2.840.113549.1.1.1","rsaEncryption"),o("1.2.840.113549.1.1.4","md5WithRSAEncryption"),o("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),o("1.2.840.113549.1.1.7","RSAES-OAEP"),o("1.2.840.113549.1.1.8","mgf1"),o("1.2.840.113549.1.1.9","pSpecified"),o("1.2.840.113549.1.1.10","RSASSA-PSS"),o("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),o("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),o("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),o("1.3.101.112","EdDSA25519"),o("1.2.840.10040.4.3","dsa-with-sha1"),o("1.3.14.3.2.7","desCBC"),o("1.3.14.3.2.26","sha1"),o("1.3.14.3.2.29","sha1WithRSASignature"),o("2.16.840.1.101.3.4.2.1","sha256"),o("2.16.840.1.101.3.4.2.2","sha384"),o("2.16.840.1.101.3.4.2.3","sha512"),o("2.16.840.1.101.3.4.2.4","sha224"),o("2.16.840.1.101.3.4.2.5","sha512-224"),o("2.16.840.1.101.3.4.2.6","sha512-256"),o("1.2.840.113549.2.2","md2"),o("1.2.840.113549.2.5","md5"),o("1.2.840.113549.1.7.1","data"),o("1.2.840.113549.1.7.2","signedData"),o("1.2.840.113549.1.7.3","envelopedData"),o("1.2.840.113549.1.7.4","signedAndEnvelopedData"),o("1.2.840.113549.1.7.5","digestedData"),o("1.2.840.113549.1.7.6","encryptedData"),o("1.2.840.113549.1.9.1","emailAddress"),o("1.2.840.113549.1.9.2","unstructuredName"),o("1.2.840.113549.1.9.3","contentType"),o("1.2.840.113549.1.9.4","messageDigest"),o("1.2.840.113549.1.9.5","signingTime"),o("1.2.840.113549.1.9.6","counterSignature"),o("1.2.840.113549.1.9.7","challengePassword"),o("1.2.840.113549.1.9.8","unstructuredAddress"),o("1.2.840.113549.1.9.14","extensionRequest"),o("1.2.840.113549.1.9.20","friendlyName"),o("1.2.840.113549.1.9.21","localKeyId"),o("1.2.840.113549.1.9.22.1","x509Certificate"),o("1.2.840.113549.1.12.10.1.1","keyBag"),o("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),o("1.2.840.113549.1.12.10.1.3","certBag"),o("1.2.840.113549.1.12.10.1.4","crlBag"),o("1.2.840.113549.1.12.10.1.5","secretBag"),o("1.2.840.113549.1.12.10.1.6","safeContentsBag"),o("1.2.840.113549.1.5.13","pkcs5PBES2"),o("1.2.840.113549.1.5.12","pkcs5PBKDF2"),o("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),o("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),o("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),o("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),o("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),o("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),o("1.2.840.113549.2.7","hmacWithSHA1"),o("1.2.840.113549.2.8","hmacWithSHA224"),o("1.2.840.113549.2.9","hmacWithSHA256"),o("1.2.840.113549.2.10","hmacWithSHA384"),o("1.2.840.113549.2.11","hmacWithSHA512"),o("1.2.840.113549.3.7","des-EDE3-CBC"),o("2.16.840.1.101.3.4.1.2","aes128-CBC"),o("2.16.840.1.101.3.4.1.22","aes192-CBC"),o("2.16.840.1.101.3.4.1.42","aes256-CBC"),o("2.5.4.3","commonName"),o("2.5.4.4","surname"),o("2.5.4.5","serialNumber"),o("2.5.4.6","countryName"),o("2.5.4.7","localityName"),o("2.5.4.8","stateOrProvinceName"),o("2.5.4.9","streetAddress"),o("2.5.4.10","organizationName"),o("2.5.4.11","organizationalUnitName"),o("2.5.4.12","title"),o("2.5.4.13","description"),o("2.5.4.15","businessCategory"),o("2.5.4.17","postalCode"),o("2.5.4.42","givenName"),o("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),o("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),o("2.16.840.1.113730.1.1","nsCertType"),o("2.16.840.1.113730.1.13","nsComment"),s("2.5.29.1","authorityKeyIdentifier"),s("2.5.29.2","keyAttributes"),s("2.5.29.3","certificatePolicies"),s("2.5.29.4","keyUsageRestriction"),s("2.5.29.5","policyMapping"),s("2.5.29.6","subtreesConstraint"),s("2.5.29.7","subjectAltName"),s("2.5.29.8","issuerAltName"),s("2.5.29.9","subjectDirectoryAttributes"),s("2.5.29.10","basicConstraints"),s("2.5.29.11","nameConstraints"),s("2.5.29.12","policyConstraints"),s("2.5.29.13","basicConstraints"),o("2.5.29.14","subjectKeyIdentifier"),o("2.5.29.15","keyUsage"),s("2.5.29.16","privateKeyUsagePeriod"),o("2.5.29.17","subjectAltName"),o("2.5.29.18","issuerAltName"),o("2.5.29.19","basicConstraints"),s("2.5.29.20","cRLNumber"),s("2.5.29.21","cRLReason"),s("2.5.29.22","expirationDate"),s("2.5.29.23","instructionCode"),s("2.5.29.24","invalidityDate"),s("2.5.29.25","cRLDistributionPoints"),s("2.5.29.26","issuingDistributionPoint"),s("2.5.29.27","deltaCRLIndicator"),s("2.5.29.28","issuingDistributionPoint"),s("2.5.29.29","certificateIssuer"),s("2.5.29.30","nameConstraints"),o("2.5.29.31","cRLDistributionPoints"),o("2.5.29.32","certificatePolicies"),s("2.5.29.33","policyMappings"),s("2.5.29.34","policyConstraints"),o("2.5.29.35","authorityKeyIdentifier"),s("2.5.29.36","policyConstraints"),o("2.5.29.37","extKeyUsage"),s("2.5.29.46","freshestCRL"),s("2.5.29.54","inhibitAnyPolicy"),o("1.3.6.1.4.1.11129.2.4.2","timestampList"),o("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),o("1.3.6.1.5.5.7.3.1","serverAuth"),o("1.3.6.1.5.5.7.3.2","clientAuth"),o("1.3.6.1.5.5.7.3.3","codeSigning"),o("1.3.6.1.5.5.7.3.4","emailProtection"),o("1.3.6.1.5.5.7.3.8","timeStamping")},9835:(e,t,r)=>{var n=r(392);if(r(8605),r(5049),r(1400),r(29),r(2886),r(6019),r(6193),r(3860),r(654),r(5493),r(3877),"undefined"===typeof i)var i=n.jsbn.BigInteger;var o=n.asn1,s=n.pki=n.pki||{};e.exports=s.pbe=n.pbe=n.pbe||{};var a=s.oids,c={name:"EncryptedPrivateKeyInfo",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},l={name:"PBES2Algorithms",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:o.Class.UNIVERSAL,type:o.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},u={name:"pkcs-12PbeParams",tagClass:o.Class.UNIVERSAL,type:o.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:o.Class.UNIVERSAL,type:o.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:o.Class.UNIVERSAL,type:o.Type.INTEGER,constructed:!1,capture:"iterations"}]};function d(e,t){return e.start().update(t).digest().getBytes()}function h(e){var t;if(e){if(!(t=s.oids[o.derToOid(e)])){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}}else t="hmacWithSHA1";return f(t)}function f(e){var t=n.md;switch(e){case"hmacWithSHA224":t=n.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}s.encryptPrivateKeyInfo=function(e,t,r){(r=r||{}).saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var i,c,l,u=n.random.getBytesSync(r.saltSize),d=r.count,h=o.integerToDer(d);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var p,g,y;switch(r.algorithm){case"aes128":i=16,p=16,g=a["aes128-CBC"],y=n.aes.createEncryptionCipher;break;case"aes192":i=24,p=16,g=a["aes192-CBC"],y=n.aes.createEncryptionCipher;break;case"aes256":i=32,p=16,g=a["aes256-CBC"],y=n.aes.createEncryptionCipher;break;case"des":i=8,p=8,g=a.desCBC,y=n.des.createEncryptionCipher;break;default:throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S}var m="hmacWith"+r.prfAlgorithm.toUpperCase(),v=f(m),b=n.pkcs5.pbkdf2(t,u,d,i,v),w=n.random.getBytesSync(p);(_=y(b)).start(w),_.update(o.toDer(e)),_.finish(),l=_.output.getBytes();var E=function(e,t,r,i){var a=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,e),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,t.getBytes())]);"hmacWithSHA1"!==i&&a.value.push(o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,n.util.hexToBytes(r.toString(16))),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(s.oids[i]).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.NULL,!1,"")]));return a}(u,h,i,m);c=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(a.pkcs5PBES2).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(a.pkcs5PBKDF2).getBytes()),E]),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(g).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,w)])])])}else{var S;if("3des"!==r.algorithm)throw(S=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=r.algorithm,S;i=24;var _,C=new n.util.ByteBuffer(u);b=s.pbe.generatePkcs12Key(t,C,1,d,i),w=s.pbe.generatePkcs12Key(t,C,2,d,i);(_=n.des.createEncryptionCipher(b)).start(w),_.update(o.toDer(e)),_.finish(),l=_.output.getBytes(),c=o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OID,!1,o.oidToDer(a["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,u),o.create(o.Class.UNIVERSAL,o.Type.INTEGER,!1,h.getBytes())])])}return o.create(o.Class.UNIVERSAL,o.Type.SEQUENCE,!0,[c,o.create(o.Class.UNIVERSAL,o.Type.OCTETSTRING,!1,l)])},s.decryptPrivateKeyInfo=function(e,t){var r=null,i={},a=[];if(!o.validate(e,c,i,a)){var l=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=a,l}var u=o.derToOid(i.encryptionOid),d=s.pbe.getCipher(u,i.encryptionParams,t),h=n.util.createBuffer(i.encryptedData);return d.update(h),d.finish()&&(r=o.fromDer(d.output)),r},s.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:o.toDer(e).getBytes()};return n.pem.encode(r,{maxline:t})},s.encryptedPrivateKeyFromPem=function(e){var t=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==t.type){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return o.fromDer(t.body)},s.encryptRsaPrivateKey=function(e,t,r){if(!(r=r||{}).legacy){var i=s.wrapRsaPrivateKey(s.privateKeyToAsn1(e));return i=s.encryptPrivateKeyInfo(i,t,r),s.encryptedPrivateKeyToPem(i)}var a,c,l,u;switch(r.algorithm){case"aes128":a="AES-128-CBC",l=16,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes192":a="AES-192-CBC",l=24,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"aes256":a="AES-256-CBC",l=32,c=n.random.getBytesSync(16),u=n.aes.createEncryptionCipher;break;case"3des":a="DES-EDE3-CBC",l=24,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;case"des":a="DES-CBC",l=8,c=n.random.getBytesSync(8),u=n.des.createEncryptionCipher;break;default:var d=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw d.algorithm=r.algorithm,d}var h=u(n.pbe.opensslDeriveBytes(t,c.substr(0,8),l));h.start(c),h.update(o.toDer(s.privateKeyToAsn1(e))),h.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:a,parameters:n.util.bytesToHex(c).toUpperCase()},body:h.output.getBytes()};return n.pem.encode(f)},s.decryptRsaPrivateKey=function(e,t){var r=null,i=n.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==i.type&&"PRIVATE KEY"!==i.type&&"RSA PRIVATE KEY"!==i.type)throw(l=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=l,l;if(i.procType&&"ENCRYPTED"===i.procType.type){var a,c;switch(i.dekInfo.algorithm){case"DES-CBC":a=8,c=n.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,c=n.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,c=n.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,c=n.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,c=n.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,c=function(e){return n.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":a=8,c=function(e){return n.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":a=16,c=function(e){return n.rc2.createDecryptionCipher(e,128)};break;default:var l;throw(l=new Error('Could not decrypt private key; unsupported encryption algorithm "'+i.dekInfo.algorithm+'".')).algorithm=i.dekInfo.algorithm,l}var u=n.util.hexToBytes(i.dekInfo.parameters),d=c(n.pbe.opensslDeriveBytes(t,u.substr(0,8),a));if(d.start(u),d.update(n.util.createBuffer(i.body)),!d.finish())return r;r=d.output.getBytes()}else r=i.body;return null!==(r="ENCRYPTED PRIVATE KEY"===i.type?s.decryptPrivateKeyInfo(o.fromDer(r),t):o.fromDer(r))&&(r=s.privateKeyFromAsn1(r)),r},s.pbe.generatePkcs12Key=function(e,t,r,i,o,s){var a,c;if("undefined"===typeof s||null===s){if(!("sha1"in n.md))throw new Error('"sha1" hash algorithm unavailable.');s=n.md.sha1.create()}var l=s.digestLength,u=s.blockLength,d=new n.util.ByteBuffer,h=new n.util.ByteBuffer;if(null!==e&&void 0!==e){for(c=0;c=0;c--)R>>=8,R+=T.at(c)+k.at(c),k.setAt(c,255&R);A.putBuffer(k)}w=A,d.putBuffer(_)}return d.truncate(d.length()-o),d},s.pbe.getCipher=function(e,t,r){switch(e){case s.oids.pkcs5PBES2:return s.pbe.getCipherForPBES2(e,t,r);case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case s.oids["pbewithSHAAnd40BitRC2-CBC"]:return s.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},s.pbe.getCipherForPBES2=function(e,t,r){var i,a={},c=[];if(!o.validate(t,l,a,c))throw(i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=c,i;if((e=o.derToOid(a.kdfOid))!==s.oids.pkcs5PBKDF2)throw(i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,i.supportedOids=["pkcs5PBKDF2"],i;if((e=o.derToOid(a.encOid))!==s.oids["aes128-CBC"]&&e!==s.oids["aes192-CBC"]&&e!==s.oids["aes256-CBC"]&&e!==s.oids["des-EDE3-CBC"]&&e!==s.oids.desCBC)throw(i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i;var u,d,f=a.kdfSalt,p=n.util.createBuffer(a.kdfIterationCount);switch(p=p.getInt(p.length()<<3),s.oids[e]){case"aes128-CBC":u=16,d=n.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,d=n.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,d=n.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,d=n.des.createDecryptionCipher;break;case"desCBC":u=8,d=n.des.createDecryptionCipher}var g=h(a.prfOid),y=n.pkcs5.pbkdf2(r,f,p,u,g),m=a.encIv,v=d(y);return v.start(m),v},s.pbe.getCipherForPKCS12PBE=function(e,t,r){var i={},a=[];if(!o.validate(t,u,i,a))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=a,g;var c,l,d,f=n.util.createBuffer(i.salt),p=n.util.createBuffer(i.iterations);switch(p=p.getInt(p.length()<<3),e){case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,l=8,d=n.des.startDecrypting;break;case s.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,l=8,d=function(e,t){var r=n.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var y=h(i.prfOid),m=s.pbe.generatePkcs12Key(r,f,1,p,c,y);return y.start(),d(m,s.pbe.generatePkcs12Key(r,f,2,p,l,y))},s.pbe.opensslDeriveBytes=function(e,t,r,i){if("undefined"===typeof i||null===i){if(!("md5"in n.md))throw new Error('"md5" hash algorithm unavailable.');i=n.md.md5.create()}null===t&&(t="");for(var o=[d(i,e+t)],s=16,a=1;s{var n=r(392);r(878),r(29),r(3877);var i,o=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(i=r(5819)),e.exports=n.pbkdf2=o.pbkdf2=function(e,t,r,o,s,a){if("function"===typeof s&&(a=s,s=null),n.util.isNodejs&&!n.options.usePureJavaScript&&i.pbkdf2&&(null===s||"object"!==typeof s)&&(i.pbkdf2Sync.length>4||!s||"sha1"===s))return"string"!==typeof s&&(s="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),a?4===i.pbkdf2Sync.length?i.pbkdf2(e,t,r,o,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):i.pbkdf2(e,t,r,o,s,(function(e,t){if(e)return a(e);a(null,t.toString("binary"))})):4===i.pbkdf2Sync.length?i.pbkdf2Sync(e,t,r,o).toString("binary"):i.pbkdf2Sync(e,t,r,o,s).toString("binary");if("undefined"!==typeof s&&null!==s||(s="sha1"),"string"===typeof s){if(!(s in n.md.algorithms))throw new Error("Unknown hash algorithm: "+s);s=n.md[s].create()}var c=s.digestLength;if(o>4294967295*c){var l=new Error("Derived key is too long.");if(a)return a(l);throw l}var u=Math.ceil(o/c),d=o-(u-1)*c,h=n.hmac.create();h.start(s,e);var f,p,g,y="";if(!a){for(var m=1;m<=u;++m){h.start(null,null),h.update(t),h.update(n.util.int32ToBytes(m)),f=g=h.digest().getBytes();for(var v=2;v<=r;++v)h.start(null,null),h.update(g),p=h.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p;y+=mu)return a(null,y);h.start(null,null),h.update(t),h.update(n.util.int32ToBytes(m)),f=g=h.digest().getBytes(),v=2,w()}function w(){if(v<=r)return h.start(null,null),h.update(g),p=h.digest().getBytes(),f=n.util.xorBytes(f,p,c),g=p,++v,n.util.setImmediate(w);y+=m{var n=r(392);r(3877);var i=e.exports=n.pem=n.pem||{};function o(e){for(var t=e.name+": ",r=[],n=function(e,t){return" "+t},i=0;i65&&-1!==s){var a=t[s];","===a?(++s,t=t.substr(0,s)+"\r\n "+t.substr(s)):t=t.substr(0,s)+"\r\n"+a+t.substr(s+1),o=i-s-1,s=-1,++i}else" "!==t[i]&&"\t"!==t[i]&&","!==t[i]||(s=i);return t}function s(e){return e.replace(/^\s+/,"")}i.encode=function(e,t){t=t||{};var r,i="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(i+=o(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(i+=o(r={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),i+=o(r)),e.headers)for(var s=0;s{var n=r(392);r(3877),r(3860),r(928);var i=e.exports=n.pkcs1=n.pkcs1||{};function o(e,t,r){r||(r=n.md.sha1.create());for(var i="",o=Math.ceil(t/r.digestLength),s=0;s>24&255,s>>16&255,s>>8&255,255&s);r.start(),r.update(e+a),i+=r.digest().getBytes()}return i.substring(0,t)}i.encode_rsa_oaep=function(e,t,r){var i,s,a,c;"string"===typeof r?(i=r,s=arguments[3]||void 0,a=arguments[4]||void 0):r&&(i=r.label||void 0,s=r.seed||void 0,a=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),a?a.start():a=n.md.sha1.create(),c||(c=a);var l=Math.ceil(e.n.bitLength()/8),u=l-2*a.digestLength-2;if(t.length>u)throw(y=new Error("RSAES-OAEP input message length is too long.")).length=t.length,y.maxLength=u,y;i||(i=""),a.update(i,"raw");for(var d=a.digest(),h="",f=u-t.length,p=0;p{var n=r(392);r(8605),r(5049),r(1400),r(2886),r(6193),r(4922),r(3860),r(3877),r(3391);var i=n.asn1,o=e.exports=n.pkcs7=n.pkcs7||{};function s(e){var t={},r=[];if(!i.validate(e,o.asn1.recipientInfoValidator,t,r)){var s=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw s.errors=r,s}return{version:t.version.charCodeAt(0),issuer:n.pki.RDNAttributesAsArray(t.issuer),serialNumber:n.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:i.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function a(e){for(var t,r=[],o=0;o0){for(var r=i.create(i.Class.CONTEXT_SPECIFIC,1,!0,[]),o=0;o=r&&s0&&s.value[0].value.push(i.create(i.Class.CONTEXT_SPECIFIC,0,!0,t)),o.length>0&&s.value[0].value.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,o)),s.value[0].value.push(i.create(i.Class.UNIVERSAL,i.Type.SET,!0,e.signerInfos)),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.type).getBytes()),s])},addSigner:function(t){var r=t.issuer,i=t.serialNumber;if(t.certificate){var o=t.certificate;"string"===typeof o&&(o=n.pki.certificateFromPem(o)),r=o.issuer.attributes,i=o.serialNumber}var s=t.key;if(!s)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"===typeof s&&(s=n.pki.privateKeyFromPem(s));var a=t.digestAlgorithm||n.pki.oids.sha1;switch(a){case n.pki.oids.sha1:case n.pki.oids.sha256:case n.pki.oids.sha384:case n.pki.oids.sha512:case n.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+a)}var c=t.authenticatedAttributes||[];if(c.length>0){for(var l=!1,u=!1,d=0;d{var n=r(392);r(5049),r(3877);var i=n.asn1,o=e.exports=n.pkcs7asn1=n.pkcs7asn1||{};n.pkcs7=n.pkcs7||{},n.pkcs7.asn1=o;var s={name:"ContentInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};o.contentInfoValidator=s;var a={name:"EncryptedContentInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};o.envelopedDataValidator={name:"EnvelopedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(a)},o.encryptedDataValidator={name:"EncryptedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"}].concat(a)};var c={name:"SignerInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};o.signedDataValidator={name:"SignedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},s,{name:"SignedData.Certificates",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,capture:"signerInfos",optional:!0,value:[c]}]},o.recipientInfoValidator={name:"RecipientInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},5132:(e,t,r)=>{var n=r(392);r(3877),r(3055),r(3860),function(){if(n.prime)e.exports=n.prime;else{var t=e.exports=n.prime=n.prime||{},r=n.jsbn.BigInteger,i=[6,4,2,4,2,4,6,2],o=new r(null);o.fromInt(30);var s=function(e,t){return e|t};t.generateProbablePrime=function(e,t,i){"function"===typeof t&&(i=t,t={});var o=(t=t||{}).algorithm||"PRIMEINC";"string"===typeof o&&(o={name:o}),o.options=o.options||{};var s=t.prng||n.random,c={nextBytes:function(e){for(var t=s.getBytesSync(e.length),r=0;re&&(s=l(e,t));var f=s.toString(16);i.target.postMessage({hex:f,workLoad:u}),s.dAddOffset(d,0)}}}f()}(e,t,i,o);return a(e,t,i,o)}(e,c,o.options,i);throw new Error("Invalid prime generation algorithm: "+o.name)}}function a(e,t,r,n){var i=l(e,t),o=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(i.bitLength());"millerRabinTests"in r&&(o=r.millerRabinTests);var s=10;"maxBlockTime"in r&&(s=r.maxBlockTime),c(i,e,t,0,o,s,n)}function c(e,t,r,o,s,a,u){var d=+new Date;do{if(e.bitLength()>t&&(e=l(t,r)),e.isProbablePrime(s))return u(null,e);e.dAddOffset(i[o++%8],0)}while(a<0||+new Date-d{var n=r(392);r(3877);var i=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(i=r(5819)),(e.exports=n.prng=n.prng||{}).create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},r=e.md,o=new Array(32),s=0;s<32;++s)o[s]=r.create();function a(){if(t.pools[0].messageLength>=32)return c();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),c()}function c(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var r=1,n=0;n<32;++n)t.reseeds%r===0&&(e.update(t.pools[n].digest().getBytes()),t.pools[n].start()),r<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var i=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(i),t.generated=0}function l(e){var t=null,r=n.util.globalScope,i=r.crypto||r.msCrypto;i&&i.getRandomValues&&(t=function(e){return i.getRandomValues(e)});var o=n.util.createBuffer();if(t)for(;o.length()>16)))<<16,h=4294967295&(u=(2147483647&(u+=l>>15))+(u>>31));for(c=0;c<3;++c)d=h>>>(c<<3),d^=Math.floor(256*Math.random()),o.putByte(255&d)}return o.getBytes(e)}return t.pools=o,t.pool=0,t.generate=function(e,r){if(!r)return t.generateSync(e);var i=t.plugin.cipher,o=t.plugin.increment,s=t.plugin.formatKey,a=t.plugin.formatSeed,l=n.util.createBuffer();t.key=null,function u(d){if(d)return r(d);if(l.length()>=e)return r(null,l.getBytes(e));t.generated>1048575&&(t.key=null);if(null===t.key)return n.util.nextTick((function(){!function(e){if(t.pools[0].messageLength>=32)return c(),e();var r=32-t.pools[0].messageLength<<5;t.seedFile(r,(function(r,n){if(r)return e(r);t.collect(n),c(),e()}))}(u)}));var h=i(t.key,t.seed);t.generated+=h.length,l.putBytes(h),t.key=s(i(t.key,o(t.seed))),t.seed=a(i(t.key,t.seed)),n.util.setImmediate(u)}()},t.generateSync=function(e){var r=t.plugin.cipher,i=t.plugin.increment,o=t.plugin.formatKey,s=t.plugin.formatSeed;t.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(t.key=null),null===t.key&&a();var l=r(t.key,t.seed);t.generated+=l.length,c.putBytes(l),t.key=o(r(t.key,i(t.seed))),t.seed=s(r(t.key,t.seed))}return c.getBytes(e)},i?(t.seedFile=function(e,t){i.randomBytes(e,(function(e,r){if(e)return t(e);t(null,r.toString())}))},t.seedFileSync=function(e){return i.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,l(e))}catch(r){t(r)}},t.seedFileSync=l),t.collect=function(e){for(var r=e.length,n=0;n>i&255);t.collect(n)},t.registerWorker=function(e){if(e===self)t.seedFile=function(e,t){self.addEventListener("message",(function e(r){var n=r.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",e),t(n.forge.prng.err,n.forge.prng.bytes))})),self.postMessage({forge:{prng:{needed:e}}})};else{e.addEventListener("message",(function(r){var n=r.data;n.forge&&n.forge.prng&&t.seedFile(n.forge.prng.needed,(function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})}))}))}},t}},325:(e,t,r)=>{var n=r(392);r(3860),r(3877),(e.exports=n.pss=n.pss||{}).create=function(e){3===arguments.length&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t,r=e.md,i=e.mgf,o=r.digestLength,s=e.salt||null;if("string"===typeof s&&(s=n.util.createBuffer(s)),"saltLength"in e)t=e.saltLength;else{if(null===s)throw new Error("Salt length not specified or specific salt not given.");t=s.length()}if(null!==s&&s.length()!==t)throw new Error("Given salt length does not match length of given salt.");var a=e.prng||n.random,c={encode:function(e,c){var l,u,d=c-1,h=Math.ceil(d/8),f=e.digest().getBytes();if(h>8*h-d&255;return(w=String.fromCharCode(w.charCodeAt(0)&~E)+w.substr(1))+g+String.fromCharCode(188)},verify:function(e,s,a){var c,l=a-1,u=Math.ceil(l/8);if(s=s.substr(-u),u>8*u-l&255;if(0!==(h.charCodeAt(0)&p))throw new Error("Bits beyond keysize not zero as expected.");var g=i.generate(f,d),y="";for(c=0;c{var n=r(392);r(8605),r(7404),r(6140),r(3877),n.random&&n.random.getBytes?e.exports=n.random:function(t){var r={},i=new Array(4),o=n.util.createBuffer();function s(){var e=n.prng.create(r);return e.getBytes=function(t,r){return e.generate(t,r)},e.getBytesSync=function(t){return e.generate(t)},e}r.formatKey=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),n.aes._expandKey(e,!1)},r.formatSeed=function(e){var t=n.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},r.cipher=function(e,t){return n.aes._updateBlock(e,t,i,!1),o.putInt32(i[0]),o.putInt32(i[1]),o.putInt32(i[2]),o.putInt32(i[3]),o.getBytes()},r.increment=function(e){return++e[3],e},r.md=n.md.sha256;var a=s(),c=null,l=n.util.globalScope,u=l.crypto||l.msCrypto;if(u&&u.getRandomValues&&(c=function(e){return u.getRandomValues(e)}),n.options.usePureJavaScript||!n.util.isNodejs&&!c){if("undefined"===typeof window||window.document,a.collectInt(+new Date,32),"undefined"!==typeof navigator){var d="";for(var h in navigator)try{"string"==typeof navigator[h]&&(d+=navigator[h])}catch(f){}a.collect(d),d=null}t&&(t().mousemove((function(e){a.collectInt(e.clientX,16),a.collectInt(e.clientY,16)})),t().keypress((function(e){a.collectInt(e.charCode,8)})))}if(n.random)for(var h in a)n.random[h]=a[h];else n.random=a;n.random.createInstance=s,e.exports=n.random}("undefined"!==typeof jQuery?jQuery:null)},654:(e,t,r)=>{var n=r(392);r(3877);var i=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],o=[1,2,3,5],s=function(e,t){return e<>16-t},a=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"===typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,o=e,s=e.length(),a=t,c=Math.ceil(a/8),l=255>>(7&a);for(r=s;r<128;r++)o.putByte(i[o.at(r-1)+o.at(r-s)&255]);for(o.setAt(128-c,i[o.at(128-c)&l]),r=127-c;r>=0;r--)o.setAt(r,i[o.at(r+1)^o.at(r+c)]);return o};var c=function(e,t,r){var i,c,l,u,d=!1,h=null,f=null,p=null,g=[];for(e=n.rc2.expandKey(e,t),l=0;l<64;l++)g.push(e.getInt16Le());r?(i=function(e){for(l=0;l<4;l++)e[l]+=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),e[l]=s(e[l],o[l]),u++},c=function(e){for(l=0;l<4;l++)e[l]+=g[63&e[(l+3)%4]]}):(i=function(e){for(l=3;l>=0;l--)e[l]=a(e[l],o[l]),e[l]-=g[u]+(e[(l+3)%4]&e[(l+2)%4])+(~e[(l+3)%4]&e[(l+1)%4]),u--},c=function(e){for(l=3;l>=0;l--)e[l]-=g[63&e[(l+3)%4]]});var y=function(e){var t=[];for(l=0;l<4;l++){var n=h.getInt16Le();null!==p&&(r?n^=p.getInt16Le():p.putInt16Le(n)),t.push(65535&n)}u=r?0:63;for(var i=0;i=8;)y([[5,i],[1,c],[6,i],[1,c],[5,i]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,h,!r);else{var n=8===h.length()?8:8-h.length();h.fillWithByte(n,n)}if(t&&(d=!0,m.update()),!r&&(t=0===h.length()))if(e)t=e(8,f,!r);else{var i=f.length(),o=f.at(i-1);o>i?t=!1:f.truncate(o)}return t}}};n.rc2.startEncrypting=function(e,t,r){var i=n.rc2.createEncryptionCipher(e,128);return i.start(t,r),i},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var i=n.rc2.createDecryptionCipher(e,128);return i.start(t,r),i},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},5493:(e,t,r)=>{var n=r(392);if(r(5049),r(3055),r(2886),r(2627),r(5132),r(3860),r(3877),"undefined"===typeof i)var i=n.jsbn.BigInteger;var o=n.util.isNodejs?r(5819):null,s=n.asn1,a=n.util;n.pki=n.pki||{},e.exports=n.pki.rsa=n.rsa=n.rsa||{};var c=n.pki,l=[6,4,2,4,2,4,6,2],u={name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},d={name:"RSAPrivateKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},h={name:"RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},f=n.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},p={name:"DigestInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){var t;if(!(e.algorithm in c.oids)){var r=new Error("Unknown message digest algorithm.");throw r.algorithm=e.algorithm,r}t=c.oids[e.algorithm];var n=s.oidToDer(t).getBytes(),i=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]),o=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]);o.value.push(s.create(s.Class.UNIVERSAL,s.Type.OID,!1,n)),o.value.push(s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,""));var a=s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(o),i.value.push(a),s.toDer(i).getBytes()},y=function(e,t,r){if(r)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var o;t.dP||(t.dP=t.d.mod(t.p.subtract(i.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(i.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{o=new i(n.util.bytesToHex(n.random.getBytes(t.n.bitLength()/8)),16)}while(o.compareTo(t.n)>=0||!o.gcd(t.n).equals(i.ONE));for(var s=(e=e.multiply(o.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);s.compareTo(a)<0;)s=s.add(t.p);var c=s.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return c=c.multiply(o.modInverse(t.n)).mod(t.n)};function m(e,t,r){var i=n.util.createBuffer(),o=Math.ceil(t.n.bitLength()/8);if(e.length>o-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=e.length,s.max=o-11,s}i.putByte(0),i.putByte(r);var a,c=o-3-e.length;if(0===r||1===r){a=0===r?0:255;for(var l=0;l0;){var u=0,d=n.random.getBytes(c);for(l=0;l1;){if(255!==s.getByte()){--s.read;break}++l}else if(2===c)for(l=0;s.length()>1;){if(0===s.getByte()){--s.read;break}++l}if(0!==s.getByte()||l!==o-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function b(e,t,r){"function"===typeof t&&(r=t,t={});var o={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function s(){a(e.pBits,(function(t,n){return t?r(t):(e.p=n,null!==e.q?l(t,e.q):void a(e.qBits,l))}))}function a(e,t){n.prime.generateProbablePrime(e,o,t)}function l(t,n){if(t)return r(t);if(e.q=n,e.p.compareTo(e.q)<0){var o=e.p;e.p=e.q,e.q=o}if(0!==e.p.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.p=null,void s();if(0!==e.q.subtract(i.ONE).gcd(e.e).compareTo(i.ONE))return e.q=null,void a(e.qBits,l);if(e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(i.ONE))return e.p=e.q=null,void s();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,l);var u=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"prng"in t&&(o.prng=t.prng),s()}function w(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=n.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0===(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128===(128&r.charCodeAt(1)))?r.substr(1):r}function E(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function S(e){return n.util.isNodejs&&"function"===typeof o[e]}function _(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.crypto&&"object"===typeof a.globalScope.crypto.subtle&&"function"===typeof a.globalScope.crypto.subtle[e]}function C(e){return"undefined"!==typeof a.globalScope&&"object"===typeof a.globalScope.msCrypto&&"object"===typeof a.globalScope.msCrypto.subtle&&"function"===typeof a.globalScope.msCrypto.subtle[e]}function T(e){for(var t=n.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),i=0;i0;)u.putByte(0),--d;return u.putBytes(n.util.hexToBytes(l)),u.getBytes()},c.rsa.decrypt=function(e,t,r,o){var s=Math.ceil(t.n.bitLength()/8);if(e.length!==s){var a=new Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=s,a}var c=new i(n.util.createBuffer(e).toHex(),16);if(c.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var l=y(c,t,r).toString(16),u=n.util.createBuffer(),d=s-Math.ceil(l.length/2);d>0;)u.putByte(0),--d;return u.putBytes(n.util.hexToBytes(l)),!1!==o?v(u.getBytes(),t,r):u.getBytes()},c.rsa.createKeyPairGenerationState=function(e,t,r){"string"===typeof e&&(e=parseInt(e,10)),e=e||2048;var o,s=(r=r||{}).prng||n.random,a={nextBytes:function(e){for(var t=s.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(o.eInt),o},c.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new i(null);r.fromInt(30);for(var n,o=0,s=function(e,t){return e|t},a=+new Date,u=0;null===e.keys&&(t<=0||ud?e.pqState=0:e.num.isProbablePrime(E(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(l[o++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(i.ONE).gcd(e.e).compareTo(i.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(i.ONE),e.q1=e.q.subtract(i.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(i.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var f=e.e.modInverse(e.phi);e.keys={privateKey:c.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:c.rsa.setPublicKey(e.n,e.e)}}u+=(n=+new Date)-a,a=n}return null!==e.keys},c.rsa.generateKeyPair=function(e,t,r,i){if(1===arguments.length?"object"===typeof e?(r=e,e=void 0):"function"===typeof e&&(i=e,e=void 0):2===arguments.length?"number"===typeof e?"function"===typeof t?(i=t,t=void 0):"number"!==typeof t&&(r=t,t=void 0):(r=e,i=t,e=void 0,t=void 0):3===arguments.length&&("number"===typeof t?"function"===typeof r&&(i=r,r=void 0):(i=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!n.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(i){if(S("generateKeyPair"))return o.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},(function(e,t,r){if(e)return i(e);i(null,{privateKey:c.privateKeyFromPem(r),publicKey:c.publicKeyFromPem(t)})}));if(_("generateKey")&&_("exportKey"))return a.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:T(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then((function(e){return a.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)})).then(void 0,(function(e){i(e)})).then((function(e){if(e){var t=c.privateKeyFromAsn1(s.fromDer(n.util.createBuffer(e)));i(null,{privateKey:t,publicKey:c.setRsaPublicKey(t.n,t.e)})}}));if(C("generateKey")&&C("exportKey")){var l=a.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:T(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return l.oncomplete=function(e){var t=e.target.result,r=a.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=c.privateKeyFromAsn1(s.fromDer(n.util.createBuffer(t)));i(null,{privateKey:r,publicKey:c.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){i(e)}},void(l.onerror=function(e){i(e)})}}else if(S("generateKeyPairSync")){var u=o.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:c.privateKeyFromPem(u.privateKey),publicKey:c.publicKeyFromPem(u.publicKey)}}var d=c.rsa.createKeyPairGenerationState(e,t,r);if(!i)return c.rsa.stepKeyPairGenerationState(d,0),d.keys;b(d,r,i)},c.setRsaPublicKey=c.rsa.setPublicKey=function(e,t){var r={n:e,e:t,encrypt:function(e,t,i){if("string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return m(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return n.pkcs1.encode_rsa_oaep(t,e,i)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"===typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var o=t.encode(e,r,!0);return c.rsa.encrypt(o,r,!0)},verify:function(e,t,i,o){"string"===typeof i?i=i.toUpperCase():void 0===i&&(i="RSASSA-PKCS1-V1_5"),void 0===o&&(o={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in o||(o._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===i?i={verify:function(e,t){t=v(t,r,!0);var i=s.fromDer(t,{parseAllBytes:o._parseAllDigestBytes}),a={},c=[];if(!s.validate(i,p,a,c))throw(l=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=c,l;var l,u=s.derToOid(a.algorithmIdentifier);if(u!==n.oids.md2&&u!==n.oids.md5&&u!==n.oids.sha1&&u!==n.oids.sha224&&u!==n.oids.sha256&&u!==n.oids.sha384&&u!==n.oids.sha512&&u!==n.oids["sha512-224"]&&u!==n.oids["sha512-256"])throw(l=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=u,l;if((u===n.oids.md2||u===n.oids.md5)&&!("parameters"in a))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return e===a.digest}}:"NONE"!==i&&"NULL"!==i&&null!==i||(i={verify:function(e,t){return e===(t=v(t,r,!0))}});var a=c.rsa.decrypt(t,r,!0,!1);return i.verify(e,a,r.n.bitLength())}};return r},c.setRsaPrivateKey=c.rsa.setPrivateKey=function(e,t,r,i,o,s,a,l){var u={n:e,e:t,d:r,p:i,q:o,dP:s,dQ:a,qInv:l,decrypt:function(e,t,r){"string"===typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var i=c.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:v};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return n.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(i,u,!1)},sign:function(e,t){var r=!1;"string"===typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var n=t.encode(e,u.n.bitLength());return c.rsa.encrypt(n,u,r)}};return u},c.wrapRsaPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(c.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,s.toDer(e).getBytes())])},c.privateKeyFromAsn1=function(e){var t,r,o,a,l,h,f,p,g={},y=[];if(s.validate(e,u,g,y)&&(e=s.fromDer(n.util.createBuffer(g.privateKey))),g={},y=[],!s.validate(e,d,g,y)){var m=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw m.errors=y,m}return t=n.util.createBuffer(g.privateKeyModulus).toHex(),r=n.util.createBuffer(g.privateKeyPublicExponent).toHex(),o=n.util.createBuffer(g.privateKeyPrivateExponent).toHex(),a=n.util.createBuffer(g.privateKeyPrime1).toHex(),l=n.util.createBuffer(g.privateKeyPrime2).toHex(),h=n.util.createBuffer(g.privateKeyExponent1).toHex(),f=n.util.createBuffer(g.privateKeyExponent2).toHex(),p=n.util.createBuffer(g.privateKeyCoefficient).toHex(),c.setRsaPrivateKey(new i(t,16),new i(r,16),new i(o,16),new i(a,16),new i(l,16),new i(h,16),new i(f,16),new i(p,16))},c.privateKeyToAsn1=c.privateKeyToRSAPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.e)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.d)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.p)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.q)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.dP)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.dQ)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.qInv))])},c.publicKeyFromAsn1=function(e){var t={},r=[];if(s.validate(e,f,t,r)){var o,a=s.derToOid(t.publicKeyOid);if(a!==c.oids.rsaEncryption)throw(o=new Error("Cannot read public key. Unknown OID.")).oid=a,o;e=t.rsaPublicKey}if(r=[],!s.validate(e,h,t,r))throw(o=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=r,o;var l=n.util.createBuffer(t.publicKeyModulus).toHex(),u=n.util.createBuffer(t.publicKeyExponent).toHex();return c.setRsaPublicKey(new i(l,16),new i(u,16))},c.publicKeyToAsn1=c.publicKeyToSubjectPublicKeyInfo=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(c.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.BITSTRING,!1,[c.publicKeyToRSAPublicKey(e)])])},c.publicKeyToRSAPublicKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,w(e.e))])}},928:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha1=n.sha1||{};n.md.sha1=n.md.algorithms.sha1=i,i.create=function(){s||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),64),s=!0);var e=null,t=n.util.createBuffer(),r=new Array(80),i={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,o=0;o>>0,c>>>0];for(var l=i.fullMessageLength.length-1;l>=0;--l)i.fullMessageLength[l]+=c[1],c[1]=c[0]+(i.fullMessageLength[l]/4294967296>>>0),i.fullMessageLength[l]=i.fullMessageLength[l]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(o),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var s=n.util.createBuffer();s.putBytes(t.bytes());var c,l=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;s.putBytes(o.substr(0,i.blockLength-l));for(var u=8*i.fullMessageLength[0],d=0;d>>0,s.putInt32(u>>>0),u=c>>>0;s.putInt32(u);var h={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(h,r,s);var f=n.util.createBuffer();return f.putInt32(h.h0),f.putInt32(h.h1),f.putInt32(h.h2),f.putInt32(h.h3),f.putInt32(h.h4),f},i};var o=null,s=!1;function a(e,t,r){for(var n,i,o,s,a,c,l,u=r.length();u>=64;){for(i=e.h0,o=e.h1,s=e.h2,a=e.h3,c=e.h4,l=0;l<16;++l)n=r.getInt32(),t[l]=n,n=(i<<5|i>>>27)+(a^o&(s^a))+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<20;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(i<<5|i>>>27)+(a^o&(s^a))+c+1518500249+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<32;++l)n=(n=t[l-3]^t[l-8]^t[l-14]^t[l-16])<<1|n>>>31,t[l]=n,n=(i<<5|i>>>27)+(o^s^a)+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<40;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(o^s^a)+c+1859775393+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<60;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(o&s|a&(o^s))+c+2400959708+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;for(;l<80;++l)n=(n=t[l-6]^t[l-16]^t[l-28]^t[l-32])<<2|n>>>30,t[l]=n,n=(i<<5|i>>>27)+(o^s^a)+c+3395469782+n,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=n;e.h0=e.h0+i|0,e.h1=e.h1+o|0,e.h2=e.h2+s|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,u-=64}}},7404:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha256=n.sha256||{};n.md.sha256=n.md.algorithms.sha256=i,i.create=function(){s||(o=String.fromCharCode(128),o+=n.util.fillString(String.fromCharCode(0),64),a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=!0);var e=null,t=n.util.createBuffer(),r=new Array(64),i={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){i.messageLength=0,i.fullMessageLength=i.messageLength64=[];for(var r=i.messageLengthSize/4,o=0;o>>0,a>>>0];for(var l=i.fullMessageLength.length-1;l>=0;--l)i.fullMessageLength[l]+=a[1],a[1]=a[0]+(i.fullMessageLength[l]/4294967296>>>0),i.fullMessageLength[l]=i.fullMessageLength[l]>>>0,a[0]=a[1]/4294967296>>>0;return t.putBytes(o),c(e,r,t),(t.read>2048||0===t.length())&&t.compact(),i},i.digest=function(){var s=n.util.createBuffer();s.putBytes(t.bytes());var a,l=i.fullMessageLength[i.fullMessageLength.length-1]+i.messageLengthSize&i.blockLength-1;s.putBytes(o.substr(0,i.blockLength-l));for(var u=8*i.fullMessageLength[0],d=0;d>>0,s.putInt32(u>>>0),u=a>>>0;s.putInt32(u);var h={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};c(h,r,s);var f=n.util.createBuffer();return f.putInt32(h.h0),f.putInt32(h.h1),f.putInt32(h.h2),f.putInt32(h.h3),f.putInt32(h.h4),f.putInt32(h.h5),f.putInt32(h.h6),f.putInt32(h.h7),f},i};var o=null,s=!1,a=null;function c(e,t,r){for(var n,i,o,s,c,l,u,d,h,f,p,g,y,m=r.length();m>=64;){for(c=0;c<16;++c)t[c]=r.getInt32();for(;c<64;++c)n=((n=t[c-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,i=((i=t[c-15])>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[c]=n+t[c-7]+i+t[c-16]|0;for(l=e.h0,u=e.h1,d=e.h2,h=e.h3,f=e.h4,p=e.h5,g=e.h6,y=e.h7,c=0;c<64;++c)o=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),s=l&u|d&(l^u),n=y+((f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7))+(g^f&(p^g))+a[c]+t[c],y=g,g=p,p=f,f=h+n>>>0,h=d,d=u,u=l,l=n+(i=o+s)>>>0;e.h0=e.h0+l|0,e.h1=e.h1+u|0,e.h2=e.h2+d|0,e.h3=e.h3+h|0,e.h4=e.h4+f|0,e.h5=e.h5+p|0,e.h6=e.h6+g|0,e.h7=e.h7+y|0,m-=64}}},4770:(e,t,r)=>{var n=r(392);r(29),r(3877);var i=e.exports=n.sha512=n.sha512||{};n.md.sha512=n.md.algorithms.sha512=i;var o=n.sha384=n.sha512.sha384=n.sha512.sha384||{};o.create=function(){return i.create("SHA-384")},n.md.sha384=n.md.algorithms.sha384=o,n.sha512.sha256=n.sha512.sha256||{create:function(){return i.create("SHA-512/256")}},n.md["sha512/256"]=n.md.algorithms["sha512/256"]=n.sha512.sha256,n.sha512.sha224=n.sha512.sha224||{create:function(){return i.create("SHA-512/224")}},n.md["sha512/224"]=n.md.algorithms["sha512/224"]=n.sha512.sha224,i.create=function(e){if(a||(s=String.fromCharCode(128),s+=n.util.fillString(String.fromCharCode(0),128),c=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],(l={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],l["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],l["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],l["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],a=!0),"undefined"===typeof e&&(e="SHA-512"),!(e in l))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=l[e],r=null,i=n.util.createBuffer(),o=new Array(80),d=0;d<80;++d)o[d]=new Array(2);var h=64;switch(e){case"SHA-384":h=48;break;case"SHA-512/256":h=32;break;case"SHA-512/224":h=28}var f={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:h,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){f.messageLength=0,f.fullMessageLength=f.messageLength128=[];for(var e=f.messageLengthSize/4,o=0;o>>0,s>>>0];for(var a=f.fullMessageLength.length-1;a>=0;--a)f.fullMessageLength[a]+=s[1],s[1]=s[0]+(f.fullMessageLength[a]/4294967296>>>0),f.fullMessageLength[a]=f.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;return i.putBytes(e),u(r,o,i),(i.read>2048||0===i.length())&&i.compact(),f},f.digest=function(){var t=n.util.createBuffer();t.putBytes(i.bytes());var a,c=f.fullMessageLength[f.fullMessageLength.length-1]+f.messageLengthSize&f.blockLength-1;t.putBytes(s.substr(0,f.blockLength-c));for(var l=8*f.fullMessageLength[0],d=0;d>>0,t.putInt32(l>>>0),l=a>>>0;t.putInt32(l);var h=new Array(r.length);for(d=0;d=128;){for(P=0;P<16;++P)t[P][0]=r.getInt32()>>>0,t[P][1]=r.getInt32()>>>0;for(;P<80;++P)n=(((D=(O=t[P-2])[0])>>>19|(N=O[1])<<13)^(N>>>29|D<<3)^D>>>6)>>>0,i=((D<<13|N>>>19)^(N<<3|D>>>29)^(D<<26|N>>>6))>>>0,o=(((D=(L=t[P-15])[0])>>>1|(N=L[1])<<31)^(D>>>8|N<<24)^D>>>7)>>>0,s=((D<<31|N>>>1)^(D<<24|N>>>8)^(D<<25|N>>>7))>>>0,x=t[P-7],M=t[P-16],N=i+x[1]+s+M[1],t[P][0]=n+x[0]+o+M[0]+(N/4294967296>>>0)>>>0,t[P][1]=N>>>0;for(p=e[0][0],g=e[0][1],y=e[1][0],m=e[1][1],v=e[2][0],b=e[2][1],w=e[3][0],E=e[3][1],S=e[4][0],_=e[4][1],C=e[5][0],T=e[5][1],I=e[6][0],A=e[6][1],k=e[7][0],R=e[7][1],P=0;P<80;++P)u=((S>>>14|_<<18)^(S>>>18|_<<14)^(_>>>9|S<<23))>>>0,d=(I^S&(C^I))>>>0,a=((p>>>28|g<<4)^(g>>>2|p<<30)^(g>>>7|p<<25))>>>0,l=((p<<4|g>>>28)^(g<<30|p>>>2)^(g<<25|p>>>7))>>>0,h=(p&y|v&(p^y))>>>0,f=(g&m|b&(g^m))>>>0,N=R+(((S<<18|_>>>14)^(S<<14|_>>>18)^(_<<23|S>>>9))>>>0)+((A^_&(T^A))>>>0)+c[P][1]+t[P][1],n=k+u+d+c[P][0]+t[P][0]+(N/4294967296>>>0)>>>0,i=N>>>0,o=a+h+((N=l+f)/4294967296>>>0)>>>0,s=N>>>0,k=I,R=A,I=C,A=T,C=S,T=_,S=w+n+((N=E+i)/4294967296>>>0)>>>0,_=N>>>0,w=v,E=b,v=y,b=m,y=p,m=g,p=n+o+((N=i+s)/4294967296>>>0)>>>0,g=N>>>0;N=e[0][1]+g,e[0][0]=e[0][0]+p+(N/4294967296>>>0)>>>0,e[0][1]=N>>>0,N=e[1][1]+m,e[1][0]=e[1][0]+y+(N/4294967296>>>0)>>>0,e[1][1]=N>>>0,N=e[2][1]+b,e[2][0]=e[2][0]+v+(N/4294967296>>>0)>>>0,e[2][1]=N>>>0,N=e[3][1]+E,e[3][0]=e[3][0]+w+(N/4294967296>>>0)>>>0,e[3][1]=N>>>0,N=e[4][1]+_,e[4][0]=e[4][0]+S+(N/4294967296>>>0)>>>0,e[4][1]=N>>>0,N=e[5][1]+T,e[5][0]=e[5][0]+C+(N/4294967296>>>0)>>>0,e[5][1]=N>>>0,N=e[6][1]+A,e[6][0]=e[6][0]+I+(N/4294967296>>>0)>>>0,e[6][1]=N>>>0,N=e[7][1]+R,e[7][0]=e[7][0]+k+(N/4294967296>>>0)>>>0,e[7][1]=N>>>0,B-=128}}},3877:(e,t,r)=>{var n=r(392),i=r(5754),o=e.exports=n.util=n.util||{};function s(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"===typeof e)this.data=e;else if(o.isArrayBuffer(e)||o.isArrayBufferView(e))if("undefined"!==typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(n){for(var r=0;r15?(r=Date.now(),s(e)):(t.push(e),1===t.length&&i.setAttribute("a",n=!n))}}o.nextTick=o.setImmediate}(),o.isNodejs="undefined"!==typeof process&&process.versions&&process.versions.node,o.globalScope=o.isNodejs?r.g:"undefined"===typeof self?window:self,o.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},o.isArrayBuffer=function(e){return"undefined"!==typeof ArrayBuffer&&e instanceof ArrayBuffer},o.isArrayBufferView=function(e){return e&&o.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},o.ByteBuffer=a,o.ByteStringBuffer=a;o.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},o.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},o.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},o.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},o.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},o.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},o.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(o.encodeUtf8(e))},o.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},o.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},o.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},o.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},o.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},o.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},o.ByteStringBuffer.prototype.putInt=function(e,t){s(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},o.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},o.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},o.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},o.ByteStringBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},o.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},o.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},o.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},o.ByteStringBuffer.prototype.copy=function(){var e=o.createBuffer(this.data);return e.read=this.read,e},o.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},o.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},o.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},o.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},o.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},o.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},o.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},o.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},o.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},o.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},o.DataBuffer.prototype.putInt=function(e,t){s(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},o.DataBuffer.prototype.putSignedInt=function(e,t){return s(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},o.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},o.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},o.DataBuffer.prototype.bytes=function(e){return"undefined"===typeof e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},o.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},o.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},o.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},o.DataBuffer.prototype.copy=function(){return new o.DataBuffer(this)},o.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},o.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},o.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},o.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},o.xorBytes=function(e,t,r){for(var n="",i="",o="",s=0,a=0;r>0;--r,++s)i=e.charCodeAt(s)^t.charCodeAt(s),a>=10&&(n+=o,o="",a=0),o+=String.fromCharCode(i),++a;return n+=o},o.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],u="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";o.encode64=function(e,t){for(var r,n,i,o="",s="",a=0;a>2),o+=c.charAt((3&r)<<4|n>>4),isNaN(n)?o+="==":(o+=c.charAt((15&n)<<2|i>>6),o+=isNaN(i)?"=":c.charAt(63&i)),t&&o.length>t&&(s+=o.substr(0,t)+"\r\n",o=o.substr(t));return s+=o},o.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,i,o="",s=0;s>4),64!==n&&(o+=String.fromCharCode((15&r)<<4|n>>2),64!==i&&(o+=String.fromCharCode((3&n)<<6|i)));return o},o.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},o.decodeUtf8=function(e){return decodeURIComponent(escape(e))},o.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:i.encode,decode:i.decode}},o.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},o.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,o=0;o>2),o+=c.charAt((3&r)<<4|n>>4),isNaN(n)?o+="==":(o+=c.charAt((15&n)<<2|i>>6),o+=isNaN(i)?"=":c.charAt(63&i)),t&&o.length>t&&(s+=o.substr(0,t)+"\r\n",o=o.substr(t));return s+=o},o.binary.base64.decode=function(e,t,r){var n,i,o,s,a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var c=0,u=r=r||0;c>4,64!==o&&(a[u++]=(15&i)<<4|o>>2,64!==s&&(a[u++]=(3&o)<<6|s));return t?u-r:a.subarray(0,u)},o.binary.base58.encode=function(e,t){return o.binary.baseN.encode(e,u,t)},o.binary.base58.decode=function(e,t){return o.binary.baseN.decode(e,u,t)},o.text={utf8:{},utf16:{}},o.text.utf8.encode=function(e,t,r){e=o.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length));for(var i=r=r||0,s=0;s0&&o.push(r),s=n.lastIndex;var a=t[0][1];switch(a){case"s":case"o":i");break;case"%":o.push("%");break;default:o.push("<%"+a+"?>")}}return o.push(e.substring(s)),o.join("")},o.formatNumber=function(e,t,r,n){var i=e,o=isNaN(t=Math.abs(t))?2:t,s=void 0===r?",":r,a=void 0===n?".":n,c=i<0?"-":"",l=parseInt(i=Math.abs(+i||0).toFixed(o),10)+"",u=l.length>3?l.length%3:0;return c+(u?l.substr(0,u)+a:"")+l.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+a)+(o?s+Math.abs(i-l).toFixed(o).slice(2):"")},o.formatSize=function(e){return e=e>=1073741824?o.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?o.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?o.formatNumber(e/1024,0)+" KiB":o.formatNumber(e,0)+" bytes"},o.bytesFromIP=function(e){return-1!==e.indexOf(".")?o.bytesFromIPv4(e):-1!==e.indexOf(":")?o.bytesFromIPv6(e):null},o.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=o.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:c,end:c})}t.push(s)}if(r.length>0){var l=r[n];l.end-l.start>0&&(t.splice(l.start,l.end-l.start+1,""),0===l.start&&t.unshift(""),7===l.end&&t.push(""))}return t.join(":")},o.estimateCores=function(e,t){if("function"===typeof e&&(t=e,e={}),e=e||{},"cores"in o&&!e.update)return t(null,o.cores);if("undefined"!==typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return o.cores=navigator.hardwareConcurrency,t(null,o.cores);if("undefined"===typeof Worker)return o.cores=1,t(null,o.cores);if("undefined"===typeof Blob)return o.cores=2,t(null,o.cores);var r=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",(function(e){for(var t=Date.now(),r=t+4;Date.now()a.st&&i.sti.st&&a.st{var n=r(392);r(8605),r(5049),r(1400),r(29),r(1746),r(2886),r(6193),r(325),r(5493),r(3877);var i=n.asn1,o=e.exports=n.pki=n.pki||{},s=o.oids,a={};a.CN=s.commonName,a.commonName="CN",a.C=s.countryName,a.countryName="C",a.L=s.localityName,a.localityName="L",a.ST=s.stateOrProvinceName,a.stateOrProvinceName="ST",a.O=s.organizationName,a.organizationName="O",a.OU=s.organizationalUnitName,a.organizationalUnitName="OU",a.E=s.emailAddress,a.emailAddress="E";var c=n.pki.rsa.publicKeyValidator,l={name:"Certificate",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:i.Class.UNIVERSAL,type:i.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:i.Class.UNIVERSAL,type:i.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:i.Class.UNIVERSAL,type:i.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:i.Class.UNIVERSAL,type:i.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},c,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:i.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:i.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},u={name:"rsapss",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:i.Class.UNIVERSAL,type:i.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:i.Class.UNIVERSAL,type:i.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:i.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:i.Class.UNIVERSAL,type:i.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:i.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:i.Class.UNIVERSAL,type:i.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},d={name:"CertificationRequestInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},c,{name:"CertificationRequestInfo.attributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0}]}]}]},h={name:"CertificationRequest",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[d,{name:"CertificationRequest.signatureAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:i.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:i.Class.UNIVERSAL,type:i.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};function f(e,t){"string"===typeof t&&(t={shortName:t});for(var r,n=null,i=0;null===n&&i128)throw new Error('Invalid "nsComment" content.');e.value=i.create(i.Class.UNIVERSAL,i.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&t.cert){var f=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=f.toHex(),e.value=i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,f.getBytes())}else if("authorityKeyIdentifier"===e.name&&t.cert){e.value=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);u=e.value.value;if(e.keyIdentifier){var p=!0===e.keyIdentifier?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;u.push(i.create(i.Class.CONTEXT_SPECIFIC,0,!1,p))}if(e.authorityCertIssuer){var g=[i.create(i.Class.CONTEXT_SPECIFIC,4,!0,[m(!0===e.authorityCertIssuer?t.cert.issuer:e.authorityCertIssuer)])];u.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,g))}if(e.serialNumber){var y=n.util.hexToBytes(!0===e.serialNumber?t.cert.serialNumber:e.serialNumber);u.push(i.create(i.Class.CONTEXT_SPECIFIC,2,!1,y))}}else if("cRLDistributionPoints"===e.name){e.value=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);u=e.value.value;var v,b=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]),w=i.create(i.Class.CONTEXT_SPECIFIC,0,!0,[]);for(h=0;h2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(d.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(c.validity.notBefore=d[0],c.validity.notAfter=d[1],c.tbsCertificate=r.tbsCertificate,t){c.md=g({signatureOid:c.signatureOid,type:"certificate"});var h=i.toDer(c.tbsCertificate);c.md.update(h.getBytes())}var y=n.md.sha1.create(),m=i.toDer(r.certIssuer);y.update(m.getBytes()),c.issuer.getField=function(e){return f(c.issuer,e)},c.issuer.addField=function(e){v([e]),c.issuer.attributes.push(e)},c.issuer.attributes=o.RDNAttributesAsArray(r.certIssuer),r.certIssuerUniqueId&&(c.issuer.uniqueId=r.certIssuerUniqueId),c.issuer.hash=y.digest().toHex();var b=n.md.sha1.create(),w=i.toDer(r.certSubject);return b.update(w.getBytes()),c.subject.getField=function(e){return f(c.subject,e)},c.subject.addField=function(e){v([e]),c.subject.attributes.push(e)},c.subject.attributes=o.RDNAttributesAsArray(r.certSubject),r.certSubjectUniqueId&&(c.subject.uniqueId=r.certSubjectUniqueId),c.subject.hash=b.digest().toHex(),r.certExtensions?c.extensions=o.certificateExtensionsFromAsn1(r.certExtensions):c.extensions=[],c.publicKey=o.publicKeyFromAsn1(r.subjectPublicKeyInfo),c},o.certificateExtensionsFromAsn1=function(e){for(var t=[],r=0;r1&&(r=c.value.charCodeAt(1),o=c.value.length>2?c.value.charCodeAt(2):0),t.digitalSignature=128===(128&r),t.nonRepudiation=64===(64&r),t.keyEncipherment=32===(32&r),t.dataEncipherment=16===(16&r),t.keyAgreement=8===(8&r),t.keyCertSign=4===(4&r),t.cRLSign=2===(2&r),t.encipherOnly=1===(1&r),t.decipherOnly=128===(128&o)}else if("basicConstraints"===t.name){(c=i.fromDer(t.value)).value.length>0&&c.value[0].type===i.Type.BOOLEAN?t.cA=0!==c.value[0].value.charCodeAt(0):t.cA=!1;var a=null;c.value.length>0&&c.value[0].type===i.Type.INTEGER?a=c.value[0].value:c.value.length>1&&(a=c.value[1].value),null!==a&&(t.pathLenConstraint=i.derToInteger(a))}else if("extKeyUsage"===t.name)for(var c=i.fromDer(t.value),l=0;l1&&(r=c.value.charCodeAt(1)),t.client=128===(128&r),t.server=64===(64&r),t.email=32===(32&r),t.objsign=16===(16&r),t.reserved=8===(8&r),t.sslCA=4===(4&r),t.emailCA=2===(2&r),t.objCA=1===(1&r)}else if("subjectAltName"===t.name||"issuerAltName"===t.name){var d;t.altNames=[];c=i.fromDer(t.value);for(var h=0;h=S&&e<_?i.create(i.Class.UNIVERSAL,i.Type.UTCTIME,!1,i.dateToUtcTime(e)):i.create(i.Class.UNIVERSAL,i.Type.GENERALIZEDTIME,!1,i.dateToGeneralizedTime(e))}o.getTBSCertificate=function(e){var t=C(e.validity.notBefore),r=C(e.validity.notAfter),s=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.CONTEXT_SPECIFIC,0,!0,[i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,i.integerToDer(e.version).getBytes())]),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,n.util.hexToBytes(e.serialNumber)),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.siginfo.algorithmOid).getBytes()),w(e.siginfo.algorithmOid,e.siginfo.parameters)]),m(e.issuer),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[t,r]),m(e.subject),o.publicKeyToAsn1(e.publicKey)]);return e.issuer.uniqueId&&s.value.push(i.create(i.Class.CONTEXT_SPECIFIC,1,!0,[i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)])),e.subject.uniqueId&&s.value.push(i.create(i.Class.CONTEXT_SPECIFIC,2,!0,[i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.subject.uniqueId)])),e.extensions.length>0&&s.value.push(o.certificateExtensionsToAsn1(e.extensions)),s},o.getCertificationRequestInfo=function(e){return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,i.integerToDer(e.version).getBytes()),m(e.subject),o.publicKeyToAsn1(e.publicKey),E(e)])},o.distinguishedNameToAsn1=function(e){return m(e)},o.certificateToAsn1=function(e){var t=e.tbsCertificate||o.getTBSCertificate(e);return i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[t,i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(e.signatureOid).getBytes()),w(e.signatureOid,e.signatureParameters)]),i.create(i.Class.UNIVERSAL,i.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},o.certificateExtensionsToAsn1=function(e){var t=i.create(i.Class.CONTEXT_SPECIFIC,3,!0,[]),r=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[]);t.value.push(r);for(var n=0;nu.validity.notAfter)&&(c={message:"Certificate is not valid yet or has expired.",error:o.certificateError.certificate_expired,notBefore:u.validity.notBefore,notAfter:u.validity.notAfter,now:s}),null===c){if(null===(d=t[0]||e.getIssuer(u))&&u.isIssuer(u)&&(h=!0,d=u),d){var f=d;n.util.isArray(f)||(f=[f]);for(var p=!1;!p&&f.length>0;){d=f.shift();try{p=d.verify(u)}catch(S){}}p||(c={message:"Certificate signature is invalid.",error:o.certificateError.bad_certificate})}null!==c||d&&!h||e.hasCertificate(u)||(c={message:"Certificate is not trusted.",error:o.certificateError.unknown_ca})}if(null===c&&d&&!u.isIssuer(d)&&(c={message:"Certificate issuer is invalid.",error:o.certificateError.bad_certificate}),null===c)for(var g={keyUsage:!0,basicConstraints:!0},y=0;null===c&&yv.pathLenConstraint&&(c={message:"Certificate basicConstraints pathLenConstraint violated.",error:o.certificateError.bad_certificate})}var w=null===c||c.error,E=r.verify?r.verify(w,l,i):w;if(!0!==E)throw!0===w&&(c={message:"The application rejected the certificate.",error:o.certificateError.bad_certificate}),(E||0===E)&&("object"!==typeof E||n.util.isArray(E)?"string"===typeof E&&(c.error=E):(E.message&&(c.message=E.message),E.error&&(c.error=E.error))),c;c=null,a=!1,++l}while(t.length>0);return!0}},1725:e=>{"use strict";var t=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable;function i(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach((function(e){n[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(i){return!1}}()?Object.assign:function(e,o){for(var s,a,c=i(e),l=1;l{const n=r(5125),i=r(2673);e.exports=class{constructor(){this._buffer=new n,this._waitingConsumers=new n}push(e){const{promise:t,resolve:r}=i();return this._buffer.push({chunk:e,resolve:r}),this._consume(),t}_consume(){for(;!this._waitingConsumers.isEmpty()&&!this._buffer.isEmpty();){const e=this._waitingConsumers.shift(),t=this._buffer.shift();e.resolve(t.chunk),t.resolve()}}shift(){const{promise:e,resolve:t}=i();return this._waitingConsumers.push({resolve:t}),this._consume(),e}isEmpty(){return this._buffer.isEmpty()}}},2673:e=>{"use strict";e.exports=()=>{const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}},3931:(e,t,r)=>{"use strict";e.exports=r(3794).default},3794:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(7922),o=n(r(8974)),s=n(r(4514)),a=r(7201),c=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new i.Netmask(e)));function l(e){return/^::$/.test(e)||/^::1$/.test(e)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}t.default=e=>{if((0,a.isValid)(e)){const t=(0,a.parse)(e);if("ipv4"===t.kind())return function(e){for(let t of c)if(t.contains(e))return!0;return!1}(t.toNormalizedString());if("ipv6"===t.kind())return l(e)}else if((0,s.default)(e)&&o.default.v6().test(e))return l(e)}},4514:(e,t,r)=>{"use strict";const n=r(8974),i=e=>n({exact:!0}).test(e);i.v4=e=>n.v4({exact:!0}).test(e),i.v6=e=>n.v6({exact:!0}).test(e),i.version=e=>i(e)?i.v4(e)?4:6:void 0,e.exports=i},1426:e=>{var t,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"===typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"===typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,c=[],l=!1,u=-1;function d(){l&&a&&(l=!1,a.length?c=a.concat(c):u=-1,c.length&&h())}function h(){if(!l){var e=s(d);l=!0;for(var t=c.length;t;){for(a=c,c=[];++u1)for(var r=1;r{"use strict";var n=r(9047);function i(){}function o(){}o.resetWarningCache=i,e.exports=function(){function e(e,t,r,i,o,s){if(s!==n){var a=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw a.name="Invariant Violation",a}}function t(){return e}e.isRequired=e;var r={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:o,resetWarningCache:i};return r.PropTypes=r,r}},2007:(e,t,r)=>{e.exports=r(888)()},9047:e=>{"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},5368:(e,t,r)=>{"use strict";e.exports=r(8154)},1427:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},7276:(e,t,r)=>{"use strict";var n=t,i=r(222),o=r(2440);function s(e,t,r,n){if(t.resolvedType)if(t.resolvedType instanceof i){e("switch(d%s){",n);for(var o=t.resolvedType.values,s=Object.keys(o),a=0;a>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":c=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,c)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,c?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof i?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var o=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":o=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,o?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=o.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n{"use strict";e.exports=function(e){var t=o.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter((function(e){return e.map})).length?",k,value":""))("while(r.pos>>3){");for(var r=0;r>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===i.basic[c]?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",c),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==i.long[a.keyType]?t('%s[typeof k==="object"?util.longToHash(k):k]=value',l):t("%s[k]=value",l)):a.repeated?(t("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==i.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos{"use strict";e.exports=function(e){for(var t,r=o.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(o.compareFieldsById),c=0;c>>0,8|i.mapKey[l.keyType],l.keyType),void 0===h?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|h,d,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==i.packed[d]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",d,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===h?s(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|h)>>>0,d,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===h?s(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|h)>>>0,d,t))}return r("return w")};var n=r(222),i=r(8517),o=r(2440);function s(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},222:(e,t,r)=>{"use strict";e.exports=s;var n=r(5154);((s.prototype=Object.create(n.prototype)).constructor=s).className="Enum";var i=r(3452),o=r(2440);function s(e,t,r,i,o,s){if(n.call(this,e,r),t&&"object"!==typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=i,this.comments=o||{},this.valuesOptions=s,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c{"use strict";e.exports=l;var n=r(5154);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var i,o=r(222),s=r(8517),a=r(2440),c=/^required|optional|repeated$/;function l(e,t,r,i,o,l,u){if(a.isObject(i)?(u=o,l=i,i=o=void 0):a.isObject(o)&&(u=l,l=o,o=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==i&&!c.test(i=i.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==o&&!a.isString(o))throw TypeError("extend must be a string");"proto3_optional"===i&&(i="optional"),this.rule=i&&"optional"!==i?i:void 0,this.type=r,this.id=t,this.extend=o||void 0,this.required="required"===i,this.optional=!this.required,this.repeated="repeated"===i,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==s.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=s.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof i?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof o&&"string"===typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof o)||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"===typeof this.typeDefault){var e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof i&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.d=function(e,t,r,n){return"function"===typeof t?t=a.decorateType(t).name:t&&"object"===typeof t&&(t=a.decorateEnum(t).name),function(i,o){a.decorateType(i.constructor).add(new l(o,e,t,r,{default:n}))}},l._configure=function(e){i=e}},4582:(e,t,r)=>{"use strict";var n=e.exports=r(4722);n.build="light",n.load=function(e,t,r){return"function"===typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(6886),n.decoder=r(2715),n.verifier=r(709),n.converter=r(7276),n.ReflectionObject=r(5154),n.Namespace=r(3452),n.Root=r(8622),n.Enum=r(222),n.Type=r(8716),n.Field=r(6734),n.OneOf=r(9794),n.MapField=r(4479),n.Service=r(4173),n.Method=r(4865),n.Message=r(4486),n.wrappers=r(9025),n.types=r(8517),n.util=r(2440),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},4722:(e,t,r)=>{"use strict";var n=t;function i(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(7063),n.BufferWriter=r(2815),n.Reader=r(6216),n.BufferReader=r(3557),n.util=r(3097),n.rpc=r(9994),n.roots=r(7907),n.configure=i,i()},8154:(e,t,r)=>{"use strict";var n=e.exports=r(4582);n.build="full",n.tokenize=r(3077),n.parse=r(7781),n.common=r(1427),n.Root._configure(n.Type,n.parse,n.common)},4479:(e,t,r)=>{"use strict";e.exports=s;var n=r(6734);((s.prototype=Object.create(n.prototype)).constructor=s).className="MapField";var i=r(8517),o=r(2440);function s(e,t,r,i,s,a){if(n.call(this,e,t,i,void 0,void 0,s,a),!o.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}s.fromJSON=function(e,t){return new s(e,t.id,t.keyType,t.type,t.options,t.comment)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return o.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},s.prototype.resolve=function(){if(this.resolved)return this;if(void 0===i.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},s.d=function(e,t,r){return"function"===typeof r?r=o.decorateType(r).name:r&&"object"===typeof r&&(r=o.decorateEnum(r).name),function(n,i){o.decorateType(n.constructor).add(new s(i,e,t,r))}}},4486:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e){if(e)for(var t=Object.keys(e),r=0;r{"use strict";e.exports=o;var n=r(5154);((o.prototype=Object.create(n.prototype)).constructor=o).className="Method";var i=r(2440);function o(e,t,r,o,s,a,c,l,u){if(i.isObject(s)?(c=s,s=a=void 0):i.isObject(a)&&(c=a,a=void 0),void 0!==t&&!i.isString(t))throw TypeError("type must be a string");if(!i.isString(r))throw TypeError("requestType must be a string");if(!i.isString(o))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!s||void 0,this.responseType=o,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}o.fromJSON=function(e,t){return new o(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},o.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},3452:(e,t,r)=>{"use strict";e.exports=d;var n=r(5154);((d.prototype=Object.create(n.prototype)).constructor=d).className="Namespace";var i,o,s,a=r(6734),c=r(2440),l=r(9794);function u(e,t){if(e&&e.length){for(var r={},n=0;nt)return!0;return!1},d.isReservedName=function(e,t){if(e)for(var r=0;r0;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof d))throw Error("path conflicts with non-namespace objects")}else r.add(r=new d(n))}return t&&r.addJSON(t),r},d.prototype.resolveAll=function(){for(var e=this.nestedArray,t=0;t-1)return n}else if(n instanceof d&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var i=0;i{"use strict";e.exports=o,o.className="ReflectionObject";var n,i=r(2440);function o(e,t){if(!i.isString(e))throw TypeError("name must be a string");if(t&&!i.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof n&&t._handleAdd(this)},o.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},o.prototype.getOption=function(e){if(this.options)return this.options[e]},o.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},o.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var o=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(o){var s=o[e];i.setProperty(s,r,t)}else(o={})[e]=i.setProperty({},r,t),n.push(o)}else{var a={};a[e]=t,n.push(a)}return this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n{"use strict";e.exports=s;var n=r(5154);((s.prototype=Object.create(n.prototype)).constructor=s).className="OneOf";var i=r(6734),o=r(2440);function s(e,t,r,i){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=i}function a(e){if(e.parent)for(var t=0;t-1&&this.oneof.splice(t,1),e.partOf=null,this},s.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t{"use strict";e.exports=C,C.filename=null,C.defaults={keepCase:!1};var n=r(3077),i=r(8622),o=r(8716),s=r(6734),a=r(4479),c=r(9794),l=r(222),u=r(4173),d=r(4865),h=r(8517),f=r(2440),p=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,m=/^-?0[x][0-9a-fA-F]+$/,v=/^0[0-7]+$/,b=/^-?0[0-7]+$/,w=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,_=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function C(e,t,r){t instanceof i||(r=t,t=new i),r||(r=C.defaults);var T,I,A,k,R,P=r.preferTrailingComment||!1,D=n(e,r.alternateCommentMode||!1),N=D.next,O=D.push,x=D.peek,L=D.skip,M=D.cmnt,B=!0,U=!1,F=t,V=r.keepCase?function(e){return e}:f.camelCase;function K(e,t,r){var n=C.filename;return r||(C.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+D.line+")")}function j(){var e,t=[];do{if('"'!==(e=N())&&"'"!==e)throw K(e);t.push(N()),L(e),e=x()}while('"'===e||"'"===e);return t.join("")}function z(e){var t=N();switch(t){case"'":case'"':return O(t),j();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e,t){var r=1;"-"===e.charAt(0)&&(r=-1,e=e.substring(1));switch(e){case"inf":case"INF":case"Inf":return r*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(p.test(e))return r*parseInt(e,10);if(y.test(e))return r*parseInt(e,16);if(v.test(e))return r*parseInt(e,8);if(w.test(e))return r*parseFloat(e);throw K(e,"number",t)}(t,!0)}catch(r){if(e&&S.test(t))return t;throw K(t,"value")}}function q(e,t){var r,n;do{!t||'"'!==(r=x())&&"'"!==r?e.push([n=H(N()),L("to",!0)?H(N()):n]):e.push(j())}while(L(",",!0));L(";")}function H(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw K(e,"id");if(g.test(e))return parseInt(e,10);if(m.test(e))return parseInt(e,16);if(b.test(e))return parseInt(e,8);throw K(e,"id")}function W(){if(void 0!==T)throw K("package");if(T=N(),!S.test(T))throw K(T,"name");F=F.define(T),L(";")}function G(){var e,t=x();switch(t){case"weak":e=A||(A=[]),N();break;case"public":N();default:e=I||(I=[])}t=j(),L(";"),e.push(t)}function Q(){if(L("="),k=j(),!(U="proto3"===k)&&"proto2"!==k)throw K(k,"syntax");L(";")}function $(e,t){switch(t){case"option":return ee(e,t),L(";"),!0;case"message":return X(e,t),!0;case"enum":return Z(e,t),!0;case"service":return function(e,t){if(!E.test(t=N()))throw K(t,"service name");var r=new u(t);Y(r,(function(e){if(!$(r,e)){if("rpc"!==e)throw K(e);!function(e,t){var r=M(),n=t;if(!E.test(t=N()))throw K(t,"name");var i,o,s,a,c=t;L("("),L("stream",!0)&&(o=!0);if(!S.test(t=N()))throw K(t);i=t,L(")"),L("returns"),L("("),L("stream",!0)&&(a=!0);if(!S.test(t=N()))throw K(t);s=t,L(")");var l=new d(c,n,i,s,o,a);l.comment=r,Y(l,(function(e){if("option"!==e)throw K(e);ee(l,e),L(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=N()))throw K(t,"reference");var r=t;Y(null,(function(t){switch(t){case"required":case"repeated":J(e,t,r);break;case"optional":J(e,U?"proto3_optional":"optional",r);break;default:if(!U||!S.test(t))throw K(t);O(t),J(e,"optional",r)}}))}(e,t),!0}return!1}function Y(e,t,r){var n=D.line;if(e&&("string"!==typeof e.comment&&(e.comment=M()),e.filename=C.filename),L("{",!0)){for(var i;"}"!==(i=N());)t(i);L(";",!0)}else r&&r(),L(";"),e&&("string"!==typeof e.comment||P)&&(e.comment=M(n)||e.comment)}function X(e,t){if(!E.test(t=N()))throw K(t,"type name");var r=new o(t);Y(r,(function(e){if(!$(r,e))switch(e){case"map":!function(e){L("<");var t=N();if(void 0===h.mapKey[t])throw K(t,"type");L(",");var r=N();if(!S.test(r))throw K(r,"type");L(">");var n=N();if(!E.test(n))throw K(n,"name");L("=");var i=new a(V(n),H(N()),t,r);Y(i,(function(e){if("option"!==e)throw K(e);ee(i,e),L(";")}),(function(){ne(i)})),e.add(i)}(r);break;case"required":case"repeated":J(r,e);break;case"optional":J(r,U?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=N()))throw K(t,"name");var r=new c(V(t));Y(r,(function(e){"option"===e?(ee(r,e),L(";")):(O(e),J(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":q(r.extensions||(r.extensions=[]));break;case"reserved":q(r.reserved||(r.reserved=[]),!0);break;default:if(!U||!S.test(e))throw K(e);O(e),J(r,"optional")}})),e.add(r)}function J(e,t,r){var n=N();if("group"!==n){if(!S.test(n))throw K(n,"type");var i=N();if(!E.test(i))throw K(i,"name");i=V(i),L("=");var a=new s(i,H(N()),n,t,r);if(Y(a,(function(e){if("option"!==e)throw K(e);ee(a,e),L(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+i);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);U||!a.repeated||void 0===h.packed[n]&&void 0!==h.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=N();if(!E.test(r))throw K(r,"name");var n=f.lcFirst(r);r===n&&(r=f.ucFirst(r));L("=");var i=H(N()),a=new o(r);a.group=!0;var c=new s(n,i,r,t);c.filename=C.filename,Y(a,(function(e){switch(e){case"option":ee(a,e),L(";");break;case"required":case"repeated":J(a,e);break;case"optional":J(a,U?"proto3_optional":"optional");break;case"message":X(a,e);break;case"enum":Z(a,e);break;default:throw K(e)}})),e.add(a).add(c)}(e,t)}function Z(e,t){if(!E.test(t=N()))throw K(t,"name");var r=new l(t);Y(r,(function(e){switch(e){case"option":ee(r,e),L(";");break;case"reserved":q(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw K(t,"name");L("=");var r=H(N(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};Y(n,(function(e){if("option"!==e)throw K(e);ee(n,e),L(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=L("(",!0);if(!S.test(t=N()))throw K(t,"name");var n,i=t,o=i;r&&(L(")"),o=i="("+i+")",t=x(),_.test(t)&&(n=t.slice(1),i+=t,N())),L("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,o,te(e,i),n)}function te(e,t){if(L("{",!0)){for(var r={};!L("}",!0);){if(!E.test(R=N()))throw K(R,"name");var n,i=R;if(L(":",!0),"{"===x())n=te(e,t+"."+R);else if("["===x()){var o;if(n=[],L("[",!0)){do{o=z(!0),n.push(o)}while(L(",",!0));L("]"),"undefined"!==typeof o&&re(e,t+"."+R,o)}}else n=z(!0),re(e,t+"."+R,n);var s=r[i];s&&(n=[].concat(s).concat(n)),r[i]=n,L(",",!0),L(";",!0)}return r}var a=z(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(L("[",!0)){do{ee(e,"option")}while(L(",",!0));L("]")}return e}for(;null!==(R=N());)switch(R){case"package":if(!B)throw K(R);W();break;case"import":if(!B)throw K(R);G();break;case"syntax":if(!B)throw K(R);Q();break;case"option":ee(F,R),L(";");break;default:if($(F,R)){B=!1;continue}throw K(R)}return C.filename=null,{package:T,imports:I,weakImports:A,syntax:k,root:t}}},6216:(e,t,r)=>{"use strict";e.exports=c;var n,i=r(3097),o=i.LongBits,s=i.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l="undefined"!==typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},u=function(){return i.Buffer?function(e){return(c.create=function(e){return i.Buffer.isBuffer(e)?new n(e):l(e)})(e)}:l};function d(){var e=new o(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function h(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new o(h(this.buf,this.pos+=4),h(this.buf,this.pos+=4))}c.create=u(),c.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,c.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return e}}(),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return h(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|h(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?new this.buf.constructor(0):this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},c.prototype.skip=function(e){if("number"===typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!==(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=u(),n._configure();var t=i.Long?"toLong":"toNumber";i.merge(c.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},3557:(e,t,r)=>{"use strict";e.exports=o;var n=r(6216);(o.prototype=Object.create(n.prototype)).constructor=o;var i=r(3097);function o(e){n.call(this,e)}o._configure=function(){i.Buffer&&(o.prototype._slice=i.Buffer.prototype.slice)},o.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},o._configure()},8622:(e,t,r)=>{"use strict";e.exports=d;var n=r(3452);((d.prototype=Object.create(n.prototype)).constructor=d).className="Root";var i,o,s,a=r(6734),c=r(222),l=r(9794),u=r(2440);function d(e){n.call(this,"",e),this.deferred=[],this.files=[]}function h(){}d.fromJSON=function(e,t){return t||(t=new d),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},d.prototype.resolvePath=u.path.resolve,d.prototype.fetch=u.fetch,d.prototype.load=function e(t,r,n){"function"===typeof r&&(n=r,r=void 0);var i=this;if(!n)return u.asPromise(e,i,t,r);var a=n===h;function c(e,t){if(n){var r=n;if(n=null,a)throw e;r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in s)return r}return null}function d(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){o.filename=e;var n,s=o(t,i,r),d=0;if(s.imports)for(;d-1))if(i.files.push(e),e in s)a?d(e,s[e]):(++p,setTimeout((function(){--p,d(e,s[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(o){return void(t||c(o))}d(e,r)}else++p,i.fetch(e,(function(r,o){--p,n&&(r?t?p||c(null,i):c(r):d(e,o))}))}var p=0;u.isString(t)&&(t=[t]);for(var g,y=0;y-1&&this.deferred.splice(t,1)}}else if(e instanceof c)f.test(e.name)&&delete e.parent[e.name];else if(e instanceof n){for(var r=0;r{"use strict";e.exports={}},9994:(e,t,r)=>{"use strict";t.Service=r(4281)},4281:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e,t,r){if("function"!==typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function e(t,r,i,o,s){if(!o)throw TypeError("request must be specified");var a=this;if(!s)return n.asPromise(e,a,t,r,i,o);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(e,r){if(e)return a.emit("error",e,t),s(e);if(null!==r){if(!(r instanceof i))try{r=i[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),s(e)}return a.emit("data",r,t),s(null,r)}a.end(!0)}))}catch(c){return a.emit("error",c,t),void setTimeout((function(){s(c)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},i.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},4173:(e,t,r)=>{"use strict";e.exports=a;var n=r(3452);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var i=r(4865),o=r(2440),s=r(9994);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),o=0;o{"use strict";e.exports=d;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,i=/^ *[*/]+ */,o=/^\s*\*?\/*/,s=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function d(e,c){e=e.toString();var l=0,d=e.length,h=1,f=0,p={},g=[],y=null;function m(e){return Error("illegal "+e+" (line "+h+")")}function v(t){return e.charAt(t)}function b(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var d=e.substring(t,r).split(s),g=0;g0)return g.shift();if(y)return function(){var t="'"===y?n:r;t.lastIndex=l-1;var i=t.exec(e);if(!i)throw m("string");return l=t.lastIndex,_(y),y=null,u(i[1])}();var i,o,s,f,p,S=0===l;do{if(l===d)return null;for(i=!1;a.test(s=v(l));)if("\n"===s&&(S=!0,++h),++l===d)return null;if("/"===v(l)){if(++l===d)throw m("comment");if("/"===v(l))if(c){if(f=l,p=!1,w(l)){p=!0;do{if((l=E(l))===d)break;if(l++,!S)break}while(w(l))}else l=Math.min(d,E(l)+1);p&&(b(f,l,S),S=!0),h++,i=!0}else{for(p="/"===v(f=l+1);"\n"!==v(++l);)if(l===d)return null;++l,p&&(b(f,l-1,S),S=!0),++h,i=!0}else{if("*"!==(s=v(l)))return"/";f=l+1,p=c||"*"===v(f);do{if("\n"===s&&++h,++l===d)throw m("comment");o=s,s=v(l)}while("*"!==o||"/"!==s);++l,p&&(b(f,l-2,S),S=!0),i=!0}}}while(i);var C=l;if(t.lastIndex=0,!t.test(v(C++)))for(;C{"use strict";e.exports=v;var n=r(3452);((v.prototype=Object.create(n.prototype)).constructor=v).className="Type";var i=r(222),o=r(9794),s=r(6734),a=r(4479),c=r(4173),l=r(4486),u=r(6216),d=r(7063),h=r(2440),f=r(6886),p=r(2715),g=r(709),y=r(7276),m=r(9025);function v(e,t){n.call(this,e,t),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function b(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(v.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t{"use strict";var n=t,i=r(2440),o=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function s(e,t){var r=0,n={};for(t|=0;r{"use strict";var n,i,o=e.exports=r(3097),s=r(7907);o.codegen=r(3297),o.fetch=r(7635),o.path=r(7468),o.fs=o.inquire("fs"),o.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n0)t[i]=e(t[i]||{},r,n);else{var o=t[i];o&&(n=[].concat(o).concat(n)),t[i]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(o,"decorateRoot",{get:function(){return s.decorated||(s.decorated=new(r(8622)))}})},9351:(e,t,r)=>{"use strict";e.exports=i;var n=r(3097);function i(e,t){this.lo=e>>>0,this.hi=t>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var s=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(e){if(0===e)return o;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new i(r,n)},i.from=function(e){if("number"===typeof e)return i.fromNumber(e);if(n.isString(e)){if(!n.Long)return i.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new i(e.low>>>0,e.high>>>0):o},i.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;i.fromHash=function(e){return e===s?o:new i((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},i.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},i.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},3097:function(e,t,r){"use strict";var n=t;function i(e,t,r){for(var n=Object.keys(t),i=0;ie,set:void 0,enumerable:!1,configurable:!0},toString:{value(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}n.asPromise=r(7206),n.base64=r(1),n.EventEmitter=r(7111),n.float=r(802),n.inquire=r(7172),n.utf8=r(3861),n.pool=r(8236),n.LongBits=r(9351),n.isNode=Boolean("undefined"!==typeof r.g&&r.g&&r.g.process&&r.g.process.versions&&r.g.process.versions.node),n.global=n.isNode&&r.g||"undefined"!==typeof window&&window||"undefined"!==typeof self&&self||this,n.emptyArray=Object.freeze?Object.freeze([]):[],n.emptyObject=Object.freeze?Object.freeze({}):{},n.isInteger=Number.isInteger||function(e){return"number"===typeof e&&isFinite(e)&&Math.floor(e)===e},n.isString=function(e){return"string"===typeof e||e instanceof String},n.isObject=function(e){return e&&"object"===typeof e},n.isset=n.isSet=function(e,t){var r=e[t];return!(null==r||!e.hasOwnProperty(t))&&("object"!==typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(t){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"===typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"===typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!==typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=i,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=o,n.ProtocolError=o("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r{"use strict";e.exports=function(e){var t=i.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r=e.oneofsArray,n={};r.length&&t("var p={}");for(var c=0;c{"use strict";var n=t,i=r(4486);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var o=this.lookup(n);o&&(e=o.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof i){var s=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),s["@type"]=n,s}return this.toObject(e,t)}}},7063:(e,t,r)=>{"use strict";e.exports=d;var n,i=r(3097),o=i.LongBits,s=i.base64,a=i.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function d(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var h=function(){return i.Buffer?function(){return(d.create=function(){return new n})()}:function(){return new d}};function f(e,t,r){t[r]=255&e}function p(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function y(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}d.create=h(),d.alloc=function(e){return new i.Array(e)},i.Array!==Array&&(d.alloc=i.pool(d.alloc,i.Array.prototype.subarray)),d.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},p.prototype=Object.create(c.prototype),p.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},d.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},d.prototype.int32=function(e){return e<0?this._push(g,10,o.fromNumber(e)):this.uint32(e)},d.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},d.prototype.uint64=function(e){var t=o.from(e);return this._push(g,t.length(),t)},d.prototype.int64=d.prototype.uint64,d.prototype.sint64=function(e){var t=o.from(e).zzEncode();return this._push(g,t.length(),t)},d.prototype.bool=function(e){return this._push(f,1,e?1:0)},d.prototype.fixed32=function(e){return this._push(y,4,e>>>0)},d.prototype.sfixed32=d.prototype.fixed32,d.prototype.fixed64=function(e){var t=o.from(e);return this._push(y,4,t.lo)._push(y,4,t.hi)},d.prototype.sfixed64=d.prototype.fixed64,d.prototype.float=function(e){return this._push(i.float.writeFloatLE,4,e)},d.prototype.double=function(e){return this._push(i.float.writeDoubleLE,8,e)};var m=i.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(f,1,0);if(i.isString(e)){var r=d.alloc(t=s.length(e));s.decode(e,r,0),e=r}return this.uint32(t)._push(m,t,e)},d.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(f,1,0)},d.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},d.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(l,0,0),this.len=0),this},d.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},d.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},d._configure=function(e){n=e,d.create=h(),n._configure()}},2815:(e,t,r)=>{"use strict";e.exports=o;var n=r(7063);(o.prototype=Object.create(n.prototype)).constructor=o;var i=r(3097);function o(){n.call(this)}function s(e,t,r){e.length<40?i.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}o._configure=function(){o.alloc=i._Buffer_allocUnsafe,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(o.writeBytesBuffer,t,e),this},o.prototype.string=function(e){var t=i.Buffer.byteLength(e);return this.uint32(t),t&&this._push(s,t,e),this},o._configure()},4463:(e,t,r)=>{"use strict";var n=r(2791),i=r(1725),o=r(5296);function s(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r
    = it.Source | (() => it.Source) | it.Duplex\nexport type Transform = it.Transform | it.Duplex\nexport type Sink = it.Sink | it.Duplex\n\nexport function pipe (\n first: Source\n): it.Source\n\nexport function pipe (\n first: Source,\n second: Sink\n): B\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Sink\n): C\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Sink\n): D\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Sink\n): E\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Sink\n): F\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Sink\n): G\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Sink\n): H\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Sink\n): I\n\nexport function pipe (\n first: Source,\n second: Transform,\n third: Transform,\n fourth: Transform,\n fifth: Transform,\n sixth: Transform,\n seventh: Transform,\n eighth: Transform,\n ninth: Transform,\n tenth: Sink\n): J\n\nexport function pipe (first: any, ...rest: any[]): any {\n // Duplex at start: wrap in function and return duplex source\n if (isDuplex(first)) {\n const duplex = first\n first = () => duplex.source\n // Iterable at start: wrap in function\n } else if (isIterable(first)) {\n const source = first\n first = () => source\n }\n\n const fns = [first, ...rest]\n\n if (fns.length > 1) {\n // Duplex at end: use duplex sink\n if (isDuplex(fns[fns.length - 1])) {\n fns[fns.length - 1] = fns[fns.length - 1].sink\n }\n }\n\n if (fns.length > 2) {\n // Duplex in the middle, consume source with duplex sink and return duplex source\n for (let i = 1; i < fns.length - 1; i++) {\n if (isDuplex(fns[i])) {\n fns[i] = duplexPipelineFn(fns[i])\n }\n }\n }\n\n return rawPipe(...fns)\n}\n","import { Peer } from \"@libp2p/interface-peer-store\";\nimport { Libp2p } from \"libp2p\";\n\n/**\n * Returns a pseudo-random peer that supports the given protocol.\n * Useful for protocols such as store and light push\n */\nexport async function selectRandomPeer(\n peers: Peer[]\n): Promise {\n if (peers.length === 0) return;\n\n const index = Math.round(Math.random() * (peers.length - 1));\n return peers[index];\n}\n\n/**\n * Returns the list of peers that supports the given protocol.\n */\nexport async function getPeersForProtocol(\n libp2p: Libp2p,\n protocols: string[]\n): Promise {\n const peers: Peer[] = [];\n await libp2p.peerStore.forEach((peer) => {\n for (let i = 0; i < protocols.length; i++) {\n if (peer.protocols.includes(protocols[i])) {\n peers.push(peer);\n break;\n }\n }\n });\n return peers;\n}\n","import * as secp from \"@noble/secp256k1\";\n\nimport { getSubtle, randomBytes, sha256 } from \"../crypto\";\nimport { concat, hexToBytes } from \"../utils\";\n/**\n * HKDF as implemented in go-ethereum.\n */\nfunction kdf(secret: Uint8Array, outputLength: number): Promise {\n let ctr = 1;\n let written = 0;\n let willBeResult = Promise.resolve(new Uint8Array());\n while (written < outputLength) {\n const counters = new Uint8Array([ctr >> 24, ctr >> 16, ctr >> 8, ctr]);\n const countersSecret = concat(\n [counters, secret],\n counters.length + secret.length\n );\n const willBeHashResult = sha256(countersSecret);\n willBeResult = willBeResult.then((result) =>\n willBeHashResult.then((hashResult) => {\n const _hashResult = new Uint8Array(hashResult);\n return concat(\n [result, _hashResult],\n result.length + _hashResult.length\n );\n })\n );\n written += 32;\n ctr += 1;\n }\n return willBeResult;\n}\n\nfunction aesCtrEncrypt(\n counter: Uint8Array,\n key: ArrayBufferLike,\n data: ArrayBufferLike\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, \"AES-CTR\", false, [\"encrypt\"])\n .then((cryptoKey) =>\n getSubtle().encrypt(\n { name: \"AES-CTR\", counter: counter, length: 128 },\n cryptoKey,\n data\n )\n )\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction aesCtrDecrypt(\n counter: Uint8Array,\n key: ArrayBufferLike,\n data: ArrayBufferLike\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, \"AES-CTR\", false, [\"decrypt\"])\n .then((cryptoKey) =>\n getSubtle().decrypt(\n { name: \"AES-CTR\", counter: counter, length: 128 },\n cryptoKey,\n data\n )\n )\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction hmacSha256Sign(\n key: ArrayBufferLike,\n msg: ArrayBufferLike\n): PromiseLike {\n const algorithm = { name: \"HMAC\", hash: { name: \"SHA-256\" } };\n return getSubtle()\n .importKey(\"raw\", key, algorithm, false, [\"sign\"])\n .then((cryptoKey) => getSubtle().sign(algorithm, cryptoKey, msg))\n .then((bytes) => new Uint8Array(bytes));\n}\n\nfunction hmacSha256Verify(\n key: ArrayBufferLike,\n msg: ArrayBufferLike,\n sig: ArrayBufferLike\n): Promise {\n const algorithm = { name: \"HMAC\", hash: { name: \"SHA-256\" } };\n const _key = getSubtle().importKey(\"raw\", key, algorithm, false, [\"verify\"]);\n return _key.then((cryptoKey) =>\n getSubtle().verify(algorithm, cryptoKey, sig, msg)\n );\n}\n\n/**\n * Derive shared secret for given private and public keys.\n *\n * @param privateKeyA Sender's private key (32 bytes)\n * @param publicKeyB Recipient's public key (65 bytes)\n * @returns A promise that resolves with the derived shared secret (Px, 32 bytes)\n * @throws Error If arguments are invalid\n */\nfunction derive(privateKeyA: Uint8Array, publicKeyB: Uint8Array): Uint8Array {\n if (privateKeyA.length !== 32) {\n throw new Error(\n `Bad private key, it should be 32 bytes but it's actually ${privateKeyA.length} bytes long`\n );\n } else if (publicKeyB.length !== 65) {\n throw new Error(\n `Bad public key, it should be 65 bytes but it's actually ${publicKeyB.length} bytes long`\n );\n } else if (publicKeyB[0] !== 4) {\n throw new Error(\"Bad public key, a valid public key would begin with 4\");\n } else {\n const px = secp.getSharedSecret(privateKeyA, publicKeyB, true);\n // Remove the compression prefix\n return new Uint8Array(hexToBytes(px).slice(1));\n }\n}\n\n/**\n * Encrypt message for given recipient's public key.\n *\n * @param publicKeyTo Recipient's public key (65 bytes)\n * @param msg The message being encrypted\n * @return A promise that resolves with the ECIES structure serialized\n */\nexport async function encrypt(\n publicKeyTo: Uint8Array,\n msg: Uint8Array\n): Promise {\n const ephemPrivateKey = randomBytes(32);\n\n const sharedPx = await derive(ephemPrivateKey, publicKeyTo);\n\n const hash = await kdf(sharedPx, 32);\n\n const iv = randomBytes(16);\n const encryptionKey = hash.slice(0, 16);\n const cipherText = await aesCtrEncrypt(iv, encryptionKey, msg);\n\n const ivCipherText = concat([iv, cipherText], iv.length + cipherText.length);\n\n const macKey = await sha256(hash.slice(16));\n const hmac = await hmacSha256Sign(macKey, ivCipherText);\n const ephemPublicKey = secp.getPublicKey(ephemPrivateKey, false);\n\n return concat(\n [ephemPublicKey, ivCipherText, hmac],\n ephemPublicKey.length + ivCipherText.length + hmac.length\n );\n}\n\nconst metaLength = 1 + 64 + 16 + 32;\n\n/**\n * Decrypt message using given private key.\n *\n * @param privateKey A 32-byte private key of recipient of the message\n * @param encrypted ECIES serialized structure (result of ECIES encryption)\n * @returns The clear text\n * @throws Error If decryption fails\n */\nexport async function decrypt(\n privateKey: Uint8Array,\n encrypted: Uint8Array\n): Promise {\n if (encrypted.length <= metaLength) {\n throw new Error(\n `Invalid Ciphertext. Data is too small. It should ba at least ${metaLength} bytes`\n );\n } else if (encrypted[0] !== 4) {\n throw new Error(\n `Not a valid ciphertext. It should begin with 4 but actually begin with ${encrypted[0]}`\n );\n } else {\n // deserialize\n const ephemPublicKey = encrypted.slice(0, 65);\n const cipherTextLength = encrypted.length - metaLength;\n const iv = encrypted.slice(65, 65 + 16);\n const cipherAndIv = encrypted.slice(65, 65 + 16 + cipherTextLength);\n const ciphertext = cipherAndIv.slice(16);\n const msgMac = encrypted.slice(65 + 16 + cipherTextLength);\n\n // check HMAC\n const px = derive(privateKey, ephemPublicKey);\n const hash = await kdf(px, 32);\n const [encryptionKey, macKey] = await sha256(hash.slice(16)).then(\n (macKey) => [hash.slice(0, 16), macKey]\n );\n\n if (!(await hmacSha256Verify(macKey, cipherAndIv, msgMac))) {\n throw new Error(\"Incorrect MAC\");\n }\n\n return aesCtrDecrypt(iv, encryptionKey, ciphertext);\n }\n}\n","import * as secp from \"@noble/secp256k1\";\n\nimport { keccak256, randomBytes, sign } from \"../crypto\";\nimport { concat, hexToBytes } from \"../utils\";\n\nimport { Symmetric } from \"./constants\";\nimport * as ecies from \"./ecies\";\nimport * as symmetric from \"./symmetric\";\n\nconst FlagsLength = 1;\nconst FlagMask = 3; // 0011\nconst IsSignedMask = 4; // 0100\nconst PaddingTarget = 256;\nconst SignatureLength = 65;\n\nexport type Signature = {\n signature: Uint8Array;\n publicKey: Uint8Array | undefined;\n};\n\n/**\n * Encode the payload pre-encryption.\n *\n * @internal\n * @param messagePayload: The payload to include in the message\n * @param sigPrivKey: If set, a signature using this private key is added.\n * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}\n * or {@link encryptSymmetric}.\n */\nexport async function clearEncode(\n messagePayload: Uint8Array,\n sigPrivKey?: Uint8Array\n): Promise<{ payload: Uint8Array; sig?: Signature }> {\n let envelope = new Uint8Array([0]); // No flags\n envelope = addPayloadSizeField(envelope, messagePayload);\n envelope = concat([envelope, messagePayload]);\n\n // Calculate padding:\n let rawSize =\n FlagsLength +\n computeSizeOfPayloadSizeField(messagePayload) +\n messagePayload.length;\n\n if (sigPrivKey) {\n rawSize += SignatureLength;\n }\n\n const remainder = rawSize % PaddingTarget;\n const paddingSize = PaddingTarget - remainder;\n const pad = randomBytes(paddingSize);\n\n if (!validateDataIntegrity(pad, paddingSize)) {\n throw new Error(\"failed to generate random padding of size \" + paddingSize);\n }\n\n envelope = concat([envelope, pad]);\n let sig;\n if (sigPrivKey) {\n envelope[0] |= IsSignedMask;\n const hash = keccak256(envelope);\n const bytesSignature = await sign(hash, sigPrivKey);\n envelope = concat([envelope, bytesSignature]);\n sig = {\n signature: bytesSignature,\n publicKey: secp.getPublicKey(sigPrivKey, false),\n };\n }\n\n return { payload: envelope, sig };\n}\n\n/**\n * Decode a decrypted payload.\n *\n * @internal\n */\nexport function clearDecode(\n message: Uint8Array\n): { payload: Uint8Array; sig?: Signature } | undefined {\n const sizeOfPayloadSizeField = getSizeOfPayloadSizeField(message);\n if (sizeOfPayloadSizeField === 0) return;\n\n const payloadSize = getPayloadSize(message, sizeOfPayloadSizeField);\n const payloadStart = 1 + sizeOfPayloadSizeField;\n const payload = message.slice(payloadStart, payloadStart + payloadSize);\n\n const isSigned = isMessageSigned(message);\n\n let sig;\n if (isSigned) {\n const signature = getSignature(message);\n const hash = getHash(message, isSigned);\n const publicKey = ecRecoverPubKey(hash, signature);\n sig = { signature, publicKey };\n }\n\n return { payload, sig };\n}\n\nfunction getSizeOfPayloadSizeField(message: Uint8Array): number {\n const messageDataView = new DataView(message.buffer);\n return messageDataView.getUint8(0) & FlagMask;\n}\n\nfunction getPayloadSize(\n message: Uint8Array,\n sizeOfPayloadSizeField: number\n): number {\n let payloadSizeBytes = message.slice(1, 1 + sizeOfPayloadSizeField);\n // int 32 == 4 bytes\n if (sizeOfPayloadSizeField < 4) {\n // If less than 4 bytes pad right (Little Endian).\n payloadSizeBytes = concat(\n [payloadSizeBytes, new Uint8Array(4 - sizeOfPayloadSizeField)],\n 4\n );\n }\n const payloadSizeDataView = new DataView(payloadSizeBytes.buffer);\n return payloadSizeDataView.getInt32(0, true);\n}\n\nfunction isMessageSigned(message: Uint8Array): boolean {\n const messageDataView = new DataView(message.buffer);\n return (messageDataView.getUint8(0) & IsSignedMask) == IsSignedMask;\n}\n\n/**\n * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n * The data MUST be flags | payload-length | payload | [signature].\n * The returned result can be set to `WakuMessage.payload`.\n *\n * @internal\n */\nexport async function encryptAsymmetric(\n data: Uint8Array,\n publicKey: Uint8Array | string\n): Promise {\n return ecies.encrypt(hexToBytes(publicKey), data);\n}\n\n/**\n * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n * The returned data is expected to be `flags | payload-length | payload | [signature]`.\n *\n * @internal\n */\nexport async function decryptAsymmetric(\n payload: Uint8Array,\n privKey: Uint8Array\n): Promise {\n return ecies.decrypt(privKey, payload);\n}\n\n/**\n * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n *\n * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.\n * @param key The key to use for encryption.\n * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.\n *\n * @internal\n */\nexport async function encryptSymmetric(\n data: Uint8Array,\n key: Uint8Array | string\n): Promise {\n const iv = symmetric.generateIv();\n\n // Returns `cipher | tag`\n const cipher = await symmetric.encrypt(iv, hexToBytes(key), data);\n return concat([cipher, iv]);\n}\n\n/**\n * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n *\n * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.\n * @param key The key to use for decryption.\n * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.\n *\n * @internal\n */\nexport async function decryptSymmetric(\n payload: Uint8Array,\n key: Uint8Array | string\n): Promise {\n const ivStart = payload.length - Symmetric.ivSize;\n const cipher = payload.slice(0, ivStart);\n const iv = payload.slice(ivStart);\n\n return symmetric.decrypt(iv, hexToBytes(key), cipher);\n}\n\n/**\n * Computes the flags & auxiliary-field as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).\n */\nfunction addPayloadSizeField(msg: Uint8Array, payload: Uint8Array): Uint8Array {\n const fieldSize = computeSizeOfPayloadSizeField(payload);\n let field = new Uint8Array(4);\n const fieldDataView = new DataView(field.buffer);\n fieldDataView.setUint32(0, payload.length, true);\n field = field.slice(0, fieldSize);\n msg = concat([msg, field]);\n msg[0] |= fieldSize;\n return msg;\n}\n\n/**\n * Returns the size of the auxiliary-field which in turns contains the payload size\n */\nfunction computeSizeOfPayloadSizeField(payload: Uint8Array): number {\n let s = 1;\n for (let i = payload.length; i >= 256; i /= 256) {\n s++;\n }\n return s;\n}\n\nfunction validateDataIntegrity(\n value: Uint8Array,\n expectedSize: number\n): boolean {\n if (value.length !== expectedSize) {\n return false;\n }\n\n return expectedSize <= 3 || value.findIndex((i) => i !== 0) !== -1;\n}\n\nfunction getSignature(message: Uint8Array): Uint8Array {\n return message.slice(message.length - SignatureLength, message.length);\n}\n\nfunction getHash(message: Uint8Array, isSigned: boolean): Uint8Array {\n if (isSigned) {\n return keccak256(message.slice(0, message.length - SignatureLength));\n }\n return keccak256(message);\n}\n\nfunction ecRecoverPubKey(\n messageHash: Uint8Array,\n signature: Uint8Array\n): Uint8Array | undefined {\n const recoveryDataView = new DataView(signature.slice(64).buffer);\n const recovery = recoveryDataView.getUint8(0);\n const _signature = secp.Signature.fromCompact(signature.slice(0, 64));\n\n return secp.recoverPublicKey(\n messageHash,\n _signature,\n recovery,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: compressed: false\n false\n );\n}\n","import { getSubtle, randomBytes } from \"../crypto\";\n\nimport { Symmetric } from \"./constants\";\n\nexport async function encrypt(\n iv: Uint8Array,\n key: Uint8Array,\n clearText: Uint8Array\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, Symmetric.algorithm, false, [\"encrypt\"])\n .then((cryptoKey) =>\n getSubtle().encrypt({ iv, ...Symmetric.algorithm }, cryptoKey, clearText)\n )\n .then((cipher) => new Uint8Array(cipher));\n}\n\nexport async function decrypt(\n iv: Uint8Array,\n key: Uint8Array,\n cipherText: Uint8Array\n): Promise {\n return getSubtle()\n .importKey(\"raw\", key, Symmetric.algorithm, false, [\"decrypt\"])\n .then((cryptoKey) =>\n getSubtle().decrypt({ iv, ...Symmetric.algorithm }, cryptoKey, cipherText)\n )\n .then((clear) => new Uint8Array(clear));\n}\n\nexport function generateIv(): Uint8Array {\n return randomBytes(Symmetric.ivSize);\n}\n","import debug from \"debug\";\n\nimport * as proto from \"../../proto/message\";\nimport { bytesToUtf8, utf8ToBytes } from \"../utils\";\n\nimport * as version_1 from \"./version_1\";\n\nconst DefaultVersion = 0;\nconst dbg = debug(\"waku:message\");\nconst OneMillion = BigInt(1_000_000);\n\nexport enum DecryptionMethod {\n Asymmetric = \"asymmetric\",\n Symmetric = \"symmetric\",\n}\n\nexport interface Options {\n /**\n * Timestamp to set on the message, defaults to now if not passed.\n */\n timestamp?: Date;\n /**\n * Public Key to use to encrypt the messages using ECIES (Asymmetric Encryption).\n *\n * @throws if both `encPublicKey` and `symKey` are passed\n */\n encPublicKey?: Uint8Array | string;\n /**\n * Key to use to encrypt the messages using AES (Symmetric Encryption).\n *\n * @throws if both `encPublicKey` and `symKey` are passed\n */\n symKey?: Uint8Array | string;\n /**\n * Private key to use to sign the message, either `encPublicKey` or `symKey` must be provided as only\n * encrypted messages are signed.\n */\n sigPrivKey?: Uint8Array;\n}\n\n// TODO: Use this in Options\nexport interface DecryptionParams {\n key: Uint8Array;\n method?: DecryptionMethod;\n contentTopics?: string[];\n}\n\nexport class WakuMessage {\n private constructor(\n public proto: proto.WakuMessage,\n private _signaturePublicKey?: Uint8Array,\n private _signature?: Uint8Array\n ) {}\n\n /**\n * Create Message with an utf-8 string as payload.\n */\n static async fromUtf8String(\n utf8: string,\n contentTopic: string,\n opts?: Options\n ): Promise {\n const payload = utf8ToBytes(utf8);\n return WakuMessage.fromBytes(payload, contentTopic, opts);\n }\n\n /**\n * Create a Waku Message with the given payload.\n *\n * By default, the payload is kept clear (version 0).\n * If `opts.encPublicKey` is passed, the payload is encrypted using\n * asymmetric encryption (version 1).\n *\n * If `opts.sigPrivKey` is passed and version 1 is used, the payload is signed\n * before encryption.\n *\n * @throws if both `opts.encPublicKey` and `opt.symKey` are passed\n */\n static async fromBytes(\n payload: Uint8Array,\n contentTopic: string,\n opts?: Options\n ): Promise {\n const { timestamp, encPublicKey, symKey, sigPrivKey } = Object.assign(\n { timestamp: new Date() },\n opts ? opts : {}\n );\n\n let _payload = payload;\n let version = DefaultVersion;\n let sig;\n\n if (encPublicKey && symKey) {\n throw \"Pass either `encPublicKey` or `symKey`, not both.\";\n }\n\n if (encPublicKey) {\n const enc = await version_1.clearEncode(_payload, sigPrivKey);\n _payload = await version_1.encryptAsymmetric(enc.payload, encPublicKey);\n sig = enc.sig;\n version = 1;\n } else if (symKey) {\n const enc = await version_1.clearEncode(_payload, sigPrivKey);\n _payload = await version_1.encryptSymmetric(enc.payload, symKey);\n sig = enc.sig;\n version = 1;\n }\n\n return new WakuMessage(\n {\n payload: _payload,\n timestampDeprecated: timestamp.valueOf() / 1000,\n // milliseconds 10^-3 to nanoseconds 10^-9\n timestamp: BigInt(timestamp.valueOf()) * OneMillion,\n version,\n contentTopic,\n },\n sig?.publicKey,\n sig?.signature\n );\n }\n\n /**\n * Decode a byte array into Waku Message.\n *\n * @params bytes The message encoded using protobuf as defined in [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/).\n * @params decryptionKeys If the payload is encrypted (version = 1), then the\n * keys are used to attempt decryption of the message. The passed key can either\n * be asymmetric private keys or symmetric keys, both method are tried for each\n * key until the message is decrypted or combinations are run out.\n */\n static async decode(\n bytes: Uint8Array,\n decryptionParams?: DecryptionParams[]\n ): Promise {\n const protoBuf = proto.WakuMessage.decode(bytes);\n\n return WakuMessage.decodeProto(protoBuf, decryptionParams);\n }\n\n /**\n * Decode and decrypt Waku Message Protobuf Object into Waku Message.\n *\n * @params protoBuf The message to decode and decrypt.\n * @params decryptionParams If the payload is encrypted (version = 1), then the\n * keys are used to attempt decryption of the message. The passed key can either\n * be asymmetric private keys or symmetric keys, both method are tried for each\n * key until the message is decrypted or combinations are run out.\n */\n static async decodeProto(\n protoBuf: proto.WakuMessage,\n decryptionParams?: DecryptionParams[]\n ): Promise {\n const payload = protoBuf.payload;\n\n let signaturePublicKey;\n let signature;\n if (protoBuf.version === 1 && payload) {\n if (decryptionParams === undefined) {\n dbg(\"Payload is encrypted but no private keys have been provided.\");\n return;\n }\n\n // Returns a bunch of `undefined` and hopefully one decrypted result\n const allResults = await Promise.all(\n decryptionParams.map(async ({ key, method, contentTopics }) => {\n if (\n !contentTopics ||\n (protoBuf.contentTopic &&\n contentTopics.includes(protoBuf.contentTopic))\n ) {\n switch (method) {\n case DecryptionMethod.Asymmetric:\n try {\n return await version_1.decryptAsymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption despite decryption method being specified\",\n e\n );\n return;\n }\n case DecryptionMethod.Symmetric:\n try {\n return await version_1.decryptSymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption despite decryption method being specified\",\n e\n );\n return;\n }\n default:\n try {\n return await version_1.decryptSymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using symmetric encryption\",\n e\n );\n try {\n return await version_1.decryptAsymmetric(payload, key);\n } catch (e) {\n dbg(\n \"Failed to decrypt message using asymmetric encryption\",\n e\n );\n return;\n }\n }\n }\n } else {\n // No key available for this content topic\n return;\n }\n })\n );\n\n const isDefined = (dec: Uint8Array | undefined): dec is Uint8Array => {\n return !!dec;\n };\n\n const decodedResults = allResults.filter(isDefined);\n\n if (decodedResults.length === 0) {\n dbg(\"Failed to decrypt payload.\");\n return;\n }\n const dec = decodedResults[0];\n\n const res = await version_1.clearDecode(dec);\n if (!res) {\n dbg(\"Failed to decode payload.\");\n return;\n }\n Object.assign(protoBuf, { payload: res.payload });\n signaturePublicKey = res.sig?.publicKey;\n signature = res.sig?.signature;\n }\n\n return new WakuMessage(protoBuf, signaturePublicKey, signature);\n }\n\n encode(): Uint8Array {\n return proto.WakuMessage.encode(this.proto);\n }\n\n get payloadAsUtf8(): string {\n if (!this.payload) {\n return \"\";\n }\n\n try {\n return bytesToUtf8(this.payload);\n } catch (e) {\n dbg(\"Could not decode byte as UTF-8\", e);\n return \"\";\n }\n }\n\n get payload(): Uint8Array | undefined {\n if (this.proto.payload) {\n return new Uint8Array(this.proto.payload);\n }\n return;\n }\n\n get contentTopic(): string | undefined {\n return this.proto.contentTopic;\n }\n\n get version(): number {\n // TODO: absent value should be replaced by default\n // value of the type by the protobuf decoder\n return this.proto.version ?? 0;\n }\n\n get timestamp(): Date | undefined {\n // In the case we receive a value that is bigger than JS's max number,\n // we catch the error and return undefined.\n try {\n if (this.proto.timestamp) {\n // nanoseconds 10^-9 to milliseconds 10^-3\n const timestamp = this.proto.timestamp / OneMillion;\n return new Date(Number(timestamp));\n }\n\n if (this.proto.timestampDeprecated) {\n return new Date(this.proto.timestampDeprecated * 1000);\n }\n } catch (e) {\n return;\n }\n return;\n }\n\n /**\n * The public key used to sign the message.\n *\n * MAY be present if the message is version 1.\n */\n get signaturePublicKey(): Uint8Array | undefined {\n return this._signaturePublicKey;\n }\n\n /**\n * The signature of the message.\n *\n * MAY be present if the message is version 1.\n */\n get signature(): Uint8Array | undefined {\n return this._signature;\n }\n}\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from \"protons-runtime\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface FilterRequest {\n subscribe?: boolean;\n topic?: string;\n contentFilters: FilterRequest.ContentFilter[];\n}\n\nexport namespace FilterRequest {\n export interface ContentFilter {\n contentTopic?: string;\n }\n\n export namespace ContentFilter {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.contentTopic != null) {\n writer.uint32(10);\n writer.string(obj.contentTopic);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.contentTopic = reader.string();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n }\n\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.subscribe != null) {\n writer.uint32(8);\n writer.bool(obj.subscribe);\n }\n\n if (obj.topic != null) {\n writer.uint32(18);\n writer.string(obj.topic);\n }\n\n if (obj.contentFilters != null) {\n for (const value of obj.contentFilters) {\n writer.uint32(26);\n FilterRequest.ContentFilter.codec().encode(value, writer);\n }\n } else {\n throw new Error(\n 'Protocol error: required field \"contentFilters\" was not found in object'\n );\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n contentFilters: [],\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.subscribe = reader.bool();\n break;\n case 2:\n obj.topic = reader.string();\n break;\n case 3:\n obj.contentFilters.push(\n FilterRequest.ContentFilter.codec().decode(\n reader,\n reader.uint32()\n )\n );\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: FilterRequest): Uint8Array => {\n return encodeMessage(obj, FilterRequest.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FilterRequest => {\n return decodeMessage(buf, FilterRequest.codec());\n };\n}\n\nexport interface MessagePush {\n messages: WakuMessage[];\n}\n\nexport namespace MessagePush {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.messages != null) {\n for (const value of obj.messages) {\n writer.uint32(10);\n WakuMessage.codec().encode(value, writer);\n }\n } else {\n throw new Error(\n 'Protocol error: required field \"messages\" was not found in object'\n );\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n messages: [],\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.messages.push(\n WakuMessage.codec().decode(reader, reader.uint32())\n );\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: MessagePush): Uint8Array => {\n return encodeMessage(obj, MessagePush.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): MessagePush => {\n return decodeMessage(buf, MessagePush.codec());\n };\n}\n\nexport interface FilterRPC {\n requestId?: string;\n request?: FilterRequest;\n push?: MessagePush;\n}\n\nexport namespace FilterRPC {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.requestId != null) {\n writer.uint32(10);\n writer.string(obj.requestId);\n }\n\n if (obj.request != null) {\n writer.uint32(18);\n FilterRequest.codec().encode(obj.request, writer);\n }\n\n if (obj.push != null) {\n writer.uint32(26);\n MessagePush.codec().encode(obj.push, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.requestId = reader.string();\n break;\n case 2:\n obj.request = FilterRequest.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n case 3:\n obj.push = MessagePush.codec().decode(reader, reader.uint32());\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: FilterRPC): Uint8Array => {\n return encodeMessage(obj, FilterRPC.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FilterRPC => {\n return decodeMessage(buf, FilterRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.payload != null) {\n writer.uint32(10);\n writer.bytes(obj.payload);\n }\n\n if (obj.contentTopic != null) {\n writer.uint32(18);\n writer.string(obj.contentTopic);\n }\n\n if (obj.version != null) {\n writer.uint32(24);\n writer.uint32(obj.version);\n }\n\n if (obj.timestampDeprecated != null) {\n writer.uint32(33);\n writer.double(obj.timestampDeprecated);\n }\n\n if (obj.timestamp != null) {\n writer.uint32(80);\n writer.sint64(obj.timestamp);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.payload = reader.bytes();\n break;\n case 2:\n obj.contentTopic = reader.string();\n break;\n case 3:\n obj.version = reader.uint32();\n break;\n case 4:\n obj.timestampDeprecated = reader.double();\n break;\n case 10:\n obj.timestamp = reader.sint64();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","import { v4 as uuid } from \"uuid\";\n\nimport * as proto from \"../../proto/filter\";\n\nexport type ContentFilter = {\n contentTopic: string;\n};\n\n/**\n * FilterRPC represents a message conforming to the Waku Filter protocol\n */\nexport class FilterRPC {\n public constructor(public proto: proto.FilterRPC) {}\n\n static createRequest(\n topic: string,\n contentFilters: ContentFilter[],\n requestId?: string,\n subscribe = true\n ): FilterRPC {\n return new FilterRPC({\n requestId: requestId || uuid(),\n request: {\n subscribe,\n topic,\n contentFilters,\n },\n push: undefined,\n });\n }\n\n /**\n *\n * @param bytes Uint8Array of bytes from a FilterRPC message\n * @returns FilterRPC\n */\n static decode(bytes: Uint8Array): FilterRPC {\n const res = proto.FilterRPC.decode(bytes);\n return new FilterRPC(res);\n }\n\n /**\n * Encode the current FilterRPC request to bytes\n * @returns Uint8Array\n */\n encode(): Uint8Array {\n return proto.FilterRPC.encode(this.proto);\n }\n\n get push(): proto.MessagePush | undefined {\n return this.proto.push;\n }\n\n get requestId(): string | undefined {\n return this.proto.requestId;\n }\n}\n","import type { Stream } from \"@libp2p/interface-connection\";\nimport type { PeerId } from \"@libp2p/interface-peer-id\";\nimport type { Peer } from \"@libp2p/interface-peer-store\";\nimport type { IncomingStreamData } from \"@libp2p/interface-registrar\";\nimport debug from \"debug\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { WakuMessage as WakuMessageProto } from \"../../proto/message\";\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport { ContentFilter, FilterRPC } from \"./filter_rpc\";\nexport { ContentFilter };\n\nexport const FilterCodec = \"/vac/waku/filter/2.0.0-beta1\";\n\nconst log = debug(\"waku:filter\");\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport type FilterSubscriptionOpts = {\n /**\n * The Pubsub topic for the subscription\n */\n pubsubTopic?: string;\n /**\n * Optionally specify a PeerId for the subscription. If not included, will use a random peer.\n */\n peerId?: PeerId;\n};\n\nexport type FilterCallback = (msg: WakuMessage) => void | Promise;\n\nexport type UnsubscribeFunction = () => Promise;\n\n/**\n * Implements client side of the [Waku v2 Filter protocol](https://rfc.vac.dev/spec/12/).\n *\n * Note this currently only works in NodeJS when the Waku node is listening on a port, see:\n * - https://github.com/status-im/go-waku/issues/245\n * - https://github.com/status-im/nwaku/issues/948\n */\nexport class WakuFilter {\n pubSubTopic: string;\n private subscriptions: Map;\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.subscriptions = new Map();\n this.decryptionKeys = new Map();\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n this.libp2p\n .handle(FilterCodec, this.onRequest.bind(this))\n .catch((e) => log(\"Failed to register filter protocol\", e));\n }\n\n /**\n * @param contentTopics Array of ContentTopics to subscribe to. If empty, no messages will be returned from the filter.\n * @param callback A function that will be called on each message returned by the filter.\n * @param opts The FilterSubscriptionOpts used to narrow which messages are returned, and which peer to connect to.\n * @returns Unsubscribe function that can be used to end the subscription.\n */\n async subscribe(\n callback: FilterCallback,\n contentTopics: string[],\n opts?: FilterSubscriptionOpts\n ): Promise {\n const topic = opts?.pubsubTopic ?? this.pubSubTopic;\n const contentFilters = contentTopics.map((contentTopic) => ({\n contentTopic,\n }));\n const request = FilterRPC.createRequest(\n topic,\n contentFilters,\n undefined,\n true\n );\n\n const requestId = request.requestId;\n if (!requestId)\n throw new Error(\n \"Internal error: createRequest expected to set `requestId`\"\n );\n\n const peer = await this.getPeer(opts?.peerId);\n const stream = await this.newStream(peer);\n\n try {\n const res = await pipe(\n [request.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n\n log(\"response\", res);\n } catch (e) {\n log(\n \"Error subscribing to peer \",\n peer.id.toString(),\n \"for content topics\",\n contentTopics,\n \": \",\n e\n );\n throw e;\n }\n\n this.addCallback(requestId, callback);\n\n return async () => {\n await this.unsubscribe(topic, contentFilters, requestId, peer);\n this.removeCallback(requestId);\n };\n }\n\n private onRequest(streamData: IncomingStreamData): void {\n log(\"Receiving message push\");\n try {\n pipe(streamData.stream, lp.decode(), async (source) => {\n for await (const bytes of source) {\n const res = FilterRPC.decode(bytes.slice());\n if (res.requestId && res.push?.messages?.length) {\n await this.pushMessages(res.requestId, res.push.messages);\n }\n }\n }).then(\n () => {\n log(\"Receiving pipe closed.\");\n },\n (e) => {\n log(\"Error with receiving pipe\", e);\n }\n );\n } catch (e) {\n log(\"Error decoding message\", e);\n }\n }\n\n private async pushMessages(\n requestId: string,\n messages: WakuMessageProto[]\n ): Promise {\n const callback = this.subscriptions.get(requestId);\n if (!callback) {\n log(`No callback registered for request ID ${requestId}`);\n return;\n }\n\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n for (const message of messages) {\n const decoded = await WakuMessage.decodeProto(message, decryptionKeys);\n if (!decoded) {\n log(\"Not able to decode message\");\n continue;\n }\n callback(decoded);\n }\n }\n\n private addCallback(requestId: string, callback: FilterCallback): void {\n this.subscriptions.set(requestId, callback);\n }\n\n private removeCallback(requestId: string): void {\n this.subscriptions.delete(requestId);\n }\n\n private async unsubscribe(\n topic: string,\n contentFilters: ContentFilter[],\n requestId: string,\n peer: Peer\n ): Promise {\n const unsubscribeRequest = FilterRPC.createRequest(\n topic,\n contentFilters,\n requestId,\n false\n );\n\n const stream = await this.newStream(peer);\n try {\n await pipe([unsubscribeRequest.encode()], lp.encode(), stream.sink);\n } catch (e) {\n log(\"Error unsubscribing\", e);\n throw e;\n }\n }\n\n // Should be able to remove any at next libp2p release >0.37.3\n private async newStream(peer: Peer): Promise {\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections) {\n throw new Error(\"Failed to get a connection to the peer\");\n }\n\n // TODO: Appropriate connection selection\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: tsc is confused by the @libp2p/interface-connection type to use\n return connections[0].newStream(FilterCodec);\n }\n\n private async getPeer(peerId?: PeerId): Promise {\n let peer;\n if (peerId) {\n peer = await this.libp2p.peerStore.get(peerId);\n if (!peer) {\n throw new Error(\n `Failed to retrieve connection details for provided peer in peer store: ${peerId.toString()}`\n );\n }\n } else {\n peer = await this.randomPeer();\n if (!peer) {\n throw new Error(\n \"Failed to find known peer that registers waku filter protocol\"\n );\n }\n }\n return peer;\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received in any\n * subsequent { @link subscribe } call. This can either be a private key for\n * asymmetric encryption or a symmetric key. { @link WakuStore } will attempt to\n * decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**\n * Delete a decryption key so that it cannot be used in future { @link subscribe } calls\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n async peers(): Promise {\n return getPeersForProtocol(this.libp2p, [FilterCodec]);\n }\n\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from \"protons-runtime\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface PushRequest {\n pubSubTopic?: string;\n message?: WakuMessage;\n}\n\nexport namespace PushRequest {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.pubSubTopic != null) {\n writer.uint32(10);\n writer.string(obj.pubSubTopic);\n }\n\n if (obj.message != null) {\n writer.uint32(18);\n WakuMessage.codec().encode(obj.message, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.pubSubTopic = reader.string();\n break;\n case 2:\n obj.message = WakuMessage.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: PushRequest): Uint8Array => {\n return encodeMessage(obj, PushRequest.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PushRequest => {\n return decodeMessage(buf, PushRequest.codec());\n };\n}\n\nexport interface PushResponse {\n isSuccess?: boolean;\n info?: string;\n}\n\nexport namespace PushResponse {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.isSuccess != null) {\n writer.uint32(8);\n writer.bool(obj.isSuccess);\n }\n\n if (obj.info != null) {\n writer.uint32(18);\n writer.string(obj.info);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.isSuccess = reader.bool();\n break;\n case 2:\n obj.info = reader.string();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: PushResponse): Uint8Array => {\n return encodeMessage(obj, PushResponse.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PushResponse => {\n return decodeMessage(buf, PushResponse.codec());\n };\n}\n\nexport interface PushRPC {\n requestId?: string;\n request?: PushRequest;\n response?: PushResponse;\n}\n\nexport namespace PushRPC {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.requestId != null) {\n writer.uint32(10);\n writer.string(obj.requestId);\n }\n\n if (obj.request != null) {\n writer.uint32(18);\n PushRequest.codec().encode(obj.request, writer);\n }\n\n if (obj.response != null) {\n writer.uint32(26);\n PushResponse.codec().encode(obj.response, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.requestId = reader.string();\n break;\n case 2:\n obj.request = PushRequest.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n case 3:\n obj.response = PushResponse.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: PushRPC): Uint8Array => {\n return encodeMessage(obj, PushRPC.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PushRPC => {\n return decodeMessage(buf, PushRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.payload != null) {\n writer.uint32(10);\n writer.bytes(obj.payload);\n }\n\n if (obj.contentTopic != null) {\n writer.uint32(18);\n writer.string(obj.contentTopic);\n }\n\n if (obj.version != null) {\n writer.uint32(24);\n writer.uint32(obj.version);\n }\n\n if (obj.timestampDeprecated != null) {\n writer.uint32(33);\n writer.double(obj.timestampDeprecated);\n }\n\n if (obj.timestamp != null) {\n writer.uint32(80);\n writer.sint64(obj.timestamp);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.payload = reader.bytes();\n break;\n case 2:\n obj.contentTopic = reader.string();\n break;\n case 3:\n obj.version = reader.uint32();\n break;\n case 4:\n obj.timestampDeprecated = reader.double();\n break;\n case 10:\n obj.timestamp = reader.sint64();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","import type { Uint8ArrayList } from \"uint8arraylist\";\nimport { v4 as uuid } from \"uuid\";\n\nimport * as proto from \"../../proto/light_push\";\nimport { WakuMessage } from \"../waku_message\";\n\nexport class PushRPC {\n public constructor(public proto: proto.PushRPC) {}\n\n static createRequest(message: WakuMessage, pubSubTopic: string): PushRPC {\n return new PushRPC({\n requestId: uuid(),\n request: {\n message: message.proto,\n pubSubTopic: pubSubTopic,\n },\n response: undefined,\n });\n }\n\n static decode(bytes: Uint8ArrayList): PushRPC {\n const res = proto.PushRPC.decode(bytes);\n return new PushRPC(res);\n }\n\n encode(): Uint8Array {\n return proto.PushRPC.encode(this.proto);\n }\n\n get query(): proto.PushRequest | undefined {\n return this.proto.request;\n }\n\n get response(): proto.PushResponse | undefined {\n return this.proto.response;\n }\n}\n","import type { PeerId } from \"@libp2p/interface-peer-id\";\nimport type { Peer } from \"@libp2p/interface-peer-store\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Libp2p } from \"libp2p\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\n\nimport { PushResponse } from \"../../proto/light_push\";\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { WakuMessage } from \"../waku_message\";\n\nimport { PushRPC } from \"./push_rpc\";\n\nexport const LightPushCodec = \"/vac/waku/lightpush/2.0.0-beta1\";\nexport { PushResponse };\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport interface PushOptions {\n peerId?: PeerId;\n pubSubTopic?: string;\n}\n\n/**\n * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).\n */\nexport class WakuLightPush {\n pubSubTopic: string;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n }\n\n async push(\n message: WakuMessage,\n opts?: PushOptions\n ): Promise {\n let peer;\n if (opts?.peerId) {\n peer = await this.libp2p.peerStore.get(opts.peerId);\n if (!peer) throw \"Peer is unknown\";\n } else {\n peer = await this.randomPeer();\n }\n if (!peer) throw \"No peer available\";\n if (!peer.protocols.includes(LightPushCodec))\n throw \"Peer does not register waku light push protocol\";\n\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections) throw \"Failed to get a connection to the peer\";\n\n // TODO: Appropriate connection management\n const stream = await connections[0].newStream(LightPushCodec);\n try {\n const pubSubTopic = opts?.pubSubTopic\n ? opts.pubSubTopic\n : this.pubSubTopic;\n const query = PushRPC.createRequest(message, pubSubTopic);\n const res = await pipe(\n [query.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n try {\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n\n const response = PushRPC.decode(bytes).response;\n\n if (!response) {\n console.log(\"No response in PushRPC\");\n return null;\n }\n\n return response;\n } catch (err) {\n console.log(\"Failed to decode push reply\", err);\n }\n } catch (err) {\n console.log(\"Failed to send waku light push request\", err);\n }\n return null;\n }\n\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * light push protocol. Waku may or may not be currently connected to these\n * peers.\n */\n async peers(): Promise {\n return getPeersForProtocol(this.libp2p, [LightPushCodec]);\n }\n\n /**\n * Returns a random peer that supports light push protocol from the address\n * book (`libp2p.peerStore`). Waku may or may not be currently connected to\n * this peer.\n */\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","export const second = 1000;\nexport const minute = 60 * second;\n\n/**\n * RelayCodec is the libp2p identifier for the waku relay protocol\n */\nexport const RelayCodecs = [\n \"/vac/waku/relay/2.0.0-beta2\",\n \"/vac/waku/relay/2.0.0\",\n];\n\nexport const RelayPingContentTopic = \"/relay-ping/1/ping/null\";\n\n/**\n * RelayGossipFactor affects how many peers we will emit gossip to at each heartbeat.\n * We will send gossip to RelayGossipFactor * (total number of non-mesh peers), or\n * RelayDlazy, whichever is greater.\n */\nexport const RelayGossipFactor = 0.25;\n\n/**\n * GossipsubHeartbeatInitialDelay is the short delay before the heartbeat timer begins\n * after the router is initialized.\n */\nexport const RelayHeartbeatInitialDelay = 100;\n\n/**\n * RelayHeartbeatInterval controls the time between heartbeats.\n */\nexport const RelayHeartbeatInterval = second;\n\n/**\n * RelayPrunePeers controls the number of peers to include in prune Peer eXchange.\n * When we prune a peer that's eligible for PX (has a good score, etc), we will try to\n * send them signed peer records for up to RelayPrunePeers other peers that we\n * know of.\n */\nexport const RelayPrunePeers = 16;\n\n/**\n * RelayPruneBackoff controls the backoff time for pruned peers. This is how long\n * a peer must wait before attempting to graft into our mesh again after being pruned.\n * When pruning a peer, we send them our value of RelayPruneBackoff so they know\n * the minimum time to wait. Peers running older versions may not send a backoff time,\n * so if we receive a prune message without one, we will wait at least RelayPruneBackoff\n * before attempting to re-graft.\n */\nexport const RelayPruneBackoff = minute;\n\n/**\n * RelayFanoutTTL controls how long we keep track of the fanout state. If it's been\n * RelayFanoutTTL since we've published to a topic that we're not subscribed to,\n * we'll delete the fanout map for that topic.\n */\nexport const RelayFanoutTTL = minute;\n\n/**\n * RelayOpportunisticGraftTicks is the number of heartbeat ticks for attempting to improve the mesh\n * with opportunistic grafting. Every RelayOpportunisticGraftTicks we will attempt to select some\n * high-scoring mesh peers to replace lower-scoring ones, if the median score of our mesh peers falls\n * below a threshold\n */\nexport const RelayOpportunisticGraftTicks = 60;\n\n/**\n * RelayOpportunisticGraftPeers is the number of peers to opportunistically graft.\n */\nexport const RelayOpportunisticGraftPeers = 2;\n\n/**\n * RelayMaxIHaveLength is the maximum number of messages to include in an IHAVE message.\n * Also controls the maximum number of IHAVE ids we will accept and request with IWANT from a\n * peer within a heartbeat, to protect from IHAVE floods. You should adjust this value from the\n * default if your system is pushing more than 5000 messages in GossipsubHistoryGossip heartbeats;\n * with the defaults this is 1666 messages/s.\n */\nexport const RelayMaxIHaveLength = 5000;\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n enumeration,\n} from \"protons-runtime\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface Index {\n digest?: Uint8Array;\n receivedTime?: bigint;\n senderTime?: bigint;\n pubsubTopic?: string;\n}\n\nexport namespace Index {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.digest != null) {\n writer.uint32(10);\n writer.bytes(obj.digest);\n }\n\n if (obj.receivedTime != null) {\n writer.uint32(16);\n writer.sint64(obj.receivedTime);\n }\n\n if (obj.senderTime != null) {\n writer.uint32(24);\n writer.sint64(obj.senderTime);\n }\n\n if (obj.pubsubTopic != null) {\n writer.uint32(34);\n writer.string(obj.pubsubTopic);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.digest = reader.bytes();\n break;\n case 2:\n obj.receivedTime = reader.sint64();\n break;\n case 3:\n obj.senderTime = reader.sint64();\n break;\n case 4:\n obj.pubsubTopic = reader.string();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: Index): Uint8Array => {\n return encodeMessage(obj, Index.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Index => {\n return decodeMessage(buf, Index.codec());\n };\n}\n\nexport interface PagingInfo {\n pageSize?: bigint;\n cursor?: Index;\n direction?: PagingInfo.Direction;\n}\n\nexport namespace PagingInfo {\n export enum Direction {\n DIRECTION_BACKWARD_UNSPECIFIED = \"DIRECTION_BACKWARD_UNSPECIFIED\",\n DIRECTION_FORWARD = \"DIRECTION_FORWARD\",\n }\n\n enum __DirectionValues {\n DIRECTION_BACKWARD_UNSPECIFIED = 0,\n DIRECTION_FORWARD = 1,\n }\n\n export namespace Direction {\n export const codec = () => {\n return enumeration(__DirectionValues);\n };\n }\n\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.pageSize != null) {\n writer.uint32(8);\n writer.uint64(obj.pageSize);\n }\n\n if (obj.cursor != null) {\n writer.uint32(18);\n Index.codec().encode(obj.cursor, writer);\n }\n\n if (obj.direction != null) {\n writer.uint32(24);\n PagingInfo.Direction.codec().encode(obj.direction, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.pageSize = reader.uint64();\n break;\n case 2:\n obj.cursor = Index.codec().decode(reader, reader.uint32());\n break;\n case 3:\n obj.direction = PagingInfo.Direction.codec().decode(reader);\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: PagingInfo): Uint8Array => {\n return encodeMessage(obj, PagingInfo.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PagingInfo => {\n return decodeMessage(buf, PagingInfo.codec());\n };\n}\n\nexport interface ContentFilter {\n contentTopic?: string;\n}\n\nexport namespace ContentFilter {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.contentTopic != null) {\n writer.uint32(10);\n writer.string(obj.contentTopic);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.contentTopic = reader.string();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n}\n\nexport interface HistoryQuery {\n pubSubTopic?: string;\n contentFilters: ContentFilter[];\n pagingInfo?: PagingInfo;\n startTime?: bigint;\n endTime?: bigint;\n}\n\nexport namespace HistoryQuery {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.pubSubTopic != null) {\n writer.uint32(18);\n writer.string(obj.pubSubTopic);\n }\n\n if (obj.contentFilters != null) {\n for (const value of obj.contentFilters) {\n writer.uint32(26);\n ContentFilter.codec().encode(value, writer);\n }\n } else {\n throw new Error(\n 'Protocol error: required field \"contentFilters\" was not found in object'\n );\n }\n\n if (obj.pagingInfo != null) {\n writer.uint32(34);\n PagingInfo.codec().encode(obj.pagingInfo, writer);\n }\n\n if (obj.startTime != null) {\n writer.uint32(40);\n writer.sint64(obj.startTime);\n }\n\n if (obj.endTime != null) {\n writer.uint32(48);\n writer.sint64(obj.endTime);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n contentFilters: [],\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 2:\n obj.pubSubTopic = reader.string();\n break;\n case 3:\n obj.contentFilters.push(\n ContentFilter.codec().decode(reader, reader.uint32())\n );\n break;\n case 4:\n obj.pagingInfo = PagingInfo.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n case 5:\n obj.startTime = reader.sint64();\n break;\n case 6:\n obj.endTime = reader.sint64();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: HistoryQuery): Uint8Array => {\n return encodeMessage(obj, HistoryQuery.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): HistoryQuery => {\n return decodeMessage(buf, HistoryQuery.codec());\n };\n}\n\nexport interface HistoryResponse {\n messages: WakuMessage[];\n pagingInfo?: PagingInfo;\n error?: HistoryResponse.HistoryError;\n}\n\nexport namespace HistoryResponse {\n export enum HistoryError {\n ERROR_NONE_UNSPECIFIED = \"ERROR_NONE_UNSPECIFIED\",\n ERROR_INVALID_CURSOR = \"ERROR_INVALID_CURSOR\",\n }\n\n enum __HistoryErrorValues {\n ERROR_NONE_UNSPECIFIED = 0,\n ERROR_INVALID_CURSOR = 1,\n }\n\n export namespace HistoryError {\n export const codec = () => {\n return enumeration(__HistoryErrorValues);\n };\n }\n\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.messages != null) {\n for (const value of obj.messages) {\n writer.uint32(18);\n WakuMessage.codec().encode(value, writer);\n }\n } else {\n throw new Error(\n 'Protocol error: required field \"messages\" was not found in object'\n );\n }\n\n if (obj.pagingInfo != null) {\n writer.uint32(26);\n PagingInfo.codec().encode(obj.pagingInfo, writer);\n }\n\n if (obj.error != null) {\n writer.uint32(32);\n HistoryResponse.HistoryError.codec().encode(obj.error, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n messages: [],\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 2:\n obj.messages.push(\n WakuMessage.codec().decode(reader, reader.uint32())\n );\n break;\n case 3:\n obj.pagingInfo = PagingInfo.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n case 4:\n obj.error = HistoryResponse.HistoryError.codec().decode(reader);\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: HistoryResponse): Uint8Array => {\n return encodeMessage(obj, HistoryResponse.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): HistoryResponse => {\n return decodeMessage(buf, HistoryResponse.codec());\n };\n}\n\nexport interface HistoryRPC {\n requestId?: string;\n query?: HistoryQuery;\n response?: HistoryResponse;\n}\n\nexport namespace HistoryRPC {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.requestId != null) {\n writer.uint32(10);\n writer.string(obj.requestId);\n }\n\n if (obj.query != null) {\n writer.uint32(18);\n HistoryQuery.codec().encode(obj.query, writer);\n }\n\n if (obj.response != null) {\n writer.uint32(26);\n HistoryResponse.codec().encode(obj.response, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.requestId = reader.string();\n break;\n case 2:\n obj.query = HistoryQuery.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n case 3:\n obj.response = HistoryResponse.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: HistoryRPC): Uint8Array => {\n return encodeMessage(obj, HistoryRPC.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): HistoryRPC => {\n return decodeMessage(buf, HistoryRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.payload != null) {\n writer.uint32(10);\n writer.bytes(obj.payload);\n }\n\n if (obj.contentTopic != null) {\n writer.uint32(18);\n writer.string(obj.contentTopic);\n }\n\n if (obj.version != null) {\n writer.uint32(24);\n writer.uint32(obj.version);\n }\n\n if (obj.timestampDeprecated != null) {\n writer.uint32(33);\n writer.double(obj.timestampDeprecated);\n }\n\n if (obj.timestamp != null) {\n writer.uint32(80);\n writer.sint64(obj.timestamp);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.payload = reader.bytes();\n break;\n case 2:\n obj.contentTopic = reader.string();\n break;\n case 3:\n obj.version = reader.uint32();\n break;\n case 4:\n obj.timestampDeprecated = reader.double();\n break;\n case 10:\n obj.timestamp = reader.sint64();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport {\n encodeMessage,\n decodeMessage,\n message,\n enumeration,\n} from \"protons-runtime\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface Index {\n digest?: Uint8Array;\n receivedTime?: number;\n senderTime?: number;\n}\n\nexport namespace Index {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.digest != null) {\n writer.uint32(10);\n writer.bytes(obj.digest);\n }\n\n if (obj.receivedTime != null) {\n writer.uint32(17);\n writer.double(obj.receivedTime);\n }\n\n if (obj.senderTime != null) {\n writer.uint32(25);\n writer.double(obj.senderTime);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.digest = reader.bytes();\n break;\n case 2:\n obj.receivedTime = reader.double();\n break;\n case 3:\n obj.senderTime = reader.double();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: Index): Uint8Array => {\n return encodeMessage(obj, Index.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Index => {\n return decodeMessage(buf, Index.codec());\n };\n}\n\nexport interface PagingInfo {\n pageSize?: bigint;\n cursor?: Index;\n direction?: PagingInfo.Direction;\n}\n\nexport namespace PagingInfo {\n export enum Direction {\n DIRECTION_BACKWARD_UNSPECIFIED = \"DIRECTION_BACKWARD_UNSPECIFIED\",\n DIRECTION_FORWARD = \"DIRECTION_FORWARD\",\n }\n\n enum __DirectionValues {\n DIRECTION_BACKWARD_UNSPECIFIED = 0,\n DIRECTION_FORWARD = 1,\n }\n\n export namespace Direction {\n export const codec = () => {\n return enumeration(__DirectionValues);\n };\n }\n\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.pageSize != null) {\n writer.uint32(8);\n writer.uint64(obj.pageSize);\n }\n\n if (obj.cursor != null) {\n writer.uint32(18);\n Index.codec().encode(obj.cursor, writer);\n }\n\n if (obj.direction != null) {\n writer.uint32(24);\n PagingInfo.Direction.codec().encode(obj.direction, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.pageSize = reader.uint64();\n break;\n case 2:\n obj.cursor = Index.codec().decode(reader, reader.uint32());\n break;\n case 3:\n obj.direction = PagingInfo.Direction.codec().decode(reader);\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: PagingInfo): Uint8Array => {\n return encodeMessage(obj, PagingInfo.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PagingInfo => {\n return decodeMessage(buf, PagingInfo.codec());\n };\n}\n\nexport interface ContentFilter {\n contentTopic?: string;\n}\n\nexport namespace ContentFilter {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.contentTopic != null) {\n writer.uint32(10);\n writer.string(obj.contentTopic);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.contentTopic = reader.string();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: ContentFilter): Uint8Array => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): ContentFilter => {\n return decodeMessage(buf, ContentFilter.codec());\n };\n}\n\nexport interface HistoryQuery {\n pubSubTopic?: string;\n contentFilters: ContentFilter[];\n pagingInfo?: PagingInfo;\n startTime?: number;\n endTime?: number;\n}\n\nexport namespace HistoryQuery {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.pubSubTopic != null) {\n writer.uint32(18);\n writer.string(obj.pubSubTopic);\n }\n\n if (obj.contentFilters != null) {\n for (const value of obj.contentFilters) {\n writer.uint32(26);\n ContentFilter.codec().encode(value, writer);\n }\n } else {\n throw new Error(\n 'Protocol error: required field \"contentFilters\" was not found in object'\n );\n }\n\n if (obj.pagingInfo != null) {\n writer.uint32(34);\n PagingInfo.codec().encode(obj.pagingInfo, writer);\n }\n\n if (obj.startTime != null) {\n writer.uint32(41);\n writer.double(obj.startTime);\n }\n\n if (obj.endTime != null) {\n writer.uint32(49);\n writer.double(obj.endTime);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n contentFilters: [],\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 2:\n obj.pubSubTopic = reader.string();\n break;\n case 3:\n obj.contentFilters.push(\n ContentFilter.codec().decode(reader, reader.uint32())\n );\n break;\n case 4:\n obj.pagingInfo = PagingInfo.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n case 5:\n obj.startTime = reader.double();\n break;\n case 6:\n obj.endTime = reader.double();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: HistoryQuery): Uint8Array => {\n return encodeMessage(obj, HistoryQuery.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): HistoryQuery => {\n return decodeMessage(buf, HistoryQuery.codec());\n };\n}\n\nexport interface HistoryResponse {\n messages: WakuMessage[];\n pagingInfo?: PagingInfo;\n error?: HistoryResponse.HistoryError;\n}\n\nexport namespace HistoryResponse {\n export enum HistoryError {\n ERROR_NONE_UNSPECIFIED = \"ERROR_NONE_UNSPECIFIED\",\n ERROR_INVALID_CURSOR = \"ERROR_INVALID_CURSOR\",\n }\n\n enum __HistoryErrorValues {\n ERROR_NONE_UNSPECIFIED = 0,\n ERROR_INVALID_CURSOR = 1,\n }\n\n export namespace HistoryError {\n export const codec = () => {\n return enumeration(__HistoryErrorValues);\n };\n }\n\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.messages != null) {\n for (const value of obj.messages) {\n writer.uint32(18);\n WakuMessage.codec().encode(value, writer);\n }\n } else {\n throw new Error(\n 'Protocol error: required field \"messages\" was not found in object'\n );\n }\n\n if (obj.pagingInfo != null) {\n writer.uint32(26);\n PagingInfo.codec().encode(obj.pagingInfo, writer);\n }\n\n if (obj.error != null) {\n writer.uint32(32);\n HistoryResponse.HistoryError.codec().encode(obj.error, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n messages: [],\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 2:\n obj.messages.push(\n WakuMessage.codec().decode(reader, reader.uint32())\n );\n break;\n case 3:\n obj.pagingInfo = PagingInfo.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n case 4:\n obj.error = HistoryResponse.HistoryError.codec().decode(reader);\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: HistoryResponse): Uint8Array => {\n return encodeMessage(obj, HistoryResponse.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): HistoryResponse => {\n return decodeMessage(buf, HistoryResponse.codec());\n };\n}\n\nexport interface HistoryRPC {\n requestId?: string;\n query?: HistoryQuery;\n response?: HistoryResponse;\n}\n\nexport namespace HistoryRPC {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.requestId != null) {\n writer.uint32(10);\n writer.string(obj.requestId);\n }\n\n if (obj.query != null) {\n writer.uint32(18);\n HistoryQuery.codec().encode(obj.query, writer);\n }\n\n if (obj.response != null) {\n writer.uint32(26);\n HistoryResponse.codec().encode(obj.response, writer);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.requestId = reader.string();\n break;\n case 2:\n obj.query = HistoryQuery.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n case 3:\n obj.response = HistoryResponse.codec().decode(\n reader,\n reader.uint32()\n );\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: HistoryRPC): Uint8Array => {\n return encodeMessage(obj, HistoryRPC.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): HistoryRPC => {\n return decodeMessage(buf, HistoryRPC.codec());\n };\n}\n\nexport interface WakuMessage {\n payload?: Uint8Array;\n contentTopic?: string;\n version?: number;\n timestampDeprecated?: number;\n timestamp?: bigint;\n}\n\nexport namespace WakuMessage {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.payload != null) {\n writer.uint32(10);\n writer.bytes(obj.payload);\n }\n\n if (obj.contentTopic != null) {\n writer.uint32(18);\n writer.string(obj.contentTopic);\n }\n\n if (obj.version != null) {\n writer.uint32(24);\n writer.uint32(obj.version);\n }\n\n if (obj.timestampDeprecated != null) {\n writer.uint32(33);\n writer.double(obj.timestampDeprecated);\n }\n\n if (obj.timestamp != null) {\n writer.uint32(80);\n writer.sint64(obj.timestamp);\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {};\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.payload = reader.bytes();\n break;\n case 2:\n obj.contentTopic = reader.string();\n break;\n case 3:\n obj.version = reader.uint32();\n break;\n case 4:\n obj.timestampDeprecated = reader.double();\n break;\n case 10:\n obj.timestamp = reader.sint64();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: WakuMessage): Uint8Array => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): WakuMessage => {\n return decodeMessage(buf, WakuMessage.codec());\n };\n}\n","export enum StoreCodecs {\n V2Beta3 = \"/vac/waku/store/2.0.0-beta3\",\n V2Beta4 = \"/vac/waku/store/2.0.0-beta4\",\n}\n","import type { Uint8ArrayList } from \"uint8arraylist\";\nimport { v4 as uuid } from \"uuid\";\n\nimport * as protoV2Beta3 from \"../../proto/store_v2beta3\";\nimport * as protoV2Beta4 from \"../../proto/store_v2beta4\";\n\nimport { StoreCodecs } from \"./constants\";\n\nconst OneMillion = BigInt(1_000_000);\n\nexport enum PageDirection {\n BACKWARD = \"backward\",\n FORWARD = \"forward\",\n}\n\nexport interface Params {\n contentTopics: string[];\n pubSubTopic: string;\n pageDirection: PageDirection;\n pageSize: number;\n startTime?: Date;\n endTime?: Date;\n cursor?: protoV2Beta3.Index | protoV2Beta4.Index;\n storeCodec?: StoreCodecs;\n}\n\nexport class HistoryRPC {\n private readonly historyRpc:\n | typeof protoV2Beta3.HistoryRPC\n | typeof protoV2Beta4.HistoryRPC;\n\n private constructor(\n public readonly proto: protoV2Beta3.HistoryRPC | protoV2Beta4.HistoryRPC,\n public readonly storeCodec: StoreCodecs\n ) {\n switch (storeCodec) {\n case StoreCodecs.V2Beta3:\n this.historyRpc = protoV2Beta3.HistoryRPC;\n break;\n case StoreCodecs.V2Beta4:\n this.historyRpc = protoV2Beta4.HistoryRPC;\n break;\n default:\n throw `Internal Error: Unexpected store codec value received in constructor: ${storeCodec}`;\n }\n }\n\n get query():\n | protoV2Beta3.HistoryQuery\n | protoV2Beta4.HistoryQuery\n | undefined {\n return this.proto.query;\n }\n\n get response():\n | protoV2Beta3.HistoryResponse\n | protoV2Beta4.HistoryResponse\n | undefined {\n return this.proto.response;\n }\n\n /**\n * Create History Query.\n */\n static createQuery(params: Params): HistoryRPC {\n const storeCodec = params.storeCodec ?? StoreCodecs.V2Beta4;\n\n const contentFilters = params.contentTopics.map((contentTopic) => {\n return { contentTopic };\n });\n\n const direction = directionToProto(params.pageDirection);\n\n switch (storeCodec) {\n case StoreCodecs.V2Beta3:\n // Using function to scope variables\n return ((): HistoryRPC => {\n const pagingInfo = {\n pageSize: BigInt(params.pageSize),\n cursor: params.cursor,\n direction,\n } as protoV2Beta3.PagingInfo;\n\n let startTime, endTime;\n if (params.startTime) startTime = params.startTime.valueOf() / 1000;\n\n if (params.endTime) endTime = params.endTime.valueOf() / 1000;\n\n return new HistoryRPC(\n {\n requestId: uuid(),\n query: {\n pubSubTopic: params.pubSubTopic,\n contentFilters,\n pagingInfo,\n startTime,\n endTime,\n },\n response: undefined,\n },\n storeCodec\n );\n })();\n case StoreCodecs.V2Beta4:\n return ((): HistoryRPC => {\n const pagingInfo = {\n pageSize: BigInt(params.pageSize),\n cursor: params.cursor,\n direction,\n } as protoV2Beta4.PagingInfo;\n\n let startTime, endTime;\n if (params.startTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n startTime = BigInt(params.startTime.valueOf()) * OneMillion;\n }\n\n if (params.endTime) {\n // milliseconds 10^-3 to nanoseconds 10^-9\n endTime = BigInt(params.endTime.valueOf()) * OneMillion;\n }\n return new HistoryRPC(\n {\n requestId: uuid(),\n query: {\n pubSubTopic: params.pubSubTopic,\n contentFilters,\n pagingInfo,\n startTime,\n endTime,\n },\n response: undefined,\n },\n storeCodec\n );\n })();\n\n default:\n throw `Internal Error: Unexpected store codec value received in createQuery: ${storeCodec}`;\n }\n }\n\n decode(bytes: Uint8ArrayList): HistoryRPC {\n const res = this.historyRpc.decode(bytes);\n return new HistoryRPC(res, this.storeCodec);\n }\n\n encode(): Uint8Array {\n return this.historyRpc.encode(this.proto as any);\n }\n}\n\nfunction directionToProto(\n pageDirection: PageDirection\n): protoV2Beta4.PagingInfo.Direction {\n switch (pageDirection) {\n case PageDirection.BACKWARD:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_BACKWARD_UNSPECIFIED;\n case PageDirection.FORWARD:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_FORWARD;\n default:\n return protoV2Beta4.PagingInfo.Direction.DIRECTION_BACKWARD_UNSPECIFIED;\n }\n}\n","import type { PeerId } from \"@libp2p/interface-peer-id\";\nimport { Peer } from \"@libp2p/interface-peer-store\";\nimport debug from \"debug\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Libp2p } from \"libp2p\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\n\nimport * as protoV2Beta4 from \"../../proto/store_v2beta4\";\nimport { HistoryResponse } from \"../../proto/store_v2beta4\";\nimport { DefaultPubSubTopic, StoreCodecs } from \"../constants\";\nimport { getPeersForProtocol, selectRandomPeer } from \"../select_peer\";\nimport { hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport { HistoryRPC, PageDirection } from \"./history_rpc\";\n\nimport Error = HistoryResponse.HistoryError;\n\nconst dbg = debug(\"waku:store\");\n\nexport const DefaultPageSize = 10;\n\nexport { PageDirection, StoreCodecs };\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n}\n\nexport interface TimeFilter {\n startTime: Date;\n endTime: Date;\n}\n\nexport interface QueryOptions {\n /**\n * The peer to query. If undefined, a pseudo-random peer is selected from the connected Waku Store peers.\n */\n peerId?: PeerId;\n /**\n * The pubsub topic to pass to the query.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/).\n */\n pubSubTopic?: string;\n /**\n * The direction in which pages are retrieved:\n * - { @link PageDirection.BACKWARD }: Most recent page first.\n * - { @link PageDirection.FORWARD }: Oldest page first.\n *\n * Note: This does not affect the ordering of messages with the page\n * (oldest message is always first).\n *\n * @default { @link PageDirection.BACKWARD }\n */\n pageDirection?: PageDirection;\n /**\n * The number of message per page.\n *\n * @default { @link DefaultPageSize }\n */\n pageSize?: number;\n /**\n * Retrieve messages with a timestamp within the provided values.\n */\n timeFilter?: TimeFilter;\n /**\n * Callback called on pages of stored messages as they are retrieved.\n *\n * Allows for a faster access to the results as it is called as soon as a page\n * is received. Traversal of the pages is done automatically so this function\n * will invoked for each retrieved page.\n *\n * If the call on a page returns `true`, then traversal of the pages is aborted.\n * For example, this can be used for the caller to stop the query after a\n * specific message is found.\n */\n callback?: (messages: WakuMessage[]) => void | boolean;\n /**\n * Keys that will be used to decrypt messages.\n *\n * It can be Asymmetric Private Keys and Symmetric Keys in the same array,\n * all keys will be tried with both methods.\n */\n decryptionKeys?: Array;\n}\n\n/**\n * Implements the [Waku v2 Store protocol](https://rfc.vac.dev/spec/13/).\n *\n * The Waku Store protocol can be used to retrieved historical messages.\n */\nexport class WakuStore {\n pubSubTopic: string;\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n constructor(public libp2p: Libp2p, options?: CreateOptions) {\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n\n this.decryptionKeys = new Map();\n }\n\n /**\n * Do a query to a Waku Store to retrieve historical/missed messages.\n *\n * @param contentTopics The content topics to pass to the query, leave empty to\n * retrieve all messages.\n * @param options Optional parameters.\n *\n * @throws If not able to reach a Waku Store peer to query\n * or if an error is encountered when processing the reply.\n */\n async queryHistory(\n contentTopics: string[],\n options?: QueryOptions\n ): Promise {\n let startTime, endTime;\n\n if (options?.timeFilter) {\n startTime = options.timeFilter.startTime;\n endTime = options.timeFilter.endTime;\n }\n\n const opts = Object.assign(\n {\n pubSubTopic: this.pubSubTopic,\n pageDirection: PageDirection.BACKWARD,\n pageSize: DefaultPageSize,\n },\n options,\n { contentTopics, startTime, endTime }\n );\n\n dbg(\"Querying history with the following options\", {\n peerId: options?.peerId?.toString(),\n ...options,\n });\n\n let peer;\n if (opts.peerId) {\n peer = await this.libp2p.peerStore.get(opts.peerId);\n if (!peer)\n throw `Failed to retrieve connection details for provided peer in peer store: ${opts.peerId.toString()}`;\n } else {\n peer = await this.randomPeer();\n if (!peer)\n throw \"Failed to find known peer that registers waku store protocol\";\n }\n\n let storeCodec = \"\";\n for (const codec of Object.values(StoreCodecs)) {\n if (peer.protocols.includes(codec)) {\n storeCodec = codec;\n // Do not break as we want to keep the last value\n }\n }\n dbg(`Use store codec ${storeCodec}`);\n if (!storeCodec)\n throw `Peer does not register waku store protocol: ${peer.id.toString()}`;\n\n Object.assign(opts, { storeCodec });\n const connections = this.libp2p.connectionManager.getConnections(peer.id);\n if (!connections || !connections.length)\n throw \"Failed to get a connection to the peer\";\n\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n // Add the decryption keys passed to this function against the\n // content topics also passed to this function.\n if (opts.decryptionKeys) {\n opts.decryptionKeys.forEach((key) => {\n decryptionKeys.push({\n key: hexToBytes(key),\n contentTopics: contentTopics.length ? contentTopics : undefined,\n method: undefined,\n });\n });\n }\n\n const messages: WakuMessage[] = [];\n let cursor = undefined;\n while (true) {\n // TODO: Some connection selection logic?\n const stream = await connections[0].newStream(storeCodec);\n const queryOpts = Object.assign(opts, { cursor });\n const historyRpcQuery = HistoryRPC.createQuery(queryOpts);\n dbg(\"Querying store peer\", connections[0].remoteAddr.toString());\n\n const res = await pipe(\n [historyRpcQuery.encode()],\n lp.encode(),\n stream,\n lp.decode(),\n async (source) => await all(source)\n );\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n\n const reply = historyRpcQuery.decode(bytes);\n\n if (!reply.response) {\n dbg(\"No message returned from store: `response` field missing\");\n return messages;\n }\n\n const response = reply.response as protoV2Beta4.HistoryResponse;\n\n if (response.error && response.error !== Error.ERROR_NONE_UNSPECIFIED) {\n throw \"History response contains an Error: \" + response.error;\n }\n\n if (!response.messages || !response.messages.length) {\n // No messages left (or stored)\n dbg(\"No message returned from store: `messages` array empty\");\n return messages;\n }\n\n dbg(\n `${response.messages.length} messages retrieved for (${opts.pubSubTopic})`,\n contentTopics\n );\n\n const pageMessages: WakuMessage[] = [];\n await Promise.all(\n response.messages.map(async (protoMsg) => {\n const msg = await WakuMessage.decodeProto(protoMsg, decryptionKeys);\n\n if (msg) {\n messages.push(msg);\n pageMessages.push(msg);\n }\n })\n );\n\n let abort = false;\n if (opts.callback) {\n abort = Boolean(opts.callback(pageMessages));\n }\n\n const responsePageSize = response.pagingInfo?.pageSize;\n const queryPageSize = historyRpcQuery.query?.pagingInfo?.pageSize;\n if (\n abort ||\n // Response page size smaller than query, meaning this is the last page\n (responsePageSize && queryPageSize && responsePageSize < queryPageSize)\n ) {\n return messages;\n }\n\n cursor = response.pagingInfo?.cursor;\n if (cursor === undefined) {\n // If the server does not return cursor then there is an issue,\n // Need to abort, or we end up in an infinite loop\n dbg(\"Store response does not contain a cursor, stopping pagination\");\n return messages;\n }\n }\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received in any\n * subsequent { @link queryHistory } call. This can either be a private key for\n * asymmetric encryption or a symmetric key. { @link WakuStore } will attempt to\n * decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**cursorV2Beta4\n * Delete a decryption key that was used to attempt decryption of messages\n * received in subsequent { @link queryHistory } calls.\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * store protocol. Waku may or may not be currently connected to these peers.\n */\n async peers(): Promise {\n const codecs = [];\n for (const codec of Object.values(StoreCodecs)) {\n codecs.push(codec);\n }\n\n return getPeersForProtocol(this.libp2p, codecs);\n }\n\n /**\n * Returns a random peer that supports store protocol from the address\n * book (`libp2p.peerStore`). Waku may or may not be currently connected to\n * this peer.\n */\n async randomPeer(): Promise {\n return selectRandomPeer(await this.peers());\n }\n}\n","import type { Stream } from \"@libp2p/interface-connection\";\nimport type { PeerId } from \"@libp2p/interface-peer-id\";\nimport { peerIdFromString } from \"@libp2p/peer-id\";\nimport type { Multiaddr } from \"@multiformats/multiaddr\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport debug from \"debug\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { FilterCodec, WakuFilter } from \"./waku_filter\";\nimport { LightPushCodec, WakuLightPush } from \"./waku_light_push\";\nimport { DecryptionMethod, WakuMessage } from \"./waku_message\";\nimport { WakuRelay } from \"./waku_relay\";\nimport { RelayCodecs, RelayPingContentTopic } from \"./waku_relay/constants\";\nimport { StoreCodecs, WakuStore } from \"./waku_store\";\n\nexport const DefaultPingKeepAliveValueSecs = 0;\nexport const DefaultRelayKeepAliveValueSecs = 5 * 60;\n\nconst log = debug(\"waku:waku\");\n\nexport enum Protocols {\n Relay = \"relay\",\n Store = \"store\",\n LightPush = \"lightpush\",\n Filter = \"filter\",\n}\n\nexport interface WakuOptions {\n /**\n * Set keep alive frequency in seconds: Waku will send a `/ipfs/ping/1.0.0`\n * request to each peer after the set number of seconds. Set to 0 to disable.\n *\n * @default {@link DefaultPingKeepAliveValueSecs}\n */\n pingKeepAlive?: number;\n /**\n * Set keep alive frequency in seconds: Waku will send a ping message over\n * relay to each peer after the set number of seconds. Set to 0 to disable.\n *\n * @default {@link DefaultRelayKeepAliveValueSecs}\n */\n relayKeepAlive?: number;\n decryptionKeys?: Array;\n}\n\nexport class Waku {\n public libp2p: Libp2p;\n public relay: WakuRelay;\n public store: WakuStore;\n public filter: WakuFilter;\n public lightPush: WakuLightPush;\n\n private pingKeepAliveTimers: {\n [peer: string]: ReturnType;\n };\n private relayKeepAliveTimers: {\n [peer: string]: ReturnType;\n };\n\n constructor(\n options: WakuOptions,\n libp2p: Libp2p,\n store: WakuStore,\n lightPush: WakuLightPush,\n filter: WakuFilter\n ) {\n this.libp2p = libp2p;\n this.relay = libp2p.pubsub as unknown as WakuRelay;\n this.store = store;\n this.filter = filter;\n this.lightPush = lightPush;\n this.pingKeepAliveTimers = {};\n this.relayKeepAliveTimers = {};\n\n const pingKeepAlive =\n options.pingKeepAlive || DefaultPingKeepAliveValueSecs;\n const relayKeepAlive =\n options.relayKeepAlive || DefaultRelayKeepAliveValueSecs;\n\n libp2p.connectionManager.addEventListener(\"peer:connect\", (evt) => {\n this.startKeepAlive(evt.detail.remotePeer, pingKeepAlive, relayKeepAlive);\n });\n\n /**\n * NOTE: Event is not being emitted on closing nor losing a connection.\n * @see https://github.com/libp2p/js-libp2p/issues/939\n * @see https://github.com/status-im/js-waku/issues/252\n *\n * >This event will be triggered anytime we are disconnected from another peer,\n * >regardless of the circumstances of that disconnection.\n * >If we happen to have multiple connections to a peer,\n * >this event will **only** be triggered when the last connection is closed.\n * @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100\n */\n libp2p.connectionManager.addEventListener(\"peer:disconnect\", (evt) => {\n this.stopKeepAlive(evt.detail.remotePeer);\n });\n\n options?.decryptionKeys?.forEach((key) => {\n this.addDecryptionKey(key);\n });\n }\n\n /**\n * Dials to the provided peer.\n *\n * @param peer The peer to dial\n * @param protocols Waku protocols we expect from the peer; Default to Relay\n */\n async dial(\n peer: PeerId | Multiaddr,\n protocols?: Protocols[]\n ): Promise {\n const _protocols = protocols ?? [Protocols.Relay];\n\n const codecs: string[] = [];\n if (_protocols.includes(Protocols.Relay)) {\n RelayCodecs.forEach((codec) => codecs.push(codec));\n }\n if (_protocols.includes(Protocols.Store)) {\n for (const codec of Object.values(StoreCodecs)) {\n codecs.push(codec);\n }\n }\n if (_protocols.includes(Protocols.LightPush)) {\n codecs.push(LightPushCodec);\n }\n if (_protocols.includes(Protocols.Filter)) {\n codecs.push(FilterCodec);\n }\n\n return this.libp2p.dialProtocol(peer, codecs);\n }\n\n /**\n * Add peer to address book, it will be auto-dialed in the background.\n */\n addPeerToAddressBook(\n peerId: PeerId | string,\n multiaddrs: Multiaddr[] | string[]\n ): void {\n let peer;\n if (typeof peerId === \"string\") {\n peer = peerIdFromString(peerId);\n } else {\n peer = peerId;\n }\n const addresses = multiaddrs.map((addr: Multiaddr | string) => {\n if (typeof addr === \"string\") {\n return multiaddr(addr);\n } else {\n return addr;\n }\n });\n this.libp2p.peerStore.addressBook.set(peer, addresses);\n }\n\n async start(): Promise {\n await this.libp2p.start();\n }\n\n async stop(): Promise {\n this.stopAllKeepAlives();\n await this.libp2p.stop();\n }\n\n isStarted(): boolean {\n return this.libp2p.isStarted();\n }\n\n /**\n * Register a decryption key to attempt decryption of messages received via\n * { @link WakuRelay } and { @link WakuStore }. This can either be a private key for\n * asymmetric encryption or a symmetric key.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.relay.addDecryptionKey(key, options);\n this.store.addDecryptionKey(key, options);\n this.filter.addDecryptionKey(key, options);\n }\n\n /**\n * Delete a decryption key that was used to attempt decryption of messages\n * received via { @link WakuRelay } or { @link WakuStore }.\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.relay.deleteDecryptionKey(key);\n this.store.deleteDecryptionKey(key);\n this.filter.deleteDecryptionKey(key);\n }\n\n /**\n * Return the local multiaddr with peer id on which libp2p is listening.\n *\n * @throws if libp2p is not listening on localhost.\n */\n getLocalMultiaddrWithID(): string {\n const localMultiaddr = this.libp2p\n .getMultiaddrs()\n .find((addr) => addr.toString().match(/127\\.0\\.0\\.1/));\n if (!localMultiaddr || localMultiaddr.toString() === \"\") {\n throw \"Not listening on localhost\";\n }\n return localMultiaddr + \"/p2p/\" + this.libp2p.peerId.toString();\n }\n\n private startKeepAlive(\n peerId: PeerId,\n pingPeriodSecs: number,\n relayPeriodSecs: number\n ): void {\n // Just in case a timer already exist for this peer\n this.stopKeepAlive(peerId);\n\n const peerIdStr = peerId.toString();\n\n if (pingPeriodSecs !== 0) {\n this.pingKeepAliveTimers[peerIdStr] = setInterval(() => {\n this.libp2p.ping(peerId).catch((e) => {\n log(`Ping failed (${peerIdStr})`, e);\n });\n }, pingPeriodSecs * 1000);\n }\n\n if (relayPeriodSecs !== 0) {\n this.relayKeepAliveTimers[peerIdStr] = setInterval(() => {\n log(\"Sending Waku Relay ping message\");\n WakuMessage.fromBytes(new Uint8Array(), RelayPingContentTopic).then(\n (wakuMsg) => this.relay.send(wakuMsg)\n );\n }, relayPeriodSecs * 1000);\n }\n }\n\n private stopKeepAlive(peerId: PeerId): void {\n const peerIdStr = peerId.toString();\n\n if (this.pingKeepAliveTimers[peerIdStr]) {\n clearInterval(this.pingKeepAliveTimers[peerIdStr]);\n delete this.pingKeepAliveTimers[peerIdStr];\n }\n\n if (this.relayKeepAliveTimers[peerIdStr]) {\n clearInterval(this.relayKeepAliveTimers[peerIdStr]);\n delete this.relayKeepAliveTimers[peerIdStr];\n }\n }\n\n private stopAllKeepAlives(): void {\n for (const timer of [\n ...Object.values(this.pingKeepAliveTimers),\n ...Object.values(this.relayKeepAliveTimers),\n ]) {\n clearInterval(timer);\n }\n\n this.pingKeepAliveTimers = {};\n this.relayKeepAliveTimers = {};\n }\n}\n","\nexport const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.publicKey != null) {\n writer.uint32(10)\n writer.bytes(obj.publicKey)\n } else {\n throw new Error('Protocol error: required field \"publicKey\" was not found in object')\n }\n\n if (obj.payloadType != null) {\n writer.uint32(18)\n writer.bytes(obj.payloadType)\n } else {\n throw new Error('Protocol error: required field \"payloadType\" was not found in object')\n }\n\n if (obj.payload != null) {\n writer.uint32(26)\n writer.bytes(obj.payload)\n } else {\n throw new Error('Protocol error: required field \"payload\" was not found in object')\n }\n\n if (obj.signature != null) {\n writer.uint32(42)\n writer.bytes(obj.signature)\n } else {\n throw new Error('Protocol error: required field \"signature\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes()\n break\n case 2:\n obj.payloadType = reader.bytes()\n break\n case 3:\n obj.payload = reader.bytes()\n break\n case 5:\n obj.signature = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.publicKey == null) {\n throw new Error('Protocol error: value for required field \"publicKey\" was not found in protobuf')\n }\n\n if (obj.payloadType == null) {\n throw new Error('Protocol error: value for required field \"payloadType\" was not found in protobuf')\n }\n\n if (obj.payload == null) {\n throw new Error('Protocol error: value for required field \"payload\" was not found in protobuf')\n }\n\n if (obj.signature == null) {\n throw new Error('Protocol error: value for required field \"signature\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Envelope): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Envelope => {\n return decodeMessage(buf, Envelope.codec())\n }\n}\n","import errCode from 'err-code'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { codes } from '../errors.js'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Record, Envelope } from '@libp2p/interface-record'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { unsigned } from 'uint8-varint'\n\nexport interface EnvelopeInit {\n peerId: PeerId\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList) => {\n const envelopeData = Protobuf.decode(data)\n const peerId = await peerIdFromKeys(envelopeData.publicKey)\n\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\n }\n\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record: Record, peerId: PeerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key')\n }\n\n const domain = record.domain\n const payloadType = record.codec\n const payload = record.marshal()\n const signData = formatSignaturePayload(domain, payloadType, payload)\n const key = await unmarshalPrivateKey(peerId.privateKey)\n const signature = await key.sign(signData.subarray())\n\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n })\n }\n\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data: Uint8Array | Uint8ArrayList, domain: string) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw errCode(new Error('envelope signature is not valid for the given domain'), codes.ERR_SIGNATURE_NOT_VALID)\n }\n\n return envelope\n }\n\n public peerId: PeerId\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: EnvelopeInit) {\n const { peerId, payloadType, payload, signature } = init\n\n this.peerId = peerId\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other: Envelope) {\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key')\n }\n\n const key = unmarshalPublicKey(this.peerId.publicKey)\n\n return await key.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = unsigned.encode(domainUint8Array.byteLength)\n const payloadTypeLength = unsigned.encode(payloadType.length)\n const payloadLength = unsigned.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.multiaddr != null) {\n writer.uint32(10)\n writer.bytes(obj.multiaddr)\n } else {\n throw new Error('Protocol error: required field \"multiaddr\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.multiaddr == null) {\n throw new Error('Protocol error: value for required field \"multiaddr\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: AddressInfo): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.peerId != null) {\n writer.uint32(10)\n writer.bytes(obj.peerId)\n } else {\n throw new Error('Protocol error: required field \"peerId\" was not found in object')\n }\n\n if (obj.seq != null) {\n writer.uint32(16)\n writer.uint64(obj.seq)\n } else {\n throw new Error('Protocol error: required field \"seq\" was not found in object')\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n writer.uint32(26)\n PeerRecord.AddressInfo.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"addresses\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes()\n break\n case 2:\n obj.seq = reader.uint64()\n break\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.peerId == null) {\n throw new Error('Protocol error: value for required field \"peerId\" was not found in protobuf')\n }\n\n if (obj.seq == null) {\n throw new Error('Protocol error: value for required field \"seq\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerRecord): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec())\n }\n}\n","\n// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1])\n","import { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\n}\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n const peerRecord = Protobuf.decode(buf)\n const peerId = peerIdFromBytes(peerRecord.peerId)\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => new Multiaddr(a.multiaddr))\n const seqNumber = peerRecord.seq\n\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\n\n /**\n * Marshal a record to be used in an envelope\n */\n marshal () {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown) {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n","/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals (a: any[], b: any[]) {\n const sort = (a: any, b: any) => a.toString().localeCompare(b.toString())\n return a.length === b.length && b.sort(sort) && a.sort(sort).every((item, index) => b[index].equals(item))\n}\n","import debug from 'debug'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base64 } from 'multiformats/bases/base64'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { CID } from 'multiformats/cid'\nimport type { Key } from 'interface-datastore'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array) => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID) => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key) => {\n return v == null ? 'undefined' : v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error: (formatter: any, ...args: any[]) => void\n trace: (formatter: any, ...args: any[]) => void\n enabled: boolean\n}\n\nexport function logger (name: string): Logger {\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace: debug(`${name}:trace`)\n })\n}\n\nexport function disable () {\n debug.disable()\n}\n\nexport function enable (namespaces: string) {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string) {\n return debug.enabled(namespaces)\n}\n","import type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nexport interface IncomingStreamData {\n stream: Stream\n connection: Connection\n}\n\nexport interface StreamHandler {\n (data: IncomingStreamData): void\n}\n\nexport interface StreamHandlerOptions {\n /**\n * How many incoming streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxInboundStreams?: number\n\n /**\n * How many outgoing streams can be open for this protocol at the same time on each connection (default: 1)\n */\n maxOutboundStreams?: number\n}\n\nexport interface StreamHandlerRecord {\n handler: StreamHandler\n options: StreamHandlerOptions\n}\n\nexport interface Registrar {\n getProtocols: () => string[]\n handle: (protocol: string, handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n unhandle: (protocol: string) => Promise\n getHandler: (protocol: string) => StreamHandlerRecord\n\n register: (protocol: string, topology: Topology) => Promise\n unregister: (id: string) => void\n getTopologies: (protocol: string) => Topology[]\n}\n\nexport interface onConnectHandler {\n (peerId: PeerId, conn: Connection): void\n}\n\nexport interface onDisconnectHandler {\n (peerId: PeerId, conn?: Connection): void\n}\n\nexport interface TopologyInit {\n /**\n * minimum needed connections\n */\n min?: number\n\n /**\n * maximum needed connections\n */\n max?: number\n onConnect?: onConnectHandler\n onDisconnect?: onDisconnectHandler\n}\n\nexport interface Topology {\n min: number\n max: number\n peers: Set\n\n onConnect: (peerId: PeerId, conn: Connection) => void\n onDisconnect: (peerId: PeerId) => void\n setRegistrar: (registrar: Registrar) => Promise\n}\n\nexport const topologySymbol = Symbol.for('@libp2p/topology')\n\nexport function isTopology (other: any): other is Topology {\n return other != null && Boolean(other[topologySymbol])\n}\n","import { topologySymbol as symbol } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Topology, TopologyInit, onConnectHandler, onDisconnectHandler, Registrar } from '@libp2p/interface-registrar'\n\nconst noop = () => {}\n\nclass TopologyImpl implements Topology {\n public min: number\n public max: number\n\n /**\n * Set of peers that support the protocol\n */\n public peers: Set\n public onConnect: onConnectHandler\n public onDisconnect: onDisconnectHandler\n\n protected registrar: Registrar | undefined\n\n constructor (init: TopologyInit) {\n this.min = init.min ?? 0\n this.max = init.max ?? Infinity\n this.peers = new Set()\n\n this.onConnect = init.onConnect ?? noop\n this.onDisconnect = init.onDisconnect ?? noop\n }\n\n get [Symbol.toStringTag] () {\n return symbol.toString()\n }\n\n get [symbol] () {\n return true\n }\n\n async setRegistrar (registrar: Registrar) {\n this.registrar = registrar\n }\n\n /**\n * Notify about peer disconnected event\n */\n disconnect (peerId: PeerId) {\n this.onDisconnect(peerId)\n }\n}\n\nexport function createTopology (init: TopologyInit): Topology {\n return new TopologyImpl(init)\n}\n","\nexport interface EventCallback { (evt: EventType): void }\nexport interface EventObject { handleEvent: EventCallback }\nexport type EventHandler = EventCallback | EventObject\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n * Adds types to the EventTarget class. Hopefully this won't be necessary forever.\n *\n * https://github.com/microsoft/TypeScript/issues/28357\n * https://github.com/microsoft/TypeScript/issues/43477\n * https://github.com/microsoft/TypeScript/issues/299\n * etc\n */\nexport class EventEmitter extends EventTarget {\n #listeners: Map = new Map()\n\n listenerCount (type: string) {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener(type: K, listener: EventHandler | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener(type: K, listener?: EventHandler | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n}\n\n/**\n * CustomEvent is a standard event but it's not supported by node.\n *\n * Remove this when https://github.com/nodejs/node/issues/40678 is closed.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n */\nclass CustomEventPolyfill extends Event {\n /** Returns any custom data event was created with. Typically used for synthetic events. */\n public detail: T\n\n constructor (message: string, data?: EventInit & { detail: T }) {\n super(message, data)\n // @ts-expect-error could be undefined\n this.detail = data?.detail\n }\n}\n\nexport const CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill\n",null,null,null,null,null,null,"import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Pushable } from 'it-pushable'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nexport const StrictSign = 'StrictSign'\n\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nexport const StrictNoSign = 'StrictNoSign'\n\nexport type SignaturePolicy = typeof StrictSign | typeof StrictNoSign\n\nexport interface SignedMessage {\n type: 'signed'\n from: PeerId\n topic: string\n data: Uint8Array\n sequenceNumber: bigint\n signature: Uint8Array\n key: Uint8Array\n}\n\nexport interface UnsignedMessage {\n type: 'unsigned'\n topic: string\n data: Uint8Array\n}\n\nexport type Message = SignedMessage | UnsignedMessage\n\nexport interface PubSubRPCMessage {\n from?: Uint8Array\n topic?: string\n data?: Uint8Array\n sequenceNumber?: Uint8Array\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCSubscription {\n subscribe?: boolean\n topic?: string\n}\n\nexport interface PubSubRPC {\n subscriptions: PubSubRPCSubscription[]\n messages: PubSubRPCMessage[]\n}\n\nexport interface PeerStreams extends EventEmitter {\n id: PeerId\n protocol: string\n outboundStream?: Pushable\n inboundStream?: AsyncIterable\n isWritable: boolean\n\n close: () => void\n write: (buf: Uint8Array | Uint8ArrayList) => void\n attachInboundStream: (stream: Stream) => AsyncIterable\n attachOutboundStream: (stream: Stream) => Promise>\n}\n\nexport interface PubSubInit {\n enabled?: boolean\n\n multicodecs?: string[]\n\n /**\n * defines how signatures should be handled\n */\n globalSignaturePolicy?: SignaturePolicy\n\n /**\n * if can relay messages not subscribed\n */\n canRelayMessage?: boolean\n\n /**\n * if publish should emit to self, if subscribed\n */\n emitSelf?: boolean\n\n /**\n * handle this many incoming pubsub messages concurrently\n */\n messageProcessingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the pubsub protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the pubsub protocol per-connection\n */\n maxOutboundStreams?: number\n}\n\ninterface Subscription {\n topic: string\n subscribe: boolean\n}\n\nexport interface SubscriptionChangeData {\n peerId: PeerId\n subscriptions: Subscription[]\n}\n\nexport interface PubSubEvents {\n 'subscription-change': CustomEvent\n 'message': CustomEvent\n}\n\nexport interface PublishResult {\n recipients: PeerId[]\n}\n\nexport interface PubSub extends EventEmitter {\n globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n multicodecs: string[]\n\n getPeers: () => PeerId[]\n getTopics: () => string[]\n subscribe: (topic: string) => void\n unsubscribe: (topic: string) => void\n getSubscribers: (topic: string) => PeerId[]\n publish: (topic: string, data: Uint8Array) => Promise\n}\n\nexport interface PeerStreamEvents {\n 'stream:inbound': CustomEvent\n 'stream:outbound': CustomEvent\n 'close': CustomEvent\n}\n",null,null,null,null,null,null,"\n/**\n * Implemented by components that have a lifecycle\n */\nexport interface Startable {\n isStarted: () => boolean\n\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?: () => void | Promise\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?: () => void | Promise\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?: () => void | Promise\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop: () => void | Promise\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?: () => void | Promise\n}\n\nexport function isStartable (obj: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\nexport async function start (...objs: any[]) {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\nexport async function stop (...objs: any[]) {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n","import errCode from 'err-code'\nimport type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AddressManager } from '@libp2p/interface-address-manager'\nimport { isStartable, Startable } from '@libp2p/interfaces/startable'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport type { TransportManager, Upgrader } from '@libp2p/interface-transport'\nimport type { Datastore } from 'interface-datastore'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\n\nexport interface Initializable {\n init: (components: Components) => void\n}\n\nexport function isInitializable (obj: any): obj is Initializable {\n return obj != null && typeof obj.init === 'function'\n}\n\nexport interface ComponentsInit {\n peerId?: PeerId\n addressManager?: AddressManager\n peerStore?: PeerStore\n upgrader?: Upgrader\n metrics?: Metrics\n registrar?: Registrar\n connectionManager?: ConnectionManager\n transportManager?: TransportManager\n connectionGater?: ConnectionGater\n contentRouting?: ContentRouting\n peerRouting?: PeerRouting\n datastore?: Datastore\n connectionProtector?: ConnectionProtector\n dht?: DualDHT\n pubsub?: PubSub\n}\n\nexport class Components implements Startable {\n private peerId?: PeerId\n private addressManager?: AddressManager\n private peerStore?: PeerStore\n private upgrader?: Upgrader\n private metrics?: Metrics\n private registrar?: Registrar\n private connectionManager?: ConnectionManager\n private transportManager?: TransportManager\n private connectionGater?: ConnectionGater\n private contentRouting?: ContentRouting\n private peerRouting?: PeerRouting\n private datastore?: Datastore\n private connectionProtector?: ConnectionProtector\n private dht?: DualDHT\n private pubsub?: PubSub\n private started = false\n\n constructor (init: ComponentsInit = {}) {\n if (init.peerId != null) {\n this.setPeerId(init.peerId)\n }\n\n if (init.addressManager != null) {\n this.setAddressManager(init.addressManager)\n }\n\n if (init.peerStore != null) {\n this.setPeerStore(init.peerStore)\n }\n\n if (init.upgrader != null) {\n this.setUpgrader(init.upgrader)\n }\n\n if (init.metrics != null) {\n this.setMetrics(init.metrics)\n }\n\n if (init.registrar != null) {\n this.setRegistrar(init.registrar)\n }\n\n if (init.connectionManager != null) {\n this.setConnectionManager(init.connectionManager)\n }\n\n if (init.transportManager != null) {\n this.setTransportManager(init.transportManager)\n }\n\n if (init.connectionGater != null) {\n this.setConnectionGater(init.connectionGater)\n }\n\n if (init.contentRouting != null) {\n this.setContentRouting(init.contentRouting)\n }\n\n if (init.peerRouting != null) {\n this.setPeerRouting(init.peerRouting)\n }\n\n if (init.datastore != null) {\n this.setDatastore(init.datastore)\n }\n\n if (init.connectionProtector != null) {\n this.setConnectionProtector(init.connectionProtector)\n }\n\n if (init.dht != null) {\n this.setDHT(init.dht)\n }\n\n if (init.pubsub != null) {\n this.setPubSub(init.pubsub)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async beforeStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStart != null) {\n await startable.beforeStart()\n }\n })\n )\n }\n\n async start () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.start()\n })\n )\n\n this.started = true\n }\n\n async afterStart () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStart != null) {\n await startable.afterStart()\n }\n })\n )\n }\n\n async beforeStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.beforeStop != null) {\n await startable.beforeStop()\n }\n })\n )\n }\n\n async stop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n await startable.stop()\n })\n )\n\n this.started = false\n }\n\n async afterStop () {\n await Promise.all(\n Object.values(this).filter(obj => isStartable(obj)).map(async (startable: Startable) => {\n if (startable.afterStop != null) {\n await startable.afterStop()\n }\n })\n )\n }\n\n setPeerId (peerId: PeerId) {\n this.peerId = peerId\n\n return peerId\n }\n\n getPeerId (): PeerId {\n if (this.peerId == null) {\n throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerId\n }\n\n setMetrics (metrics: Metrics) {\n this.metrics = metrics\n\n if (isInitializable(metrics)) {\n metrics.init(this)\n }\n\n return metrics\n }\n\n getMetrics (): Metrics | undefined {\n return this.metrics\n }\n\n setAddressManager (addressManager: AddressManager) {\n this.addressManager = addressManager\n\n if (isInitializable(addressManager)) {\n addressManager.init(this)\n }\n\n return addressManager\n }\n\n getAddressManager (): AddressManager {\n if (this.addressManager == null) {\n throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.addressManager\n }\n\n setPeerStore (peerStore: PeerStore) {\n this.peerStore = peerStore\n\n if (isInitializable(peerStore)) {\n peerStore.init(this)\n }\n\n return peerStore\n }\n\n getPeerStore (): PeerStore {\n if (this.peerStore == null) {\n throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerStore\n }\n\n setUpgrader (upgrader: Upgrader) {\n this.upgrader = upgrader\n\n if (isInitializable(upgrader)) {\n upgrader.init(this)\n }\n\n return upgrader\n }\n\n getUpgrader (): Upgrader {\n if (this.upgrader == null) {\n throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.upgrader\n }\n\n setRegistrar (registrar: Registrar) {\n this.registrar = registrar\n\n if (isInitializable(registrar)) {\n registrar.init(this)\n }\n\n return registrar\n }\n\n getRegistrar (): Registrar {\n if (this.registrar == null) {\n throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.registrar\n }\n\n setConnectionManager (connectionManager: ConnectionManager) {\n this.connectionManager = connectionManager\n\n if (isInitializable(connectionManager)) {\n connectionManager.init(this)\n }\n\n return connectionManager\n }\n\n getConnectionManager (): ConnectionManager {\n if (this.connectionManager == null) {\n throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.connectionManager\n }\n\n setTransportManager (transportManager: TransportManager) {\n this.transportManager = transportManager\n\n if (isInitializable(transportManager)) {\n transportManager.init(this)\n }\n\n return transportManager\n }\n\n getTransportManager (): TransportManager {\n if (this.transportManager == null) {\n throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.transportManager\n }\n\n setConnectionGater (connectionGater: ConnectionGater) {\n this.connectionGater = connectionGater\n\n if (isInitializable(connectionGater)) {\n connectionGater.init(this)\n }\n\n return connectionGater\n }\n\n getConnectionGater (): ConnectionGater {\n if (this.connectionGater == null) {\n throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.connectionGater\n }\n\n setContentRouting (contentRouting: ContentRouting) {\n this.contentRouting = contentRouting\n\n if (isInitializable(contentRouting)) {\n contentRouting.init(this)\n }\n\n return contentRouting\n }\n\n getContentRouting (): ContentRouting {\n if (this.contentRouting == null) {\n throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.contentRouting\n }\n\n setPeerRouting (peerRouting: PeerRouting) {\n this.peerRouting = peerRouting\n\n if (isInitializable(peerRouting)) {\n peerRouting.init(this)\n }\n\n return peerRouting\n }\n\n getPeerRouting (): PeerRouting {\n if (this.peerRouting == null) {\n throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.peerRouting\n }\n\n setDatastore (datastore: Datastore) {\n this.datastore = datastore\n\n if (isInitializable(datastore)) {\n datastore.init(this)\n }\n\n return datastore\n }\n\n getDatastore (): Datastore {\n if (this.datastore == null) {\n throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.datastore\n }\n\n setConnectionProtector (connectionProtector: ConnectionProtector) {\n this.connectionProtector = connectionProtector\n\n if (isInitializable(connectionProtector)) {\n connectionProtector.init(this)\n }\n\n return connectionProtector\n }\n\n getConnectionProtector (): ConnectionProtector | undefined {\n return this.connectionProtector\n }\n\n setDHT (dht: DualDHT) {\n this.dht = dht\n\n if (isInitializable(dht)) {\n dht.init(this)\n }\n\n return dht\n }\n\n getDHT (): DualDHT {\n if (this.dht == null) {\n throw errCode(new Error('dht not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.dht\n }\n\n setPubSub (pubsub: PubSub) {\n this.pubsub = pubsub\n\n if (isInitializable(pubsub)) {\n pubsub.init(this)\n }\n\n return pubsub\n }\n\n getPubSub (): PubSub {\n if (this.pubsub == null) {\n throw errCode(new Error('pubsub not set'), 'ERR_SERVICE_MISSING')\n }\n\n return this.pubsub\n }\n}\n",null,null,null,null,"// @ts-expect-error types are missing\nimport forgePbkdf2 from 'node-forge/lib/pbkdf2.js'\n// @ts-expect-error types are missing\nimport forgeUtil from 'node-forge/lib/util.js'\nimport errcode from 'err-code'\n\n/**\n * Maps an IPFS hash name to its node-forge equivalent.\n *\n * See https://github.com/multiformats/multihash/blob/master/hashtable.csv\n *\n * @private\n */\nconst hashName = {\n sha1: 'sha1',\n 'sha2-256': 'sha256',\n 'sha2-512': 'sha512'\n}\n\n/**\n * Computes the Password-Based Key Derivation Function 2.\n */\nexport default function pbkdf2 (password: string, salt: string, iterations: number, keySize: number, hash: string): string {\n if (hash !== 'sha1' && hash !== 'sha2-256' && hash !== 'sha2-512') {\n const types = Object.keys(hashName).join(' / ')\n throw errcode(new Error(`Hash '${hash}' is unknown or not supported. Must be ${types}`), 'ERR_UNSUPPORTED_HASH_TYPE')\n }\n\n const hasher = hashName[hash]\n const dek = forgePbkdf2(\n password,\n salt,\n iterations,\n keySize,\n hasher\n )\n\n return forgeUtil.encode64(dek, null)\n}\n",null,null,"import { randomBytes } from '@libp2p/crypto'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport type { Message, PubSubRPCMessage } from '@libp2p/interface-pubsub'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport { codes } from './errors.js'\nimport errcode from 'err-code'\n\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno (): bigint {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`)\n}\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key: Uint8Array, seqno: bigint) => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16')\n\n const msgId = new Uint8Array(key.length + seqnoBytes.length)\n msgId.set(key, 0)\n msgId.set(seqnoBytes, key.length)\n\n return msgId\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data: Uint8Array) => {\n return sha256.encode(data)\n}\n\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a: Set | number[], b: Set | number[]) => {\n let bHas\n if (Array.isArray(b)) {\n bHas = (val: number) => b.includes(val)\n } else {\n bHas = (val: number) => b.has(val)\n }\n\n for (const val of a) {\n if (bHas(val)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Make everything an array\n */\nexport const ensureArray = function (maybeArray: T | T[]) {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray]\n }\n\n return maybeArray\n}\n\nexport const toMessage = (message: PubSubRPCMessage): Message => {\n if (message.from == null) {\n throw errcode(new Error('RPC message was missing from'), codes.ERR_MISSING_FROM)\n }\n\n if (message.sequenceNumber == null || message.from == null || message.signature == null || message.key == null) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n }\n }\n\n return {\n type: 'signed',\n from: peerIdFromBytes(message.from),\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature,\n key: message.key\n }\n}\n\nexport const toRpcMessage = (message: Message): PubSubRPCMessage => {\n if (message.type === 'signed') {\n return {\n from: message.from.multihash.bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n key: message.key\n }\n }\n\n return {\n data: message.data,\n topic: message.topic\n }\n}\n\nexport const bigIntToBytes = (num: bigint): Uint8Array => {\n let str = num.toString(16)\n\n if (str.length % 2 !== 0) {\n str = `0${str}`\n }\n\n return uint8ArrayFromString(str, 'base16')\n}\n\nexport const bigIntFromBytes = (num: Uint8Array): bigint => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`)\n}\n",null,null,"\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n","import { AbortError } from './abort-error.js'\nimport { getIterator } from 'get-iterator'\nimport type { Duplex, Source, Sink } from 'it-stream-types'\n\nexport interface Options {\n onReturnError?: (err: Error) => void\n onAbort?: (source: Source) => void\n abortMessage?: string\n abortCode?: string\n returnOnAbort?: boolean\n}\n\n// Wrap an iterator to make it abortable, allow cleanup when aborted via onAbort\nexport function abortableSource (source: Source, signal: AbortSignal, options?: Options) {\n const opts: Options = options ?? {}\n const iterator = getIterator(source)\n\n async function * abortable () {\n let nextAbortHandler: (() => void) | null\n const abortHandler = () => {\n if (nextAbortHandler != null) nextAbortHandler()\n }\n\n signal.addEventListener('abort', abortHandler)\n\n while (true) {\n let result: IteratorResult\n try {\n if (signal.aborted) {\n const { abortMessage, abortCode } = opts\n throw new AbortError(abortMessage, abortCode)\n }\n\n const abort = new Promise((resolve, reject) => { // eslint-disable-line no-loop-func\n nextAbortHandler = () => {\n const { abortMessage, abortCode } = opts\n reject(new AbortError(abortMessage, abortCode))\n }\n })\n\n // Race the iterator and the abort signals\n result = await Promise.race([abort, iterator.next()])\n nextAbortHandler = null\n } catch (err: any) {\n signal.removeEventListener('abort', abortHandler)\n\n // Might not have been aborted by a known signal\n const isKnownAborter = err.type === 'aborted' && signal.aborted\n\n if (isKnownAborter && (opts.onAbort != null)) {\n // Do any custom abort handling for the iterator\n await opts.onAbort(source)\n }\n\n // End the iterator if it is a generator\n if (typeof iterator.return === 'function') {\n try {\n const p = iterator.return()\n\n if (p instanceof Promise) { // eslint-disable-line max-depth\n p.catch(err => {\n if (opts.onReturnError != null) {\n opts.onReturnError(err)\n }\n })\n }\n } catch (err: any) {\n if (opts.onReturnError != null) { // eslint-disable-line max-depth\n opts.onReturnError(err)\n }\n }\n }\n\n if (isKnownAborter && opts.returnOnAbort === true) {\n return\n }\n\n throw err\n }\n\n if (result.done === true) {\n break\n }\n\n yield result.value\n }\n\n signal.removeEventListener('abort', abortHandler)\n }\n\n return abortable()\n}\n\nexport function abortableSink (sink: Sink, signal: AbortSignal, options?: Options): Sink {\n return (source: Source) => sink(abortableSource(source, signal, options))\n}\n\nexport function abortableDuplex > (duplex: Duplex, signal: AbortSignal, options?: Options) {\n return {\n sink: abortableSink(duplex.sink, signal, {\n ...options,\n onAbort: undefined\n }),\n source: abortableSource(duplex.source, signal, options)\n }\n}\n\nexport { AbortError }\nexport { abortableSink as abortableTransform }\n","\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator (obj: AsyncIterable): AsyncIterator\nexport function getIterator (obj: AsyncIterator): AsyncIterator\nexport function getIterator (obj: Iterable): Iterator\nexport function getIterator (obj: Iterator): Iterator\nexport function getIterator (obj: any): AsyncIterator | Iterator \nexport function getIterator (obj: any): AsyncIterator | Iterator {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]()\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]()\n }\n if (typeof obj.next === 'function') {\n return obj // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable')\n}\n",null,null,null,"import {\n GossipSub,\n GossipsubMessage,\n GossipsubOpts,\n} from \"@chainsafe/libp2p-gossipsub\";\nimport {\n PeerIdStr,\n TopicStr,\n} from \"@chainsafe/libp2p-gossipsub/dist/src/types\";\nimport { SignaturePolicy } from \"@chainsafe/libp2p-gossipsub/types\";\nimport debug from \"debug\";\n\nimport { DefaultPubSubTopic } from \"../constants\";\nimport { hexToBytes } from \"../utils\";\nimport { DecryptionMethod, WakuMessage } from \"../waku_message\";\n\nimport * as constants from \"./constants\";\n\nconst dbg = debug(\"waku:relay\");\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use. Defaults to {@link DefaultPubSubTopic}.\n *\n * One and only one pubsub topic is used by Waku. This is used by:\n * - WakuRelay to receive, route and send messages,\n * - WakuLightPush to send messages,\n * - WakuStore to retrieve messages.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n decryptionKeys?: Array;\n}\n\n/**\n * Implements the [Waku v2 Relay protocol](https://rfc.vac.dev/spec/11/).\n * Must be passed as a `pubsub` module to a `Libp2p` instance.\n *\n * @implements {require('libp2p-interfaces/src/pubsub')}\n */\nexport class WakuRelay extends GossipSub {\n pubSubTopic: string;\n public static multicodec: string = constants.RelayCodecs[0];\n\n public decryptionKeys: Map<\n Uint8Array,\n { method?: DecryptionMethod; contentTopics?: string[] }\n >;\n\n /**\n * observers called when receiving new message.\n * Observers under key `\"\"` are always called.\n */\n public observers: {\n [contentTopic: string]: Set<(message: WakuMessage) => void>;\n };\n\n constructor(options?: Partial) {\n options = Object.assign(options ?? {}, {\n // Ensure that no signature is included nor expected in the messages.\n globalSignaturePolicy: SignaturePolicy.StrictNoSign,\n fallbackToFloodsub: false,\n });\n super(options);\n this.multicodecs = constants.RelayCodecs;\n\n this.observers = {};\n this.decryptionKeys = new Map();\n\n this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;\n\n options?.decryptionKeys?.forEach((key) => {\n this.addDecryptionKey(key);\n });\n }\n\n /**\n * Mounts the gossipsub protocol onto the libp2p node\n * and subscribes to the default topic.\n *\n * @override\n * @returns {void}\n */\n public async start(): Promise {\n await super.start();\n this.subscribe(this.pubSubTopic);\n }\n\n /**\n * Send Waku message.\n *\n * @param {WakuMessage} message\n * @returns {Promise}\n */\n public async send(message: WakuMessage): Promise {\n const msg = message.encode();\n await this.publish(this.pubSubTopic, msg);\n }\n\n /**\n * Register a decryption key to attempt decryption of received messages.\n * This can either be a private key for asymmetric encryption or a symmetric\n * key. `WakuRelay` will attempt to decrypt messages using both methods.\n *\n * Strings must be in hex format.\n */\n addDecryptionKey(\n key: Uint8Array | string,\n options?: { method?: DecryptionMethod; contentTopics?: string[] }\n ): void {\n this.decryptionKeys.set(hexToBytes(key), options ?? {});\n }\n\n /**\n * Delete a decryption key that was used to attempt decryption of received\n * messages.\n *\n * Strings must be in hex format.\n */\n deleteDecryptionKey(key: Uint8Array | string): void {\n this.decryptionKeys.delete(hexToBytes(key));\n }\n\n /**\n * Register an observer of new messages received via waku relay\n *\n * @param callback called when a new message is received via waku relay\n * @param contentTopics Content Topics for which the callback with be called,\n * all of them if undefined, [] or [\"\",..] is passed.\n * @returns {void}\n */\n addObserver(\n callback: (message: WakuMessage) => void,\n contentTopics: string[] = []\n ): void {\n if (contentTopics.length === 0) {\n if (!this.observers[\"\"]) {\n this.observers[\"\"] = new Set();\n }\n this.observers[\"\"].add(callback);\n } else {\n contentTopics.forEach((contentTopic) => {\n if (!this.observers[contentTopic]) {\n this.observers[contentTopic] = new Set();\n }\n this.observers[contentTopic].add(callback);\n });\n }\n }\n\n /**\n * Remove an observer of new messages received via waku relay.\n * Useful to ensure the same observer is not registered several time\n * (e.g when loading React components)\n */\n deleteObserver(\n callback: (message: WakuMessage) => void,\n contentTopics: string[] = []\n ): void {\n if (contentTopics.length === 0) {\n if (this.observers[\"\"]) {\n this.observers[\"\"].delete(callback);\n }\n } else {\n contentTopics.forEach((contentTopic) => {\n if (this.observers[contentTopic]) {\n this.observers[contentTopic].delete(callback);\n }\n });\n }\n }\n\n /**\n * Subscribe to a pubsub topic and start emitting Waku messages to observers.\n *\n * @override\n */\n subscribe(pubSubTopic: string): void {\n this.addEventListener(\n \"gossipsub:message\",\n (event: CustomEvent) => {\n if (event.detail.msg.topic === pubSubTopic) {\n const decryptionKeys = Array.from(this.decryptionKeys).map(\n ([key, { method, contentTopics }]) => {\n return {\n key,\n method,\n contentTopics,\n };\n }\n );\n\n dbg(`Message received on ${pubSubTopic}`);\n WakuMessage.decode(event.detail.msg.data, decryptionKeys)\n .then((wakuMsg) => {\n if (!wakuMsg) {\n dbg(\"Failed to decode Waku Message\");\n return;\n }\n\n if (this.observers[\"\"]) {\n this.observers[\"\"].forEach((callbackFn) => {\n callbackFn(wakuMsg);\n });\n }\n if (wakuMsg.contentTopic) {\n if (this.observers[wakuMsg.contentTopic]) {\n this.observers[wakuMsg.contentTopic].forEach((callbackFn) => {\n callbackFn(wakuMsg);\n });\n }\n }\n })\n .catch((e) => {\n dbg(\"Failed to decode Waku Message\", e);\n });\n }\n }\n );\n\n super.subscribe(pubSubTopic);\n }\n\n getMeshPeers(topic?: TopicStr): PeerIdStr[] {\n return super.getMeshPeers(topic ?? this.pubSubTopic);\n }\n}\n","import { multiaddr } from \"@multiformats/multiaddr\";\nimport { Waku } from \"js-waku\";\n\nfunction help(): string[] {\n return [\n \"/nick : set a new nickname\",\n \"/info: some information about the node\",\n \"/connect : connect to the given peer\",\n \"/help: Display this help\",\n ];\n}\n\nfunction nick(\n nick: string | undefined,\n setNick: (nick: string) => void\n): string[] {\n if (!nick) {\n return [\"No nick provided\"];\n }\n setNick(nick);\n return [`New nick: ${nick}`];\n}\n\nfunction info(waku: Waku | undefined): string[] {\n if (!waku) {\n return [\"Waku node is starting\"];\n }\n return [`PeerId: ${waku.libp2p.peerId.toString()}`];\n}\n\nfunction connect(peer: string | undefined, waku: Waku | undefined): string[] {\n if (!waku) {\n return [\"Waku node is starting\"];\n }\n if (!peer) {\n return [\"No peer provided\"];\n }\n try {\n const peerMultiaddr = multiaddr(peer);\n const peerId = peerMultiaddr.getPeerId();\n if (!peerId) {\n return [\"Peer Id needed to dial\"];\n }\n waku.addPeerToAddressBook(peerId, [peerMultiaddr]);\n return [\n `${peerId}: ${peerMultiaddr.toString()} added to address book, autodial in progress`,\n ];\n } catch (e) {\n return [\"Invalid multiaddr: \" + e];\n }\n}\n\nasync function peers(waku: Waku | undefined): Promise {\n if (!waku) {\n return [\"Waku node is starting\"];\n }\n let response: string[] = [];\n const peers = await waku.libp2p.peerStore.all();\n\n Array.from(peers).forEach((peer) => {\n response.push(peer.id.toString() + \":\");\n let addresses = \" addresses: [\";\n peer.addresses.forEach(({ multiaddr }) => {\n addresses += \" \" + multiaddr.toString() + \",\";\n });\n addresses = addresses.replace(/,$/, \"\");\n addresses += \"]\";\n response.push(addresses);\n let protocols = \" protocols: [\";\n protocols += peer.protocols;\n protocols += \"]\";\n response.push(protocols);\n });\n if (response.length === 0) {\n response.push(\"Not connected to any peer.\");\n }\n return response;\n}\n\nfunction connections(waku: Waku | undefined): string[] {\n if (!waku) {\n return [\"Waku node is starting\"];\n }\n let response: string[] = [];\n let strConnections = \" connections: \\n\";\n waku.libp2p.connectionManager.getConnections().forEach((connection) => {\n strConnections += connection.remotePeer.toString() + \", \";\n strConnections += JSON.stringify(connection.stat);\n strConnections += \"; \" + JSON.stringify(connection.streams);\n strConnections += \"\\n\";\n });\n response.push(strConnections);\n if (response.length === 0) {\n response.push(\"Not connected to any peer.\");\n }\n return response;\n}\n\nexport default async function handleCommand(\n input: string,\n waku: Waku | undefined,\n setNick: (nick: string) => void\n): Promise<{ command: string; response: string[] }> {\n let response: string[] = [];\n const args = parseInput(input);\n const command = args.shift()!;\n switch (command) {\n case \"/help\":\n help().map((str) => response.push(str));\n break;\n case \"/nick\":\n nick(args.shift(), setNick).map((str) => response.push(str));\n break;\n case \"/info\":\n info(waku).map((str) => response.push(str));\n break;\n case \"/connect\":\n connect(args.shift(), waku).map((str) => response.push(str));\n break;\n case \"/peers\":\n (await peers(waku)).map((str) => response.push(str));\n break;\n case \"/connections\":\n connections(waku).map((str) => response.push(str));\n break;\n default:\n response.push(`Unknown Command '${command}'`);\n }\n return { command, response };\n}\n\nexport function parseInput(input: string): string[] {\n const clean = input.trim().replaceAll(/\\s\\s+/g, \" \");\n return clean.split(\" \");\n}\n","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n return _extends.apply(this, arguments);\n}","function memoize(fn) {\n var cache = Object.create(null);\n return function (arg) {\n if (cache[arg] === undefined) cache[arg] = fn(arg);\n return cache[arg];\n };\n}\n\nexport default memoize;\n","import memoize from '@emotion/memoize';\n\nvar reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23\n\nvar isPropValid = /* #__PURE__ */memoize(function (prop) {\n return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111\n /* o */\n && prop.charCodeAt(1) === 110\n /* n */\n && prop.charCodeAt(2) < 91;\n}\n/* Z+1 */\n);\n\nexport default isPropValid;\n","/*\n\nBased off glamor's StyleSheet, thanks Sunil ❤️\n\nhigh performance StyleSheet for css-in-js systems\n\n- uses multiple style tags behind the scenes for millions of rules\n- uses `insertRule` for appending in production for *much* faster performance\n\n// usage\n\nimport { StyleSheet } from '@emotion/sheet'\n\nlet styleSheet = new StyleSheet({ key: '', container: document.head })\n\nstyleSheet.insert('#box { border: 1px solid red; }')\n- appends a css rule into the stylesheet\n\nstyleSheet.flush()\n- empties the stylesheet of all its contents\n\n*/\n// $FlowFixMe\nfunction sheetForTag(tag) {\n if (tag.sheet) {\n // $FlowFixMe\n return tag.sheet;\n } // this weirdness brought to you by firefox\n\n /* istanbul ignore next */\n\n\n for (var i = 0; i < document.styleSheets.length; i++) {\n if (document.styleSheets[i].ownerNode === tag) {\n // $FlowFixMe\n return document.styleSheets[i];\n }\n }\n}\n\nfunction createStyleElement(options) {\n var tag = document.createElement('style');\n tag.setAttribute('data-emotion', options.key);\n\n if (options.nonce !== undefined) {\n tag.setAttribute('nonce', options.nonce);\n }\n\n tag.appendChild(document.createTextNode(''));\n tag.setAttribute('data-s', '');\n return tag;\n}\n\nvar StyleSheet = /*#__PURE__*/function () {\n // Using Node instead of HTMLElement since container may be a ShadowRoot\n function StyleSheet(options) {\n var _this = this;\n\n this._insertTag = function (tag) {\n var before;\n\n if (_this.tags.length === 0) {\n if (_this.insertionPoint) {\n before = _this.insertionPoint.nextSibling;\n } else if (_this.prepend) {\n before = _this.container.firstChild;\n } else {\n before = _this.before;\n }\n } else {\n before = _this.tags[_this.tags.length - 1].nextSibling;\n }\n\n _this.container.insertBefore(tag, before);\n\n _this.tags.push(tag);\n };\n\n this.isSpeedy = options.speedy === undefined ? process.env.NODE_ENV === 'production' : options.speedy;\n this.tags = [];\n this.ctr = 0;\n this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets\n\n this.key = options.key;\n this.container = options.container;\n this.prepend = options.prepend;\n this.insertionPoint = options.insertionPoint;\n this.before = null;\n }\n\n var _proto = StyleSheet.prototype;\n\n _proto.hydrate = function hydrate(nodes) {\n nodes.forEach(this._insertTag);\n };\n\n _proto.insert = function insert(rule) {\n // the max length is how many rules we have per style tag, it's 65000 in speedy mode\n // it's 1 in dev because we insert source maps that map a single rule to a location\n // and you can only have one source map per style tag\n if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {\n this._insertTag(createStyleElement(this));\n }\n\n var tag = this.tags[this.tags.length - 1];\n\n if (process.env.NODE_ENV !== 'production') {\n var isImportRule = rule.charCodeAt(0) === 64 && rule.charCodeAt(1) === 105;\n\n if (isImportRule && this._alreadyInsertedOrderInsensitiveRule) {\n // this would only cause problem in speedy mode\n // but we don't want enabling speedy to affect the observable behavior\n // so we report this error at all times\n console.error(\"You're attempting to insert the following rule:\\n\" + rule + '\\n\\n`@import` rules must be before all other types of rules in a stylesheet but other rules have already been inserted. Please ensure that `@import` rules are before all other rules.');\n }\n this._alreadyInsertedOrderInsensitiveRule = this._alreadyInsertedOrderInsensitiveRule || !isImportRule;\n }\n\n if (this.isSpeedy) {\n var sheet = sheetForTag(tag);\n\n try {\n // this is the ultrafast version, works across browsers\n // the big drawback is that the css won't be editable in devtools\n sheet.insertRule(rule, sheet.cssRules.length);\n } catch (e) {\n if (process.env.NODE_ENV !== 'production' && !/:(-moz-placeholder|-moz-focus-inner|-moz-focusring|-ms-input-placeholder|-moz-read-write|-moz-read-only|-ms-clear){/.test(rule)) {\n console.error(\"There was a problem inserting the following rule: \\\"\" + rule + \"\\\"\", e);\n }\n }\n } else {\n tag.appendChild(document.createTextNode(rule));\n }\n\n this.ctr++;\n };\n\n _proto.flush = function flush() {\n // $FlowFixMe\n this.tags.forEach(function (tag) {\n return tag.parentNode && tag.parentNode.removeChild(tag);\n });\n this.tags = [];\n this.ctr = 0;\n\n if (process.env.NODE_ENV !== 'production') {\n this._alreadyInsertedOrderInsensitiveRule = false;\n }\n };\n\n return StyleSheet;\n}();\n\nexport { StyleSheet };\n","/**\n * @param {number}\n * @return {number}\n */\nexport var abs = Math.abs\n\n/**\n * @param {number}\n * @return {string}\n */\nexport var from = String.fromCharCode\n\n/**\n * @param {object}\n * @return {object}\n */\nexport var assign = Object.assign\n\n/**\n * @param {string} value\n * @param {number} length\n * @return {number}\n */\nexport function hash (value, length) {\n\treturn (((((((length << 2) ^ charat(value, 0)) << 2) ^ charat(value, 1)) << 2) ^ charat(value, 2)) << 2) ^ charat(value, 3)\n}\n\n/**\n * @param {string} value\n * @return {string}\n */\nexport function trim (value) {\n\treturn value.trim()\n}\n\n/**\n * @param {string} value\n * @param {RegExp} pattern\n * @return {string?}\n */\nexport function match (value, pattern) {\n\treturn (value = pattern.exec(value)) ? value[0] : value\n}\n\n/**\n * @param {string} value\n * @param {(string|RegExp)} pattern\n * @param {string} replacement\n * @return {string}\n */\nexport function replace (value, pattern, replacement) {\n\treturn value.replace(pattern, replacement)\n}\n\n/**\n * @param {string} value\n * @param {string} search\n * @return {number}\n */\nexport function indexof (value, search) {\n\treturn value.indexOf(search)\n}\n\n/**\n * @param {string} value\n * @param {number} index\n * @return {number}\n */\nexport function charat (value, index) {\n\treturn value.charCodeAt(index) | 0\n}\n\n/**\n * @param {string} value\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function substr (value, begin, end) {\n\treturn value.slice(begin, end)\n}\n\n/**\n * @param {string} value\n * @return {number}\n */\nexport function strlen (value) {\n\treturn value.length\n}\n\n/**\n * @param {any[]} value\n * @return {number}\n */\nexport function sizeof (value) {\n\treturn value.length\n}\n\n/**\n * @param {any} value\n * @param {any[]} array\n * @return {any}\n */\nexport function append (value, array) {\n\treturn array.push(value), value\n}\n\n/**\n * @param {string[]} array\n * @param {function} callback\n * @return {string}\n */\nexport function combine (array, callback) {\n\treturn array.map(callback).join('')\n}\n","import {from, trim, charat, strlen, substr, append, assign} from './Utility.js'\n\nexport var line = 1\nexport var column = 1\nexport var length = 0\nexport var position = 0\nexport var character = 0\nexport var characters = ''\n\n/**\n * @param {string} value\n * @param {object | null} root\n * @param {object | null} parent\n * @param {string} type\n * @param {string[] | string} props\n * @param {object[] | string} children\n * @param {number} length\n */\nexport function node (value, root, parent, type, props, children, length) {\n\treturn {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: ''}\n}\n\n/**\n * @param {object} root\n * @param {object} props\n * @return {object}\n */\nexport function copy (root, props) {\n\treturn assign(node('', null, null, '', null, null, 0), root, {length: -root.length}, props)\n}\n\n/**\n * @return {number}\n */\nexport function char () {\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function prev () {\n\tcharacter = position > 0 ? charat(characters, --position) : 0\n\n\tif (column--, character === 10)\n\t\tcolumn = 1, line--\n\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function next () {\n\tcharacter = position < length ? charat(characters, position++) : 0\n\n\tif (column++, character === 10)\n\t\tcolumn = 1, line++\n\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function peek () {\n\treturn charat(characters, position)\n}\n\n/**\n * @return {number}\n */\nexport function caret () {\n\treturn position\n}\n\n/**\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function slice (begin, end) {\n\treturn substr(characters, begin, end)\n}\n\n/**\n * @param {number} type\n * @return {number}\n */\nexport function token (type) {\n\tswitch (type) {\n\t\t// \\0 \\t \\n \\r \\s whitespace token\n\t\tcase 0: case 9: case 10: case 13: case 32:\n\t\t\treturn 5\n\t\t// ! + , / > @ ~ isolate token\n\t\tcase 33: case 43: case 44: case 47: case 62: case 64: case 126:\n\t\t// ; { } breakpoint token\n\t\tcase 59: case 123: case 125:\n\t\t\treturn 4\n\t\t// : accompanied token\n\t\tcase 58:\n\t\t\treturn 3\n\t\t// \" ' ( [ opening delimit token\n\t\tcase 34: case 39: case 40: case 91:\n\t\t\treturn 2\n\t\t// ) ] closing delimit token\n\t\tcase 41: case 93:\n\t\t\treturn 1\n\t}\n\n\treturn 0\n}\n\n/**\n * @param {string} value\n * @return {any[]}\n */\nexport function alloc (value) {\n\treturn line = column = 1, length = strlen(characters = value), position = 0, []\n}\n\n/**\n * @param {any} value\n * @return {any}\n */\nexport function dealloc (value) {\n\treturn characters = '', value\n}\n\n/**\n * @param {number} type\n * @return {string}\n */\nexport function delimit (type) {\n\treturn trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)))\n}\n\n/**\n * @param {string} value\n * @return {string[]}\n */\nexport function tokenize (value) {\n\treturn dealloc(tokenizer(alloc(value)))\n}\n\n/**\n * @param {number} type\n * @return {string}\n */\nexport function whitespace (type) {\n\twhile (character = peek())\n\t\tif (character < 33)\n\t\t\tnext()\n\t\telse\n\t\t\tbreak\n\n\treturn token(type) > 2 || token(character) > 3 ? '' : ' '\n}\n\n/**\n * @param {string[]} children\n * @return {string[]}\n */\nexport function tokenizer (children) {\n\twhile (next())\n\t\tswitch (token(character)) {\n\t\t\tcase 0: append(identifier(position - 1), children)\n\t\t\t\tbreak\n\t\t\tcase 2: append(delimit(character), children)\n\t\t\t\tbreak\n\t\t\tdefault: append(from(character), children)\n\t\t}\n\n\treturn children\n}\n\n/**\n * @param {number} index\n * @param {number} count\n * @return {string}\n */\nexport function escaping (index, count) {\n\twhile (--count && next())\n\t\t// not 0-9 A-F a-f\n\t\tif (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97))\n\t\t\tbreak\n\n\treturn slice(index, caret() + (count < 6 && peek() == 32 && next() == 32))\n}\n\n/**\n * @param {number} type\n * @return {number}\n */\nexport function delimiter (type) {\n\twhile (next())\n\t\tswitch (character) {\n\t\t\t// ] ) \" '\n\t\t\tcase type:\n\t\t\t\treturn position\n\t\t\t// \" '\n\t\t\tcase 34: case 39:\n\t\t\t\tif (type !== 34 && type !== 39)\n\t\t\t\t\tdelimiter(character)\n\t\t\t\tbreak\n\t\t\t// (\n\t\t\tcase 40:\n\t\t\t\tif (type === 41)\n\t\t\t\t\tdelimiter(type)\n\t\t\t\tbreak\n\t\t\t// \\\n\t\t\tcase 92:\n\t\t\t\tnext()\n\t\t\t\tbreak\n\t\t}\n\n\treturn position\n}\n\n/**\n * @param {number} type\n * @param {number} index\n * @return {number}\n */\nexport function commenter (type, index) {\n\twhile (next())\n\t\t// //\n\t\tif (type + character === 47 + 10)\n\t\t\tbreak\n\t\t// /*\n\t\telse if (type + character === 42 + 42 && peek() === 47)\n\t\t\tbreak\n\n\treturn '/*' + slice(index, position - 1) + '*' + from(type === 47 ? type : next())\n}\n\n/**\n * @param {number} index\n * @return {string}\n */\nexport function identifier (index) {\n\twhile (!token(peek()))\n\t\tnext()\n\n\treturn slice(index, position)\n}\n","export var MS = '-ms-'\nexport var MOZ = '-moz-'\nexport var WEBKIT = '-webkit-'\n\nexport var COMMENT = 'comm'\nexport var RULESET = 'rule'\nexport var DECLARATION = 'decl'\n\nexport var PAGE = '@page'\nexport var MEDIA = '@media'\nexport var IMPORT = '@import'\nexport var CHARSET = '@charset'\nexport var VIEWPORT = '@viewport'\nexport var SUPPORTS = '@supports'\nexport var DOCUMENT = '@document'\nexport var NAMESPACE = '@namespace'\nexport var KEYFRAMES = '@keyframes'\nexport var FONT_FACE = '@font-face'\nexport var COUNTER_STYLE = '@counter-style'\nexport var FONT_FEATURE_VALUES = '@font-feature-values'\n","import {IMPORT, COMMENT, RULESET, DECLARATION, KEYFRAMES} from './Enum.js'\nimport {strlen, sizeof} from './Utility.js'\n\n/**\n * @param {object[]} children\n * @param {function} callback\n * @return {string}\n */\nexport function serialize (children, callback) {\n\tvar output = ''\n\tvar length = sizeof(children)\n\n\tfor (var i = 0; i < length; i++)\n\t\toutput += callback(children[i], i, children, callback) || ''\n\n\treturn output\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n * @param {function} callback\n * @return {string}\n */\nexport function stringify (element, index, children, callback) {\n\tswitch (element.type) {\n\t\tcase IMPORT: case DECLARATION: return element.return = element.return || element.value\n\t\tcase COMMENT: return ''\n\t\tcase KEYFRAMES: return element.return = element.value + '{' + serialize(element.children, callback) + '}'\n\t\tcase RULESET: element.value = element.props.join(',')\n\t}\n\n\treturn strlen(children = serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''\n}\n","import {MS, MOZ, WEBKIT} from './Enum.js'\nimport {hash, charat, strlen, indexof, replace} from './Utility.js'\n\n/**\n * @param {string} value\n * @param {number} length\n * @return {string}\n */\nexport function prefix (value, length) {\n\tswitch (hash(value, length)) {\n\t\t// color-adjust\n\t\tcase 5103:\n\t\t\treturn WEBKIT + 'print-' + value + value\n\t\t// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)\n\t\tcase 5737: case 4201: case 3177: case 3433: case 1641: case 4457: case 2921:\n\t\t// text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break\n\t\tcase 5572: case 6356: case 5844: case 3191: case 6645: case 3005:\n\t\t// mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,\n\t\tcase 6391: case 5879: case 5623: case 6135: case 4599: case 4855:\n\t\t// background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)\n\t\tcase 4215: case 6389: case 5109: case 5365: case 5621: case 3829:\n\t\t\treturn WEBKIT + value + value\n\t\t// appearance, user-select, transform, hyphens, text-size-adjust\n\t\tcase 5349: case 4246: case 4810: case 6968: case 2756:\n\t\t\treturn WEBKIT + value + MOZ + value + MS + value + value\n\t\t// flex, flex-direction\n\t\tcase 6828: case 4268:\n\t\t\treturn WEBKIT + value + MS + value + value\n\t\t// order\n\t\tcase 6165:\n\t\t\treturn WEBKIT + value + MS + 'flex-' + value + value\n\t\t// align-items\n\t\tcase 5187:\n\t\t\treturn WEBKIT + value + replace(value, /(\\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value\n\t\t// align-self\n\t\tcase 5443:\n\t\t\treturn WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value\n\t\t// align-content\n\t\tcase 4675:\n\t\t\treturn WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value\n\t\t// flex-shrink\n\t\tcase 5548:\n\t\t\treturn WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value\n\t\t// flex-basis\n\t\tcase 5292:\n\t\t\treturn WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value\n\t\t// flex-grow\n\t\tcase 6060:\n\t\t\treturn WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value\n\t\t// transition\n\t\tcase 4554:\n\t\t\treturn WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value\n\t\t// cursor\n\t\tcase 6187:\n\t\t\treturn replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value\n\t\t// background, background-image\n\t\tcase 5495: case 3959:\n\t\t\treturn replace(value, /(image-set\\([^]*)/, WEBKIT + '$1' + '$`$1')\n\t\t// justify-content\n\t\tcase 4968:\n\t\t\treturn replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value\n\t\t// (margin|padding)-inline-(start|end)\n\t\tcase 4095: case 3583: case 4068: case 2532:\n\t\t\treturn replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value\n\t\t// (min|max)?(width|height|inline-size|block-size)\n\t\tcase 8116: case 7059: case 5753: case 5535:\n\t\tcase 5445: case 5701: case 4933: case 4677:\n\t\tcase 5533: case 5789: case 5021: case 4765:\n\t\t\t// stretch, max-content, min-content, fill-available\n\t\t\tif (strlen(value) - 1 - length > 6)\n\t\t\t\tswitch (charat(value, length + 1)) {\n\t\t\t\t\t// (m)ax-content, (m)in-content\n\t\t\t\t\tcase 109:\n\t\t\t\t\t\t// -\n\t\t\t\t\t\tif (charat(value, length + 4) !== 45)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t// (f)ill-available, (f)it-content\n\t\t\t\t\tcase 102:\n\t\t\t\t\t\treturn replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value\n\t\t\t\t\t// (s)tretch\n\t\t\t\t\tcase 115:\n\t\t\t\t\t\treturn ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value\n\t\t\t\t}\n\t\t\tbreak\n\t\t// position: sticky\n\t\tcase 4949:\n\t\t\t// (s)ticky?\n\t\t\tif (charat(value, length + 1) !== 115)\n\t\t\t\tbreak\n\t\t// display: (flex|inline-flex)\n\t\tcase 6444:\n\t\t\tswitch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {\n\t\t\t\t// stic(k)y\n\t\t\t\tcase 107:\n\t\t\t\t\treturn replace(value, ':', ':' + WEBKIT) + value\n\t\t\t\t// (inline-)?fl(e)x\n\t\t\t\tcase 101:\n\t\t\t\t\treturn replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value\n\t\t\t}\n\t\t\tbreak\n\t\t// writing-mode\n\t\tcase 5936:\n\t\t\tswitch (charat(value, length + 11)) {\n\t\t\t\t// vertical-l(r)\n\t\t\t\tcase 114:\n\t\t\t\t\treturn WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'tb') + value\n\t\t\t\t// vertical-r(l)\n\t\t\t\tcase 108:\n\t\t\t\t\treturn WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'tb-rl') + value\n\t\t\t\t// horizontal(-)tb\n\t\t\t\tcase 45:\n\t\t\t\t\treturn WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'lr') + value\n\t\t\t}\n\n\t\t\treturn WEBKIT + value + MS + value + value\n\t}\n\n\treturn value\n}\n","import {COMMENT, RULESET, DECLARATION} from './Enum.js'\nimport {abs, trim, from, sizeof, strlen, substr, append, replace, indexof} from './Utility.js'\nimport {node, char, prev, next, peek, caret, alloc, dealloc, delimit, whitespace, escaping, identifier, commenter} from './Tokenizer.js'\n\n/**\n * @param {string} value\n * @return {object[]}\n */\nexport function compile (value) {\n\treturn dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value))\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {string[]} rule\n * @param {string[]} rules\n * @param {string[]} rulesets\n * @param {number[]} pseudo\n * @param {number[]} points\n * @param {string[]} declarations\n * @return {object}\n */\nexport function parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {\n\tvar index = 0\n\tvar offset = 0\n\tvar length = pseudo\n\tvar atrule = 0\n\tvar property = 0\n\tvar previous = 0\n\tvar variable = 1\n\tvar scanning = 1\n\tvar ampersand = 1\n\tvar character = 0\n\tvar type = ''\n\tvar props = rules\n\tvar children = rulesets\n\tvar reference = rule\n\tvar characters = type\n\n\twhile (scanning)\n\t\tswitch (previous = character, character = next()) {\n\t\t\t// (\n\t\t\tcase 40:\n\t\t\t\tif (previous != 108 && characters.charCodeAt(length - 1) == 58) {\n\t\t\t\t\tif (indexof(characters += replace(delimit(character), '&', '&\\f'), '&\\f') != -1)\n\t\t\t\t\t\tampersand = -1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t// \" ' [\n\t\t\tcase 34: case 39: case 91:\n\t\t\t\tcharacters += delimit(character)\n\t\t\t\tbreak\n\t\t\t// \\t \\n \\r \\s\n\t\t\tcase 9: case 10: case 13: case 32:\n\t\t\t\tcharacters += whitespace(previous)\n\t\t\t\tbreak\n\t\t\t// \\\n\t\t\tcase 92:\n\t\t\t\tcharacters += escaping(caret() - 1, 7)\n\t\t\t\tcontinue\n\t\t\t// /\n\t\t\tcase 47:\n\t\t\t\tswitch (peek()) {\n\t\t\t\t\tcase 42: case 47:\n\t\t\t\t\t\tappend(comment(commenter(next(), caret()), root, parent), declarations)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcharacters += '/'\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t// {\n\t\t\tcase 123 * variable:\n\t\t\t\tpoints[index++] = strlen(characters) * ampersand\n\t\t\t// } ; \\0\n\t\t\tcase 125 * variable: case 59: case 0:\n\t\t\t\tswitch (character) {\n\t\t\t\t\t// \\0 }\n\t\t\t\t\tcase 0: case 125: scanning = 0\n\t\t\t\t\t// ;\n\t\t\t\t\tcase 59 + offset:\n\t\t\t\t\t\tif (property > 0 && (strlen(characters) - length))\n\t\t\t\t\t\t\tappend(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// @ ;\n\t\t\t\t\tcase 59: characters += ';'\n\t\t\t\t\t// { rule/at-rule\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tappend(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets)\n\n\t\t\t\t\t\tif (character === 123)\n\t\t\t\t\t\t\tif (offset === 0)\n\t\t\t\t\t\t\t\tparse(characters, root, reference, reference, props, rulesets, length, points, children)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tswitch (atrule) {\n\t\t\t\t\t\t\t\t\t// d m s\n\t\t\t\t\t\t\t\t\tcase 100: case 109: case 115:\n\t\t\t\t\t\t\t\t\t\tparse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\tparse(characters, reference, reference, reference, [''], children, 0, points, children)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tindex = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo\n\t\t\t\tbreak\n\t\t\t// :\n\t\t\tcase 58:\n\t\t\t\tlength = 1 + strlen(characters), property = previous\n\t\t\tdefault:\n\t\t\t\tif (variable < 1)\n\t\t\t\t\tif (character == 123)\n\t\t\t\t\t\t--variable\n\t\t\t\t\telse if (character == 125 && variable++ == 0 && prev() == 125)\n\t\t\t\t\t\tcontinue\n\n\t\t\t\tswitch (characters += from(character), character * variable) {\n\t\t\t\t\t// &\n\t\t\t\t\tcase 38:\n\t\t\t\t\t\tampersand = offset > 0 ? 1 : (characters += '\\f', -1)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// ,\n\t\t\t\t\tcase 44:\n\t\t\t\t\t\tpoints[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// @\n\t\t\t\t\tcase 64:\n\t\t\t\t\t\t// -\n\t\t\t\t\t\tif (peek() === 45)\n\t\t\t\t\t\t\tcharacters += delimit(next())\n\n\t\t\t\t\t\tatrule = peek(), offset = length = strlen(type = characters += identifier(caret())), character++\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// -\n\t\t\t\t\tcase 45:\n\t\t\t\t\t\tif (previous === 45 && strlen(characters) == 2)\n\t\t\t\t\t\t\tvariable = 0\n\t\t\t\t}\n\t\t}\n\n\treturn rulesets\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {number} index\n * @param {number} offset\n * @param {string[]} rules\n * @param {number[]} points\n * @param {string} type\n * @param {string[]} props\n * @param {string[]} children\n * @param {number} length\n * @return {object}\n */\nexport function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length) {\n\tvar post = offset - 1\n\tvar rule = offset === 0 ? rules : ['']\n\tvar size = sizeof(rule)\n\n\tfor (var i = 0, j = 0, k = 0; i < index; ++i)\n\t\tfor (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)\n\t\t\tif (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\\f/g, rule[x])))\n\t\t\t\tprops[k++] = z\n\n\treturn node(value, root, parent, offset === 0 ? RULESET : type, props, children, length)\n}\n\n/**\n * @param {number} value\n * @param {object} root\n * @param {object?} parent\n * @return {object}\n */\nexport function comment (value, root, parent) {\n\treturn node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0)\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {number} length\n * @return {object}\n */\nexport function declaration (value, root, parent, length) {\n\treturn node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length)\n}\n","import { StyleSheet } from '@emotion/sheet';\nimport { dealloc, alloc, next, token, from, peek, delimit, slice, position, stringify, COMMENT, rulesheet, middleware, prefixer, serialize, compile } from 'stylis';\nimport '@emotion/weak-memoize';\nimport '@emotion/memoize';\n\nvar identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {\n var previous = 0;\n var character = 0;\n\n while (true) {\n previous = character;\n character = peek(); // &\\f\n\n if (previous === 38 && character === 12) {\n points[index] = 1;\n }\n\n if (token(character)) {\n break;\n }\n\n next();\n }\n\n return slice(begin, position);\n};\n\nvar toRules = function toRules(parsed, points) {\n // pretend we've started with a comma\n var index = -1;\n var character = 44;\n\n do {\n switch (token(character)) {\n case 0:\n // &\\f\n if (character === 38 && peek() === 12) {\n // this is not 100% correct, we don't account for literal sequences here - like for example quoted strings\n // stylis inserts \\f after & to know when & where it should replace this sequence with the context selector\n // and when it should just concatenate the outer and inner selectors\n // it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here\n points[index] = 1;\n }\n\n parsed[index] += identifierWithPointTracking(position - 1, points, index);\n break;\n\n case 2:\n parsed[index] += delimit(character);\n break;\n\n case 4:\n // comma\n if (character === 44) {\n // colon\n parsed[++index] = peek() === 58 ? '&\\f' : '';\n points[index] = parsed[index].length;\n break;\n }\n\n // fallthrough\n\n default:\n parsed[index] += from(character);\n }\n } while (character = next());\n\n return parsed;\n};\n\nvar getRules = function getRules(value, points) {\n return dealloc(toRules(alloc(value), points));\n}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11\n\n\nvar fixedElements = /* #__PURE__ */new WeakMap();\nvar compat = function compat(element) {\n if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo\n // negative .length indicates that this rule has been already prefixed\n element.length < 1) {\n return;\n }\n\n var value = element.value,\n parent = element.parent;\n var isImplicitRule = element.column === parent.column && element.line === parent.line;\n\n while (parent.type !== 'rule') {\n parent = parent.parent;\n if (!parent) return;\n } // short-circuit for the simplest case\n\n\n if (element.props.length === 1 && value.charCodeAt(0) !== 58\n /* colon */\n && !fixedElements.get(parent)) {\n return;\n } // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)\n // then the props has already been manipulated beforehand as they that array is shared between it and its \"rule parent\"\n\n\n if (isImplicitRule) {\n return;\n }\n\n fixedElements.set(element, true);\n var points = [];\n var rules = getRules(value, points);\n var parentRules = parent.props;\n\n for (var i = 0, k = 0; i < rules.length; i++) {\n for (var j = 0; j < parentRules.length; j++, k++) {\n element.props[k] = points[i] ? rules[i].replace(/&\\f/g, parentRules[j]) : parentRules[j] + \" \" + rules[i];\n }\n }\n};\nvar removeLabel = function removeLabel(element) {\n if (element.type === 'decl') {\n var value = element.value;\n\n if ( // charcode for l\n value.charCodeAt(0) === 108 && // charcode for b\n value.charCodeAt(2) === 98) {\n // this ignores label\n element[\"return\"] = '';\n element.value = '';\n }\n }\n};\nvar ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';\n\nvar isIgnoringComment = function isIgnoringComment(element) {\n return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;\n};\n\nvar createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {\n return function (element, index, children) {\n if (element.type !== 'rule' || cache.compat) return;\n var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);\n\n if (unsafePseudoClasses) {\n var isNested = element.parent === children[0]; // in nested rules comments become children of the \"auto-inserted\" rule\n //\n // considering this input:\n // .a {\n // .b /* comm */ {}\n // color: hotpink;\n // }\n // we get output corresponding to this:\n // .a {\n // & {\n // /* comm */\n // color: hotpink;\n // }\n // .b {}\n // }\n\n var commentContainer = isNested ? children[0].children : // global rule at the root level\n children;\n\n for (var i = commentContainer.length - 1; i >= 0; i--) {\n var node = commentContainer[i];\n\n if (node.line < element.line) {\n break;\n } // it is quite weird but comments are *usually* put at `column: element.column - 1`\n // so we seek *from the end* for the node that is earlier than the rule's `element` and check that\n // this will also match inputs like this:\n // .a {\n // /* comm */\n // .b {}\n // }\n //\n // but that is fine\n //\n // it would be the easiest to change the placement of the comment to be the first child of the rule:\n // .a {\n // .b { /* comm */ }\n // }\n // with such inputs we wouldn't have to search for the comment at all\n // TODO: consider changing this comment placement in the next major version\n\n\n if (node.column < element.column) {\n if (isIgnoringComment(node)) {\n return;\n }\n\n break;\n }\n }\n\n unsafePseudoClasses.forEach(function (unsafePseudoClass) {\n console.error(\"The pseudo class \\\"\" + unsafePseudoClass + \"\\\" is potentially unsafe when doing server-side rendering. Try changing it to \\\"\" + unsafePseudoClass.split('-child')[0] + \"-of-type\\\".\");\n });\n }\n };\n};\n\nvar isImportRule = function isImportRule(element) {\n return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;\n};\n\nvar isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {\n for (var i = index - 1; i >= 0; i--) {\n if (!isImportRule(children[i])) {\n return true;\n }\n }\n\n return false;\n}; // use this to remove incorrect elements from further processing\n// so they don't get handed to the `sheet` (or anything else)\n// as that could potentially lead to additional logs which in turn could be overhelming to the user\n\n\nvar nullifyElement = function nullifyElement(element) {\n element.type = '';\n element.value = '';\n element[\"return\"] = '';\n element.children = '';\n element.props = '';\n};\n\nvar incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {\n if (!isImportRule(element)) {\n return;\n }\n\n if (element.parent) {\n console.error(\"`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.\");\n nullifyElement(element);\n } else if (isPrependedWithRegularRules(index, children)) {\n console.error(\"`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.\");\n nullifyElement(element);\n }\n};\n\nvar defaultStylisPlugins = [prefixer];\n\nvar createCache = function createCache(options) {\n var key = options.key;\n\n if (process.env.NODE_ENV !== 'production' && !key) {\n throw new Error(\"You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\\n\" + \"If multiple caches share the same key they might \\\"fight\\\" for each other's style elements.\");\n }\n\n if ( key === 'css') {\n var ssrStyles = document.querySelectorAll(\"style[data-emotion]:not([data-s])\"); // get SSRed styles out of the way of React's hydration\n // document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)\n // note this very very intentionally targets all style elements regardless of the key to ensure\n // that creating a cache works inside of render of a React component\n\n Array.prototype.forEach.call(ssrStyles, function (node) {\n // we want to only move elements which have a space in the data-emotion attribute value\n // because that indicates that it is an Emotion 11 server-side rendered style elements\n // while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector\n // Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)\n // so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles\n // will not result in the Emotion 10 styles being destroyed\n var dataEmotionAttribute = node.getAttribute('data-emotion');\n\n if (dataEmotionAttribute.indexOf(' ') === -1) {\n return;\n }\n document.head.appendChild(node);\n node.setAttribute('data-s', '');\n });\n }\n\n var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;\n\n if (process.env.NODE_ENV !== 'production') {\n // $FlowFixMe\n if (/[^a-z-]/.test(key)) {\n throw new Error(\"Emotion key must only contain lower case alphabetical characters and - but \\\"\" + key + \"\\\" was passed\");\n }\n }\n\n var inserted = {};\n var container;\n var nodesToHydrate = [];\n\n {\n container = options.container || document.head;\n Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which\n // means that the style elements we're looking at are only Emotion 11 server-rendered style elements\n document.querySelectorAll(\"style[data-emotion^=\\\"\" + key + \" \\\"]\"), function (node) {\n var attrib = node.getAttribute(\"data-emotion\").split(' '); // $FlowFixMe\n\n for (var i = 1; i < attrib.length; i++) {\n inserted[attrib[i]] = true;\n }\n\n nodesToHydrate.push(node);\n });\n }\n\n var _insert;\n\n var omnipresentPlugins = [compat, removeLabel];\n\n if (process.env.NODE_ENV !== 'production') {\n omnipresentPlugins.push(createUnsafeSelectorsAlarm({\n get compat() {\n return cache.compat;\n }\n\n }), incorrectImportAlarm);\n }\n\n {\n var currentSheet;\n var finalizingPlugins = [stringify, process.env.NODE_ENV !== 'production' ? function (element) {\n if (!element.root) {\n if (element[\"return\"]) {\n currentSheet.insert(element[\"return\"]);\n } else if (element.value && element.type !== COMMENT) {\n // insert empty rule in non-production environments\n // so @emotion/jest can grab `key` from the (JS)DOM for caches without any rules inserted yet\n currentSheet.insert(element.value + \"{}\");\n }\n }\n } : rulesheet(function (rule) {\n currentSheet.insert(rule);\n })];\n var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));\n\n var stylis = function stylis(styles) {\n return serialize(compile(styles), serializer);\n };\n\n _insert = function insert(selector, serialized, sheet, shouldCache) {\n currentSheet = sheet;\n\n if (process.env.NODE_ENV !== 'production' && serialized.map !== undefined) {\n currentSheet = {\n insert: function insert(rule) {\n sheet.insert(rule + serialized.map);\n }\n };\n }\n\n stylis(selector ? selector + \"{\" + serialized.styles + \"}\" : serialized.styles);\n\n if (shouldCache) {\n cache.inserted[serialized.name] = true;\n }\n };\n }\n\n var cache = {\n key: key,\n sheet: new StyleSheet({\n key: key,\n container: container,\n nonce: options.nonce,\n speedy: options.speedy,\n prepend: options.prepend,\n insertionPoint: options.insertionPoint\n }),\n nonce: options.nonce,\n inserted: inserted,\n registered: {},\n insert: _insert\n };\n cache.sheet.hydrate(nodesToHydrate);\n return cache;\n};\n\nexport default createCache;\n","import {MS, MOZ, WEBKIT, RULESET, KEYFRAMES, DECLARATION} from './Enum.js'\nimport {match, charat, substr, strlen, sizeof, replace, combine} from './Utility.js'\nimport {copy, tokenize} from './Tokenizer.js'\nimport {serialize} from './Serializer.js'\nimport {prefix} from './Prefixer.js'\n\n/**\n * @param {function[]} collection\n * @return {function}\n */\nexport function middleware (collection) {\n\tvar length = sizeof(collection)\n\n\treturn function (element, index, children, callback) {\n\t\tvar output = ''\n\n\t\tfor (var i = 0; i < length; i++)\n\t\t\toutput += collection[i](element, index, children, callback) || ''\n\n\t\treturn output\n\t}\n}\n\n/**\n * @param {function} callback\n * @return {function}\n */\nexport function rulesheet (callback) {\n\treturn function (element) {\n\t\tif (!element.root)\n\t\t\tif (element = element.return)\n\t\t\t\tcallback(element)\n\t}\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n * @param {function} callback\n */\nexport function prefixer (element, index, children, callback) {\n\tif (element.length > -1)\n\t\tif (!element.return)\n\t\t\tswitch (element.type) {\n\t\t\t\tcase DECLARATION: element.return = prefix(element.value, element.length)\n\t\t\t\t\tbreak\n\t\t\t\tcase KEYFRAMES:\n\t\t\t\t\treturn serialize([copy(element, {value: replace(element.value, '@', '@' + WEBKIT)})], callback)\n\t\t\t\tcase RULESET:\n\t\t\t\t\tif (element.length)\n\t\t\t\t\t\treturn combine(element.props, function (value) {\n\t\t\t\t\t\t\tswitch (match(value, /(::plac\\w+|:read-\\w+)/)) {\n\t\t\t\t\t\t\t\t// :read-(only|write)\n\t\t\t\t\t\t\t\tcase ':read-only': case ':read-write':\n\t\t\t\t\t\t\t\t\treturn serialize([copy(element, {props: [replace(value, /:(read-\\w+)/, ':' + MOZ + '$1')]})], callback)\n\t\t\t\t\t\t\t\t// :placeholder\n\t\t\t\t\t\t\t\tcase '::placeholder':\n\t\t\t\t\t\t\t\t\treturn serialize([\n\t\t\t\t\t\t\t\t\t\tcopy(element, {props: [replace(value, /:(plac\\w+)/, ':' + WEBKIT + 'input-$1')]}),\n\t\t\t\t\t\t\t\t\t\tcopy(element, {props: [replace(value, /:(plac\\w+)/, ':' + MOZ + '$1')]}),\n\t\t\t\t\t\t\t\t\t\tcopy(element, {props: [replace(value, /:(plac\\w+)/, MS + 'input-$1')]})\n\t\t\t\t\t\t\t\t\t], callback)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn ''\n\t\t\t\t\t\t})\n\t\t\t}\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n */\nexport function namespace (element) {\n\tswitch (element.type) {\n\t\tcase RULESET:\n\t\t\telement.props = element.props.map(function (value) {\n\t\t\t\treturn combine(tokenize(value), function (value, index, children) {\n\t\t\t\t\tswitch (charat(value, 0)) {\n\t\t\t\t\t\t// \\f\n\t\t\t\t\t\tcase 12:\n\t\t\t\t\t\t\treturn substr(value, 1, strlen(value))\n\t\t\t\t\t\t// \\0 ( + > ~\n\t\t\t\t\t\tcase 0: case 40: case 43: case 62: case 126:\n\t\t\t\t\t\t\treturn value\n\t\t\t\t\t\t// :\n\t\t\t\t\t\tcase 58:\n\t\t\t\t\t\t\tif (children[++index] === 'global')\n\t\t\t\t\t\t\t\tchildren[index] = '', children[++index] = '\\f' + substr(children[index], index = 1, -1)\n\t\t\t\t\t\t// \\s\n\t\t\t\t\t\tcase 32:\n\t\t\t\t\t\t\treturn index === 1 ? '' : value\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tswitch (index) {\n\t\t\t\t\t\t\t\tcase 0: element = value\n\t\t\t\t\t\t\t\t\treturn sizeof(children) > 1 ? '' : value\n\t\t\t\t\t\t\t\tcase index = sizeof(children) - 1: case 2:\n\t\t\t\t\t\t\t\t\treturn index === 2 ? value + element + element : value + element\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\treturn value\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t}\n}\n","var weakMemoize = function weakMemoize(func) {\n // $FlowFixMe flow doesn't include all non-primitive types as allowed for weakmaps\n var cache = new WeakMap();\n return function (arg) {\n if (cache.has(arg)) {\n // $FlowFixMe\n return cache.get(arg);\n }\n\n var ret = func(arg);\n cache.set(arg, ret);\n return ret;\n };\n};\n\nexport default weakMemoize;\n","var isBrowser = \"object\" !== 'undefined';\nfunction getRegisteredStyles(registered, registeredStyles, classNames) {\n var rawClassName = '';\n classNames.split(' ').forEach(function (className) {\n if (registered[className] !== undefined) {\n registeredStyles.push(registered[className] + \";\");\n } else {\n rawClassName += className + \" \";\n }\n });\n return rawClassName;\n}\nvar registerStyles = function registerStyles(cache, serialized, isStringTag) {\n var className = cache.key + \"-\" + serialized.name;\n\n if ( // we only need to add the styles to the registered cache if the\n // class name could be used further down\n // the tree but if it's a string tag, we know it won't\n // so we don't have to add it to registered cache.\n // this improves memory usage since we can avoid storing the whole style string\n (isStringTag === false || // we need to always store it if we're in compat mode and\n // in node since emotion-server relies on whether a style is in\n // the registered cache to know whether a style is global or not\n // also, note that this check will be dead code eliminated in the browser\n isBrowser === false ) && cache.registered[className] === undefined) {\n cache.registered[className] = serialized.styles;\n }\n};\nvar insertStyles = function insertStyles(cache, serialized, isStringTag) {\n registerStyles(cache, serialized, isStringTag);\n var className = cache.key + \"-\" + serialized.name;\n\n if (cache.inserted[serialized.name] === undefined) {\n var current = serialized;\n\n do {\n var maybeStyles = cache.insert(serialized === current ? \".\" + className : '', current, cache.sheet, true);\n\n current = current.next;\n } while (current !== undefined);\n }\n};\n\nexport { getRegisteredStyles, insertStyles, registerStyles };\n","/* eslint-disable */\n// Inspired by https://github.com/garycourt/murmurhash-js\n// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86\nfunction murmur2(str) {\n // 'm' and 'r' are mixing constants generated offline.\n // They're not really 'magic', they just happen to work well.\n // const m = 0x5bd1e995;\n // const r = 24;\n // Initialize the hash\n var h = 0; // Mix 4 bytes at a time into the hash\n\n var k,\n i = 0,\n len = str.length;\n\n for (; len >= 4; ++i, len -= 4) {\n k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;\n k =\n /* Math.imul(k, m): */\n (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);\n k ^=\n /* k >>> r: */\n k >>> 24;\n h =\n /* Math.imul(k, m): */\n (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n } // Handle the last few bytes of the input array\n\n\n switch (len) {\n case 3:\n h ^= (str.charCodeAt(i + 2) & 0xff) << 16;\n\n case 2:\n h ^= (str.charCodeAt(i + 1) & 0xff) << 8;\n\n case 1:\n h ^= str.charCodeAt(i) & 0xff;\n h =\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n } // Do a few final mixes of the hash to ensure the last few\n // bytes are well-incorporated.\n\n\n h ^= h >>> 13;\n h =\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n return ((h ^ h >>> 15) >>> 0).toString(36);\n}\n\nexport default murmur2;\n","var unitlessKeys = {\n animationIterationCount: 1,\n borderImageOutset: 1,\n borderImageSlice: 1,\n borderImageWidth: 1,\n boxFlex: 1,\n boxFlexGroup: 1,\n boxOrdinalGroup: 1,\n columnCount: 1,\n columns: 1,\n flex: 1,\n flexGrow: 1,\n flexPositive: 1,\n flexShrink: 1,\n flexNegative: 1,\n flexOrder: 1,\n gridRow: 1,\n gridRowEnd: 1,\n gridRowSpan: 1,\n gridRowStart: 1,\n gridColumn: 1,\n gridColumnEnd: 1,\n gridColumnSpan: 1,\n gridColumnStart: 1,\n msGridRow: 1,\n msGridRowSpan: 1,\n msGridColumn: 1,\n msGridColumnSpan: 1,\n fontWeight: 1,\n lineHeight: 1,\n opacity: 1,\n order: 1,\n orphans: 1,\n tabSize: 1,\n widows: 1,\n zIndex: 1,\n zoom: 1,\n WebkitLineClamp: 1,\n // SVG-related properties\n fillOpacity: 1,\n floodOpacity: 1,\n stopOpacity: 1,\n strokeDasharray: 1,\n strokeDashoffset: 1,\n strokeMiterlimit: 1,\n strokeOpacity: 1,\n strokeWidth: 1\n};\n\nexport default unitlessKeys;\n","import hashString from '@emotion/hash';\nimport unitless from '@emotion/unitless';\nimport memoize from '@emotion/memoize';\n\nvar ILLEGAL_ESCAPE_SEQUENCE_ERROR = \"You have illegal escape sequence in your template literal, most likely inside content's property value.\\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \\\"content: '\\\\00d7';\\\" should become \\\"content: '\\\\\\\\00d7';\\\".\\nYou can read more about this here:\\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences\";\nvar UNDEFINED_AS_OBJECT_KEY_ERROR = \"You have passed in falsy value as style object's key (can happen when in example you pass unexported component as computed key).\";\nvar hyphenateRegex = /[A-Z]|^ms/g;\nvar animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;\n\nvar isCustomProperty = function isCustomProperty(property) {\n return property.charCodeAt(1) === 45;\n};\n\nvar isProcessableValue = function isProcessableValue(value) {\n return value != null && typeof value !== 'boolean';\n};\n\nvar processStyleName = /* #__PURE__ */memoize(function (styleName) {\n return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase();\n});\n\nvar processStyleValue = function processStyleValue(key, value) {\n switch (key) {\n case 'animation':\n case 'animationName':\n {\n if (typeof value === 'string') {\n return value.replace(animationRegex, function (match, p1, p2) {\n cursor = {\n name: p1,\n styles: p2,\n next: cursor\n };\n return p1;\n });\n }\n }\n }\n\n if (unitless[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) {\n return value + 'px';\n }\n\n return value;\n};\n\nif (process.env.NODE_ENV !== 'production') {\n var contentValuePattern = /(var|attr|counters?|url|(((repeating-)?(linear|radial))|conic)-gradient)\\(|(no-)?(open|close)-quote/;\n var contentValues = ['normal', 'none', 'initial', 'inherit', 'unset'];\n var oldProcessStyleValue = processStyleValue;\n var msPattern = /^-ms-/;\n var hyphenPattern = /-(.)/g;\n var hyphenatedCache = {};\n\n processStyleValue = function processStyleValue(key, value) {\n if (key === 'content') {\n if (typeof value !== 'string' || contentValues.indexOf(value) === -1 && !contentValuePattern.test(value) && (value.charAt(0) !== value.charAt(value.length - 1) || value.charAt(0) !== '\"' && value.charAt(0) !== \"'\")) {\n throw new Error(\"You seem to be using a value for 'content' without quotes, try replacing it with `content: '\\\"\" + value + \"\\\"'`\");\n }\n }\n\n var processed = oldProcessStyleValue(key, value);\n\n if (processed !== '' && !isCustomProperty(key) && key.indexOf('-') !== -1 && hyphenatedCache[key] === undefined) {\n hyphenatedCache[key] = true;\n console.error(\"Using kebab-case for css properties in objects is not supported. Did you mean \" + key.replace(msPattern, 'ms-').replace(hyphenPattern, function (str, _char) {\n return _char.toUpperCase();\n }) + \"?\");\n }\n\n return processed;\n };\n}\n\nvar noComponentSelectorMessage = 'Component selectors can only be used in conjunction with ' + '@emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware ' + 'compiler transform.';\n\nfunction handleInterpolation(mergedProps, registered, interpolation) {\n if (interpolation == null) {\n return '';\n }\n\n if (interpolation.__emotion_styles !== undefined) {\n if (process.env.NODE_ENV !== 'production' && interpolation.toString() === 'NO_COMPONENT_SELECTOR') {\n throw new Error(noComponentSelectorMessage);\n }\n\n return interpolation;\n }\n\n switch (typeof interpolation) {\n case 'boolean':\n {\n return '';\n }\n\n case 'object':\n {\n if (interpolation.anim === 1) {\n cursor = {\n name: interpolation.name,\n styles: interpolation.styles,\n next: cursor\n };\n return interpolation.name;\n }\n\n if (interpolation.styles !== undefined) {\n var next = interpolation.next;\n\n if (next !== undefined) {\n // not the most efficient thing ever but this is a pretty rare case\n // and there will be very few iterations of this generally\n while (next !== undefined) {\n cursor = {\n name: next.name,\n styles: next.styles,\n next: cursor\n };\n next = next.next;\n }\n }\n\n var styles = interpolation.styles + \";\";\n\n if (process.env.NODE_ENV !== 'production' && interpolation.map !== undefined) {\n styles += interpolation.map;\n }\n\n return styles;\n }\n\n return createStringFromObject(mergedProps, registered, interpolation);\n }\n\n case 'function':\n {\n if (mergedProps !== undefined) {\n var previousCursor = cursor;\n var result = interpolation(mergedProps);\n cursor = previousCursor;\n return handleInterpolation(mergedProps, registered, result);\n } else if (process.env.NODE_ENV !== 'production') {\n console.error('Functions that are interpolated in css calls will be stringified.\\n' + 'If you want to have a css call based on props, create a function that returns a css call like this\\n' + 'let dynamicStyle = (props) => css`color: ${props.color}`\\n' + 'It can be called directly with props or interpolated in a styled call like this\\n' + \"let SomeComponent = styled('div')`${dynamicStyle}`\");\n }\n\n break;\n }\n\n case 'string':\n if (process.env.NODE_ENV !== 'production') {\n var matched = [];\n var replaced = interpolation.replace(animationRegex, function (match, p1, p2) {\n var fakeVarName = \"animation\" + matched.length;\n matched.push(\"const \" + fakeVarName + \" = keyframes`\" + p2.replace(/^@keyframes animation-\\w+/, '') + \"`\");\n return \"${\" + fakeVarName + \"}\";\n });\n\n if (matched.length) {\n console.error('`keyframes` output got interpolated into plain string, please wrap it with `css`.\\n\\n' + 'Instead of doing this:\\n\\n' + [].concat(matched, [\"`\" + replaced + \"`\"]).join('\\n') + '\\n\\nYou should wrap it with `css` like this:\\n\\n' + (\"css`\" + replaced + \"`\"));\n }\n }\n\n break;\n } // finalize string values (regular strings and functions interpolated into css calls)\n\n\n if (registered == null) {\n return interpolation;\n }\n\n var cached = registered[interpolation];\n return cached !== undefined ? cached : interpolation;\n}\n\nfunction createStringFromObject(mergedProps, registered, obj) {\n var string = '';\n\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; i++) {\n string += handleInterpolation(mergedProps, registered, obj[i]) + \";\";\n }\n } else {\n for (var _key in obj) {\n var value = obj[_key];\n\n if (typeof value !== 'object') {\n if (registered != null && registered[value] !== undefined) {\n string += _key + \"{\" + registered[value] + \"}\";\n } else if (isProcessableValue(value)) {\n string += processStyleName(_key) + \":\" + processStyleValue(_key, value) + \";\";\n }\n } else {\n if (_key === 'NO_COMPONENT_SELECTOR' && process.env.NODE_ENV !== 'production') {\n throw new Error(noComponentSelectorMessage);\n }\n\n if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {\n for (var _i = 0; _i < value.length; _i++) {\n if (isProcessableValue(value[_i])) {\n string += processStyleName(_key) + \":\" + processStyleValue(_key, value[_i]) + \";\";\n }\n }\n } else {\n var interpolated = handleInterpolation(mergedProps, registered, value);\n\n switch (_key) {\n case 'animation':\n case 'animationName':\n {\n string += processStyleName(_key) + \":\" + interpolated + \";\";\n break;\n }\n\n default:\n {\n if (process.env.NODE_ENV !== 'production' && _key === 'undefined') {\n console.error(UNDEFINED_AS_OBJECT_KEY_ERROR);\n }\n\n string += _key + \"{\" + interpolated + \"}\";\n }\n }\n }\n }\n }\n }\n\n return string;\n}\n\nvar labelPattern = /label:\\s*([^\\s;\\n{]+)\\s*(;|$)/g;\nvar sourceMapPattern;\n\nif (process.env.NODE_ENV !== 'production') {\n sourceMapPattern = /\\/\\*#\\ssourceMappingURL=data:application\\/json;\\S+\\s+\\*\\//g;\n} // this is the cursor for keyframes\n// keyframes are stored on the SerializedStyles object as a linked list\n\n\nvar cursor;\nvar serializeStyles = function serializeStyles(args, registered, mergedProps) {\n if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {\n return args[0];\n }\n\n var stringMode = true;\n var styles = '';\n cursor = undefined;\n var strings = args[0];\n\n if (strings == null || strings.raw === undefined) {\n stringMode = false;\n styles += handleInterpolation(mergedProps, registered, strings);\n } else {\n if (process.env.NODE_ENV !== 'production' && strings[0] === undefined) {\n console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);\n }\n\n styles += strings[0];\n } // we start at 1 since we've already handled the first arg\n\n\n for (var i = 1; i < args.length; i++) {\n styles += handleInterpolation(mergedProps, registered, args[i]);\n\n if (stringMode) {\n if (process.env.NODE_ENV !== 'production' && strings[i] === undefined) {\n console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);\n }\n\n styles += strings[i];\n }\n }\n\n var sourceMap;\n\n if (process.env.NODE_ENV !== 'production') {\n styles = styles.replace(sourceMapPattern, function (match) {\n sourceMap = match;\n return '';\n });\n } // using a global regex with .exec is stateful so lastIndex has to be reset each time\n\n\n labelPattern.lastIndex = 0;\n var identifierName = '';\n var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5\n\n while ((match = labelPattern.exec(styles)) !== null) {\n identifierName += '-' + // $FlowFixMe we know it's not null\n match[1];\n }\n\n var name = hashString(styles) + identifierName;\n\n if (process.env.NODE_ENV !== 'production') {\n // $FlowFixMe SerializedStyles type doesn't have toString property (and we don't want to add it)\n return {\n name: name,\n styles: styles,\n map: sourceMap,\n next: cursor,\n toString: function toString() {\n return \"You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop).\";\n }\n };\n }\n\n return {\n name: name,\n styles: styles,\n next: cursor\n };\n};\n\nexport { serializeStyles };\n","import * as React from 'react';\nimport { useLayoutEffect } from 'react';\n\nvar syncFallback = function syncFallback(create) {\n return create();\n};\n\nvar useInsertionEffect = React['useInsertion' + 'Effect'] ? React['useInsertion' + 'Effect'] : false;\nvar useInsertionEffectAlwaysWithSyncFallback = useInsertionEffect || syncFallback;\nvar useInsertionEffectWithLayoutFallback = useInsertionEffect || useLayoutEffect;\n\nexport { useInsertionEffectAlwaysWithSyncFallback, useInsertionEffectWithLayoutFallback };\n","import { createContext, useContext, forwardRef, createElement, Fragment } from 'react';\nimport createCache from '@emotion/cache';\nimport _extends from '@babel/runtime/helpers/esm/extends';\nimport weakMemoize from '@emotion/weak-memoize';\nimport hoistNonReactStatics from '../_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js';\nimport { getRegisteredStyles, registerStyles, insertStyles } from '@emotion/utils';\nimport { serializeStyles } from '@emotion/serialize';\nimport { useInsertionEffectAlwaysWithSyncFallback } from '@emotion/use-insertion-effect-with-fallbacks';\n\nvar hasOwnProperty = {}.hasOwnProperty;\n\nvar EmotionCacheContext = /* #__PURE__ */createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case\n// because this module is primarily intended for the browser and node\n// but it's also required in react native and similar environments sometimes\n// and we could have a special build just for that\n// but this is much easier and the native packages\n// might use a different theme context in the future anyway\ntypeof HTMLElement !== 'undefined' ? /* #__PURE__ */createCache({\n key: 'css'\n}) : null);\n\nif (process.env.NODE_ENV !== 'production') {\n EmotionCacheContext.displayName = 'EmotionCacheContext';\n}\n\nvar CacheProvider = EmotionCacheContext.Provider;\nvar __unsafe_useEmotionCache = function useEmotionCache() {\n return useContext(EmotionCacheContext);\n};\n\nvar withEmotionCache = function withEmotionCache(func) {\n // $FlowFixMe\n return /*#__PURE__*/forwardRef(function (props, ref) {\n // the cache will never be null in the browser\n var cache = useContext(EmotionCacheContext);\n return func(props, cache, ref);\n });\n};\n\nvar ThemeContext = /* #__PURE__ */createContext({});\n\nif (process.env.NODE_ENV !== 'production') {\n ThemeContext.displayName = 'EmotionThemeContext';\n}\n\nvar useTheme = function useTheme() {\n return useContext(ThemeContext);\n};\n\nvar getTheme = function getTheme(outerTheme, theme) {\n if (typeof theme === 'function') {\n var mergedTheme = theme(outerTheme);\n\n if (process.env.NODE_ENV !== 'production' && (mergedTheme == null || typeof mergedTheme !== 'object' || Array.isArray(mergedTheme))) {\n throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!');\n }\n\n return mergedTheme;\n }\n\n if (process.env.NODE_ENV !== 'production' && (theme == null || typeof theme !== 'object' || Array.isArray(theme))) {\n throw new Error('[ThemeProvider] Please make your theme prop a plain object');\n }\n\n return _extends({}, outerTheme, theme);\n};\n\nvar createCacheWithTheme = /* #__PURE__ */weakMemoize(function (outerTheme) {\n return weakMemoize(function (theme) {\n return getTheme(outerTheme, theme);\n });\n});\nvar ThemeProvider = function ThemeProvider(props) {\n var theme = useContext(ThemeContext);\n\n if (props.theme !== theme) {\n theme = createCacheWithTheme(theme)(props.theme);\n }\n\n return /*#__PURE__*/createElement(ThemeContext.Provider, {\n value: theme\n }, props.children);\n};\nfunction withTheme(Component) {\n var componentName = Component.displayName || Component.name || 'Component';\n\n var render = function render(props, ref) {\n var theme = useContext(ThemeContext);\n return /*#__PURE__*/createElement(Component, _extends({\n theme: theme,\n ref: ref\n }, props));\n }; // $FlowFixMe\n\n\n var WithTheme = /*#__PURE__*/forwardRef(render);\n WithTheme.displayName = \"WithTheme(\" + componentName + \")\";\n return hoistNonReactStatics(WithTheme, Component);\n}\n\nvar getLastPart = function getLastPart(functionName) {\n // The match may be something like 'Object.createEmotionProps' or\n // 'Loader.prototype.render'\n var parts = functionName.split('.');\n return parts[parts.length - 1];\n};\n\nvar getFunctionNameFromStackTraceLine = function getFunctionNameFromStackTraceLine(line) {\n // V8\n var match = /^\\s+at\\s+([A-Za-z0-9$.]+)\\s/.exec(line);\n if (match) return getLastPart(match[1]); // Safari / Firefox\n\n match = /^([A-Za-z0-9$.]+)@/.exec(line);\n if (match) return getLastPart(match[1]);\n return undefined;\n};\n\nvar internalReactFunctionNames = /* #__PURE__ */new Set(['renderWithHooks', 'processChild', 'finishClassComponent', 'renderToString']); // These identifiers come from error stacks, so they have to be valid JS\n// identifiers, thus we only need to replace what is a valid character for JS,\n// but not for CSS.\n\nvar sanitizeIdentifier = function sanitizeIdentifier(identifier) {\n return identifier.replace(/\\$/g, '-');\n};\n\nvar getLabelFromStackTrace = function getLabelFromStackTrace(stackTrace) {\n if (!stackTrace) return undefined;\n var lines = stackTrace.split('\\n');\n\n for (var i = 0; i < lines.length; i++) {\n var functionName = getFunctionNameFromStackTraceLine(lines[i]); // The first line of V8 stack traces is just \"Error\"\n\n if (!functionName) continue; // If we reach one of these, we have gone too far and should quit\n\n if (internalReactFunctionNames.has(functionName)) break; // The component name is the first function in the stack that starts with an\n // uppercase letter\n\n if (/^[A-Z]/.test(functionName)) return sanitizeIdentifier(functionName);\n }\n\n return undefined;\n};\n\nvar typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';\nvar labelPropName = '__EMOTION_LABEL_PLEASE_DO_NOT_USE__';\nvar createEmotionProps = function createEmotionProps(type, props) {\n if (process.env.NODE_ENV !== 'production' && typeof props.css === 'string' && // check if there is a css declaration\n props.css.indexOf(':') !== -1) {\n throw new Error(\"Strings are not allowed as css prop values, please wrap it in a css template literal from '@emotion/react' like this: css`\" + props.css + \"`\");\n }\n\n var newProps = {};\n\n for (var key in props) {\n if (hasOwnProperty.call(props, key)) {\n newProps[key] = props[key];\n }\n }\n\n newProps[typePropName] = type; // For performance, only call getLabelFromStackTrace in development and when\n // the label hasn't already been computed\n\n if (process.env.NODE_ENV !== 'production' && !!props.css && (typeof props.css !== 'object' || typeof props.css.name !== 'string' || props.css.name.indexOf('-') === -1)) {\n var label = getLabelFromStackTrace(new Error().stack);\n if (label) newProps[labelPropName] = label;\n }\n\n return newProps;\n};\n\nvar Insertion = function Insertion(_ref) {\n var cache = _ref.cache,\n serialized = _ref.serialized,\n isStringTag = _ref.isStringTag;\n registerStyles(cache, serialized, isStringTag);\n var rules = useInsertionEffectAlwaysWithSyncFallback(function () {\n return insertStyles(cache, serialized, isStringTag);\n });\n\n return null;\n};\n\nvar Emotion = /* #__PURE__ */withEmotionCache(function (props, cache, ref) {\n var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works\n // not passing the registered cache to serializeStyles because it would\n // make certain babel optimisations not possible\n\n if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {\n cssProp = cache.registered[cssProp];\n }\n\n var WrappedComponent = props[typePropName];\n var registeredStyles = [cssProp];\n var className = '';\n\n if (typeof props.className === 'string') {\n className = getRegisteredStyles(cache.registered, registeredStyles, props.className);\n } else if (props.className != null) {\n className = props.className + \" \";\n }\n\n var serialized = serializeStyles(registeredStyles, undefined, useContext(ThemeContext));\n\n if (process.env.NODE_ENV !== 'production' && serialized.name.indexOf('-') === -1) {\n var labelFromStack = props[labelPropName];\n\n if (labelFromStack) {\n serialized = serializeStyles([serialized, 'label:' + labelFromStack + ';']);\n }\n }\n\n className += cache.key + \"-\" + serialized.name;\n var newProps = {};\n\n for (var key in props) {\n if (hasOwnProperty.call(props, key) && key !== 'css' && key !== typePropName && (process.env.NODE_ENV === 'production' || key !== labelPropName)) {\n newProps[key] = props[key];\n }\n }\n\n newProps.ref = ref;\n newProps.className = className;\n return /*#__PURE__*/createElement(Fragment, null, /*#__PURE__*/createElement(Insertion, {\n cache: cache,\n serialized: serialized,\n isStringTag: typeof WrappedComponent === 'string'\n }), /*#__PURE__*/createElement(WrappedComponent, newProps));\n});\n\nif (process.env.NODE_ENV !== 'production') {\n Emotion.displayName = 'EmotionCssPropInternal';\n}\n\nexport { CacheProvider as C, Emotion as E, ThemeContext as T, __unsafe_useEmotionCache as _, ThemeProvider as a, withTheme as b, createEmotionProps as c, hasOwnProperty as h, useTheme as u, withEmotionCache as w };\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport { useContext, createElement, Fragment } from 'react';\nimport isPropValid from '@emotion/is-prop-valid';\nimport { withEmotionCache, ThemeContext } from '@emotion/react';\nimport { getRegisteredStyles, registerStyles, insertStyles } from '@emotion/utils';\nimport { serializeStyles } from '@emotion/serialize';\nimport { useInsertionEffectAlwaysWithSyncFallback } from '@emotion/use-insertion-effect-with-fallbacks';\n\nvar testOmitPropsOnStringTag = isPropValid;\n\nvar testOmitPropsOnComponent = function testOmitPropsOnComponent(key) {\n return key !== 'theme';\n};\n\nvar getDefaultShouldForwardProp = function getDefaultShouldForwardProp(tag) {\n return typeof tag === 'string' && // 96 is one less than the char code\n // for \"a\" so this is checking that\n // it's a lowercase character\n tag.charCodeAt(0) > 96 ? testOmitPropsOnStringTag : testOmitPropsOnComponent;\n};\nvar composeShouldForwardProps = function composeShouldForwardProps(tag, options, isReal) {\n var shouldForwardProp;\n\n if (options) {\n var optionsShouldForwardProp = options.shouldForwardProp;\n shouldForwardProp = tag.__emotion_forwardProp && optionsShouldForwardProp ? function (propName) {\n return tag.__emotion_forwardProp(propName) && optionsShouldForwardProp(propName);\n } : optionsShouldForwardProp;\n }\n\n if (typeof shouldForwardProp !== 'function' && isReal) {\n shouldForwardProp = tag.__emotion_forwardProp;\n }\n\n return shouldForwardProp;\n};\n\nvar ILLEGAL_ESCAPE_SEQUENCE_ERROR = \"You have illegal escape sequence in your template literal, most likely inside content's property value.\\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \\\"content: '\\\\00d7';\\\" should become \\\"content: '\\\\\\\\00d7';\\\".\\nYou can read more about this here:\\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences\";\n\nvar Insertion = function Insertion(_ref) {\n var cache = _ref.cache,\n serialized = _ref.serialized,\n isStringTag = _ref.isStringTag;\n registerStyles(cache, serialized, isStringTag);\n var rules = useInsertionEffectAlwaysWithSyncFallback(function () {\n return insertStyles(cache, serialized, isStringTag);\n });\n\n return null;\n};\n\nvar createStyled = function createStyled(tag, options) {\n if (process.env.NODE_ENV !== 'production') {\n if (tag === undefined) {\n throw new Error('You are trying to create a styled element with an undefined component.\\nYou may have forgotten to import it.');\n }\n }\n\n var isReal = tag.__emotion_real === tag;\n var baseTag = isReal && tag.__emotion_base || tag;\n var identifierName;\n var targetClassName;\n\n if (options !== undefined) {\n identifierName = options.label;\n targetClassName = options.target;\n }\n\n var shouldForwardProp = composeShouldForwardProps(tag, options, isReal);\n var defaultShouldForwardProp = shouldForwardProp || getDefaultShouldForwardProp(baseTag);\n var shouldUseAs = !defaultShouldForwardProp('as');\n return function () {\n var args = arguments;\n var styles = isReal && tag.__emotion_styles !== undefined ? tag.__emotion_styles.slice(0) : [];\n\n if (identifierName !== undefined) {\n styles.push(\"label:\" + identifierName + \";\");\n }\n\n if (args[0] == null || args[0].raw === undefined) {\n styles.push.apply(styles, args);\n } else {\n if (process.env.NODE_ENV !== 'production' && args[0][0] === undefined) {\n console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);\n }\n\n styles.push(args[0][0]);\n var len = args.length;\n var i = 1;\n\n for (; i < len; i++) {\n if (process.env.NODE_ENV !== 'production' && args[0][i] === undefined) {\n console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);\n }\n\n styles.push(args[i], args[0][i]);\n }\n } // $FlowFixMe: we need to cast StatelessFunctionalComponent to our PrivateStyledComponent class\n\n\n var Styled = withEmotionCache(function (props, cache, ref) {\n var FinalTag = shouldUseAs && props.as || baseTag;\n var className = '';\n var classInterpolations = [];\n var mergedProps = props;\n\n if (props.theme == null) {\n mergedProps = {};\n\n for (var key in props) {\n mergedProps[key] = props[key];\n }\n\n mergedProps.theme = useContext(ThemeContext);\n }\n\n if (typeof props.className === 'string') {\n className = getRegisteredStyles(cache.registered, classInterpolations, props.className);\n } else if (props.className != null) {\n className = props.className + \" \";\n }\n\n var serialized = serializeStyles(styles.concat(classInterpolations), cache.registered, mergedProps);\n className += cache.key + \"-\" + serialized.name;\n\n if (targetClassName !== undefined) {\n className += \" \" + targetClassName;\n }\n\n var finalShouldForwardProp = shouldUseAs && shouldForwardProp === undefined ? getDefaultShouldForwardProp(FinalTag) : defaultShouldForwardProp;\n var newProps = {};\n\n for (var _key in props) {\n if (shouldUseAs && _key === 'as') continue;\n\n if ( // $FlowFixMe\n finalShouldForwardProp(_key)) {\n newProps[_key] = props[_key];\n }\n }\n\n newProps.className = className;\n newProps.ref = ref;\n return /*#__PURE__*/createElement(Fragment, null, /*#__PURE__*/createElement(Insertion, {\n cache: cache,\n serialized: serialized,\n isStringTag: typeof FinalTag === 'string'\n }), /*#__PURE__*/createElement(FinalTag, newProps));\n });\n Styled.displayName = identifierName !== undefined ? identifierName : \"Styled(\" + (typeof baseTag === 'string' ? baseTag : baseTag.displayName || baseTag.name || 'Component') + \")\";\n Styled.defaultProps = tag.defaultProps;\n Styled.__emotion_real = Styled;\n Styled.__emotion_base = baseTag;\n Styled.__emotion_styles = styles;\n Styled.__emotion_forwardProp = shouldForwardProp;\n Object.defineProperty(Styled, 'toString', {\n value: function value() {\n if (targetClassName === undefined && process.env.NODE_ENV !== 'production') {\n return 'NO_COMPONENT_SELECTOR';\n } // $FlowFixMe: coerce undefined to string\n\n\n return \".\" + targetClassName;\n }\n });\n\n Styled.withComponent = function (nextTag, nextOptions) {\n return createStyled(nextTag, _extends({}, options, nextOptions, {\n shouldForwardProp: composeShouldForwardProps(Styled, nextOptions, true)\n })).apply(void 0, styles);\n };\n\n return Styled;\n };\n};\n\nexport default createStyled;\n","import '@babel/runtime/helpers/extends';\nimport 'react';\nimport '@emotion/is-prop-valid';\nimport createStyled from '../base/dist/emotion-styled-base.browser.esm.js';\nimport '@emotion/react';\nimport '@emotion/utils';\nimport '@emotion/serialize';\nimport '@emotion/use-insertion-effect-with-fallbacks';\n\nvar tags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG\n'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];\n\nvar newStyled = createStyled.bind();\ntags.forEach(function (tagName) {\n // $FlowFixMe: we can ignore this because its exposed type is defined by the CreateStyled type\n newStyled[tagName] = newStyled(tagName);\n});\n\nexport default newStyled;\n","function add(first, second) {\n return first + second;\n}\n\nvar _ref = {},\n hasOwnProperty = _ref.hasOwnProperty;\nfunction hasOwn(prop, obj) {\n return hasOwnProperty.call(obj, prop);\n}\n\nfunction assign() {\n // eslint-disable-next-line no-func-assign\n assign = Object.assign || function (target) {\n for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n sources[_key - 1] = arguments[_key];\n }\n\n sources.forEach(function (source) {\n for (var key in source) {\n if (hasOwn(key, source)) {\n target[key] = source[key];\n }\n }\n });\n return target;\n };\n\n return assign.apply(void 0, arguments);\n}\n\nvar capitalizeFirstLetter = function capitalizeFirstLetter(text) {\n return text.charAt(0).toUpperCase() + text.slice(1);\n};\n\nfunction flatMap(iteratee, arr) {\n var _ref;\n\n return (_ref = []).concat.apply(_ref, arr.map(iteratee));\n}\n\nfunction chain(fn, listOrFn) {\n if (typeof listOrFn === 'function') {\n return function (list) {\n return fn(listOrFn(list))(list);\n };\n }\n\n return flatMap(fn, listOrFn);\n}\n\nfunction chunk(arr, number) {\n var chunked = [];\n\n for (var i = 0; i < arr.length; i += number) {\n chunked.push(arr.slice(i, i + number));\n }\n\n return chunked;\n}\n\nvar isArray = Array.isArray;\n\nfunction isObject(obj) {\n return typeof obj === 'object' && obj !== null && !isArray(obj);\n}\n\nfunction mapValues(mapper, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n acc[key] = mapper(obj[key]);\n return acc;\n }, {});\n}\n\nfunction cloneDeep(value) {\n if (isArray(value)) {\n return value.map(cloneDeep);\n }\n\n if (isObject(value)) {\n return mapValues(cloneDeep, value);\n }\n\n return value;\n}\n\n// slightly simplified version of https://github.com/sindresorhus/camelcase/blob/a526ef0399f9a1310eaacafa0ae4a69da4a2f1ad/index.js\n// TODO: possibly could be rewritten using short-ish regexp\nvar preserveCamelCase = function preserveCamelCase(input) {\n var text = input;\n var isLastCharLower = false;\n var isLastCharUpper = false;\n var isLastLastCharUpper = false;\n\n for (var index = 0; index < text.length; index++) {\n var _char = text[index];\n\n if (isLastCharLower && /[a-zA-Z]/.test(_char) && _char.toUpperCase() === _char) {\n text = text.slice(0, index) + '-' + text.slice(index);\n isLastCharLower = false;\n isLastLastCharUpper = isLastCharUpper;\n isLastCharUpper = true;\n index++;\n } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(_char) && _char.toLowerCase() === _char) {\n text = text.slice(0, index - 1) + '-' + text.slice(index - 1);\n isLastLastCharUpper = isLastCharUpper;\n isLastCharUpper = false;\n isLastCharLower = true;\n } else {\n isLastCharLower = _char.toLowerCase() === _char;\n isLastLastCharUpper = isLastCharUpper;\n isLastCharUpper = _char.toUpperCase() === _char;\n }\n }\n\n return text;\n};\n\nfunction camelCase(input) {\n var text = input.trim();\n\n if (text.length === 0) {\n return '';\n }\n\n if (text.length === 1) {\n return text.toLowerCase();\n }\n\n if (/^[a-z\\d]+$/.test(text)) {\n return text;\n }\n\n var hasUpperCase = text !== text.toLowerCase();\n\n if (hasUpperCase) {\n text = preserveCamelCase(text);\n }\n\n text = text.replace(/^[_.\\- ]+/, '').toLowerCase().replace(/[_.\\- ]+(\\w|$)/g, function (match, p1) {\n return p1.toUpperCase();\n });\n return text;\n}\n\nfunction compact(collection) {\n return isArray(collection) ? collection.filter(function (value) {\n return value !== null && value !== undefined;\n }) : Object.keys(collection).reduce(function (result, key) {\n var value = collection[key];\n\n if (value !== null && value !== undefined) {\n result[key] = value;\n }\n\n return result;\n }, {});\n}\n\nfunction compose() {\n for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {\n funcs[_key] = arguments[_key];\n }\n\n return funcs.reduce(function (composed, next) {\n return function () {\n return composed(next.apply(void 0, arguments));\n };\n });\n}\n\nfunction debounce(ms, fn) {\n // actual return type of setTimeout differs per platform (browser vs node)\n var timeoutId;\n return function () {\n clearTimeout(timeoutId);\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n timeoutId = setTimeout.apply(void 0, [fn, ms].concat(args));\n };\n}\n\nfunction mapKeys(mapper, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n if (obj[key] && typeof obj[key] === 'object') {\n if (Array.isArray(obj[key])) {\n acc[mapper(key)] = obj[key].map(function (el) {\n return mapKeys(mapper, el);\n });\n return acc;\n }\n\n acc[mapper(key)] = mapKeys(mapper, obj[key]);\n return acc;\n }\n\n acc[mapper(key)] = obj[key];\n return acc;\n }, {});\n}\n\nfunction deepMerge(target) {\n for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n sources[_key - 1] = arguments[_key];\n }\n\n if (!sources.length) return target;\n var source = sources.shift();\n\n if (isObject(target) && isObject(source)) {\n for (var key in source) {\n if (isObject(source[key])) {\n var _Object$assign;\n\n if (!target[key]) Object.assign(target, (_Object$assign = {}, _Object$assign[key] = {}, _Object$assign));\n deepMerge(target[key], source[key]);\n } else {\n var _Object$assign2;\n\n Object.assign(target, (_Object$assign2 = {}, _Object$assign2[key] = source[key], _Object$assign2));\n }\n }\n }\n\n return deepMerge.apply(void 0, [target].concat(sources));\n}\n\nfunction isNil(value) {\n return value === null || value === undefined;\n}\n\nfunction defaultTo(defaultValue) {\n return function (value) {\n return isNil(value) ? defaultValue : value;\n };\n}\n\nfunction drop(count, arr) {\n return arr.slice(count);\n}\n\nfunction dropRight(count, arr) {\n return arr.slice(0, -count);\n}\n\nfunction ensureArray(maybeArr) {\n return isArray(maybeArr) ? maybeArr : [maybeArr];\n}\n\nfunction entries(obj) {\n return Object.keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n}\n\nfunction find(predicate, arr) {\n for (var index = 0; index < arr.length; index++) {\n var element = arr[index];\n\n if (predicate(element)) {\n return element;\n }\n }\n}\n\nfunction findIndex(predicate, arr) {\n for (var index = 0; index < arr.length; index++) {\n if (predicate(arr[index])) {\n return index;\n }\n }\n\n return -1;\n}\n\nfunction findKey(predicate, obj) {\n return find(function (key) {\n return predicate(obj[key]);\n }, Object.keys(obj));\n}\n\nfunction findLast(predicate, arr) {\n for (var index = arr.length - 1; index >= 0; index--) {\n if (predicate(arr[index])) {\n return arr[index];\n }\n }\n}\n\nfunction findLastIndexFrom(predicate, startIndex, arr) {\n for (var index = startIndex; index >= 0; index--) {\n if (predicate(arr[index])) {\n return index;\n }\n }\n\n return -1;\n}\n\nfunction findLastIndex(predicate, arr) {\n return findLastIndexFrom(predicate, arr.length - 1, arr);\n}\n\nfunction filledArray(length, value) {\n var arr = [];\n\n while (length--) {\n arr.push(value);\n }\n\n return arr;\n}\n\nfunction identity(value) {\n return value;\n}\n\nfunction flatten(arr) {\n return flatMap(identity, arr);\n}\n\nfunction forOwn(callback, obj) {\n return Object.keys(obj).forEach(function (key) {\n callback(obj[key], key);\n });\n}\n\nfunction fromPairs(pairs) {\n return pairs.reduce(function (obj, _ref) {\n var key = _ref[0],\n value = _ref[1];\n obj[key] = value;\n return obj;\n }, {});\n}\n\nfunction generateRandomId() {\n return Math.random().toString(36).substring(2);\n}\n\nfunction generateUniqueId(map) {\n var id = generateRandomId();\n return hasOwn(id, map) ? generateUniqueId(map) : id;\n}\n\n// based on https://github.com/developit/dlv/blob/d7ec976d12665f1c25dec2acf955dfc2e8757a9c/index.js\nfunction get(propPath, obj) {\n var arrPath = typeof propPath === 'string' ? propPath.split('.') : propPath;\n var pathPartIndex = 0;\n var result = obj;\n\n while (result && pathPartIndex < arrPath.length) {\n result = result[arrPath[pathPartIndex++]];\n }\n\n return result;\n}\n\nfunction getOr(defaultValue, prop, obj) {\n var propValue = get(prop, obj);\n return propValue !== undefined && propValue !== null ? propValue : defaultValue;\n}\n\nfunction groupBy(mapper, collection) {\n return Object.keys(collection).reduce(function (grouped, key) {\n var element = collection[key];\n var groupKey = mapper(element);\n grouped[groupKey] = grouped[groupKey] || [];\n grouped[groupKey].push(element);\n return grouped;\n }, {});\n}\n\nfunction groupKeys(mapper, obj) {\n return Object.keys(obj).reduce(function (grouped, key) {\n var groupKey = mapper(key);\n grouped[groupKey] = grouped[groupKey] || {};\n grouped[groupKey][key] = obj[key];\n return grouped;\n }, {});\n}\n\nfunction includes(value, arrOrStr) {\n return arrOrStr.indexOf(value) !== -1;\n}\n\nfunction isEmpty(collection) {\n return (isArray(collection) ? collection : Object.keys(collection)).length === 0;\n}\n\nfunction isFalsy (value) {\n return !value;\n}\n\nfunction isTruthy (value) {\n return !!value;\n}\n\nvar isPromise = function isPromise(promise) {\n return !!promise && typeof promise.then === 'function';\n};\n\nfunction keyBy(prop, arr) {\n return arr.reduce(function (acc, el) {\n acc[el[prop]] = el;\n return acc;\n }, {});\n}\n\nfunction keys(obj) {\n var keysArray = [];\n\n for (var property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n keysArray.push(property);\n }\n }\n\n return keysArray;\n}\n\n// TODO: this should return `T | undefined` to match native behavior\nfunction last(arr) {\n return arr.length > 0 ? arr[arr.length - 1] : null;\n}\n\nfunction mapKeys$1(mapper, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n acc[mapper(key)] = obj[key];\n return acc;\n }, {});\n}\n\nfunction mapValuesIndexed(iteratee, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n acc[key] = iteratee(obj[key], key);\n return acc;\n }, {});\n}\n\nfunction merge(objA, objB) {\n if (isEmpty(objB)) {\n return objA;\n }\n\n var result = {};\n forOwn(function (value, key) {\n if (hasOwn(key, objB)) {\n if (isObject(objA[key]) && isObject(objB[key])) {\n result[key] = merge(objA[key], objB[key]);\n } else if (isArray(objA[key]) && isArray(objB[key])) {\n var length = Math.max(objA[key].length, objB[key].length);\n result[key] = new Array(length);\n\n for (var i = 0; i < length; i++) {\n if (i in objB[key]) {\n result[key][i] = objB[key][i];\n } else if (i in objA[key]) {\n result[key][i] = objA[key][i];\n }\n }\n } else {\n result[key] = objB[key];\n }\n } else {\n result[key] = objA[key];\n }\n }, objA);\n forOwn(function (value, key) {\n if (!hasOwn(key, result)) {\n result[key] = objB[key];\n }\n }, objB);\n return result;\n}\n\nfunction mergeAll(objs) {\n if (objs.length === 0) {\n return {};\n }\n\n var first = objs[0],\n rest = objs.slice(1);\n return rest.reduce(function (merged, obj) {\n return merge(merged, obj);\n }, first);\n}\n\nfunction memoizeWith(keyResolver, func) {\n var cache = {};\n return function () {\n var key = keyResolver.apply(void 0, arguments);\n\n if (hasOwn(key, cache)) {\n return cache[key];\n }\n\n var value = func.apply(void 0, arguments);\n cache[key] = value;\n return value;\n };\n}\n\n// TODO: technically this should accept AnyFunction but it doesn't type check currently with that for some reason\nfunction memoize(func) {\n return memoizeWith(identity, func);\n}\n\nfunction memoizeOne(fn) {\n var called = false;\n var memoized;\n var cacheKey;\n return function () {\n if (called && (arguments.length <= 0 ? undefined : arguments[0]) === cacheKey) {\n return memoized;\n }\n\n called = true;\n cacheKey = arguments.length <= 0 ? undefined : arguments[0];\n memoized = fn.apply(void 0, arguments);\n return memoized;\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop() {}\n\nfunction values(obj) {\n return Object.keys(obj).map(function (key) {\n return obj[key];\n });\n}\n\nfunction numericSortBy(propOrMapper, collection) {\n var mapper = typeof propOrMapper === 'function' ? propOrMapper : function (element) {\n return get(propOrMapper, element);\n };\n return (isArray(collection) ? [].concat(collection) : values(collection)).sort(function (elementA, elementB) {\n return mapper(elementA) - mapper(elementB);\n });\n}\n\nfunction omitByIndexed(predicate, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n if (!predicate(obj[key], key)) {\n acc[key] = obj[key];\n }\n\n return acc;\n }, {});\n}\n\nfunction omit(keys, obj) {\n return omitByIndexed(function (_, key) {\n return keys.indexOf(key) !== -1;\n }, obj);\n}\n\nfunction omitBy(predicate, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n if (!predicate(obj[key])) {\n acc[key] = obj[key];\n }\n\n return acc;\n }, {});\n}\n\nfunction once(fn) {\n var called = false;\n var result;\n return function () {\n if (called) {\n return result;\n }\n\n called = true;\n return result = fn.apply(void 0, arguments);\n };\n}\n\nfunction over(fns) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return fns.map(function (fn) {\n return fn.apply(void 0, args);\n });\n };\n}\n\nfunction takeLast(count, arr) {\n return arr.slice(-count);\n}\n\nfunction overArgs(fn, transformers) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var transformed = transformers.map(function (transform, index) {\n return transform(args[index]);\n });\n return args.length > transformed.length ? fn.apply(void 0, transformed.concat(takeLast(args.length - transformed.length, args))) : fn.apply(void 0, transformed);\n };\n}\n\nfunction pair(a, b) {\n return [a, b];\n}\n\nfunction partitionObject(predicate, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n acc[predicate(obj[key]) ? 0 : 1][key] = obj[key];\n return acc;\n }, [{}, {}]);\n}\n\nfunction pick(props, obj) {\n return props.reduce(function (acc, prop) {\n acc[prop] = obj[prop];\n return acc;\n }, {});\n}\n\nfunction pickBy(predicate, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n if (predicate(obj[key])) {\n acc[key] = obj[key];\n }\n\n return acc;\n }, {});\n}\n\nfunction pickByIndexed(predicate, obj) {\n return Object.keys(obj).reduce(function (acc, key) {\n if (predicate(obj[key], key)) {\n acc[key] = obj[key];\n }\n\n return acc;\n }, {});\n}\n\nfunction pickOwn(props, obj) {\n return props.reduce(function (acc, prop) {\n if (hasOwn(prop, obj)) {\n acc[prop] = obj[prop];\n }\n\n return acc;\n }, {});\n}\n\nfunction randomInt(min, max) {\n return min + Math.floor(Math.random() * (max - min + 1));\n}\n\nfunction range(max) {\n var arr = [];\n var counter = 0;\n\n while (counter <= max) {\n arr.push(counter++);\n }\n\n return arr;\n}\n\nfunction reject(predicate, arr) {\n return arr.filter(function (element) {\n return !predicate(element);\n });\n}\n\nfunction removeAt(index, arr) {\n var copy = [].concat(arr);\n copy.splice(index, 1);\n return copy;\n}\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) {\n var it;\n\n if (typeof Symbol === \"undefined\" || o[Symbol.iterator] == null) {\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n return function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n\n it = o[Symbol.iterator]();\n return it.next.bind(it);\n}\n\nfunction set(_keys, val, obj) {\n var _extends2;\n\n var keys = _keys.split ? _keys.split('.') : _keys;\n var index = keys[0];\n var finalVal = val;\n\n if (keys.length > 1) {\n // eslint-disable-next-line eqeqeq\n var nextObj = obj != null && hasOwn(index, obj) ? obj[index] : {};\n finalVal = set(keys.slice(1), val, nextObj);\n }\n\n return _extends({}, obj, (_extends2 = {}, _extends2[index] = finalVal, _extends2));\n}\n\n// https://github.com/reactjs/react-redux/blob/5d792a283554cff3d2f54fad1be1f79cbcab33fe/src/utils/shallowEqual.js\n\nfunction is(first, second) {\n if (first === second) {\n return first !== 0 || second !== 0 || 1 / first === 1 / second;\n } // eslint-disable-next-line no-self-compare\n\n\n return first !== first && second !== second;\n}\n\nfunction shallowEqual(objA, objB) {\n if (is(objA, objB)) return true;\n\n if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {\n return false;\n }\n\n var keysA = Object.keys(objA);\n var keysB = Object.keys(objB);\n if (keysA.length !== keysB.length) return false;\n\n for (var index = 0; index < keysA.length; index++) {\n if (!hasOwn(keysA[index], objB) || !is(objA[keysA[index]], objB[keysA[index]])) {\n return false;\n }\n }\n\n return true;\n}\n\nvar shortenLongText = function shortenLongText(limit, text) {\n if (text.length <= limit) {\n return text;\n }\n\n var words = text.split(' ');\n var sentence = [];\n var totalLength = 0;\n\n for (var _iterator = _createForOfIteratorHelperLoose(words), _step; !(_step = _iterator()).done;) {\n var word = _step.value;\n\n if (totalLength + word.length > limit) {\n break;\n }\n\n totalLength += word.length + 1;\n sentence.push(word);\n }\n\n return sentence.join(' ') + \"...\";\n};\n\nfunction sign(value) {\n if (typeof value !== 'number' || isNaN(value)) {\n return NaN;\n }\n\n if (value === 0) {\n return 0;\n } // eslint-disable-next-line no-compare-neg-zero\n\n\n if (value === -0) {\n return -0;\n }\n\n return value > 0 ? 1 : -1;\n}\n\nfunction shuffle(arr) {\n var copy = arr.slice();\n var lastIndex = arr.length - 1;\n\n for (var i = 0; i < arr.length; i++) {\n var randomIndex = randomInt(i, lastIndex);\n var randomValue = copy[randomIndex];\n copy[randomIndex] = copy[i];\n copy[i] = randomValue;\n }\n\n return copy;\n}\n\nfunction sliceDiff(slice, obj) {\n var picked = pickByIndexed(function (value, key) {\n return value !== obj[key];\n }, slice);\n return isEmpty(picked) ? null : picked;\n}\n\n// TODO: this could be written a lot better\nfunction snakeCase(str) {\n var snakeCased = str.replace(/[A-Z]|([-_ ]+)/g, function (match) {\n var code = match.charCodeAt(0);\n var upperCased = code > 64 && code < 91;\n return upperCased ? \"_\" + match.toLowerCase() : '_';\n });\n return snakeCased[0] === '_' ? snakeCased.substr(1) : snakeCased;\n}\n\nfunction someAreTruthy(arr) {\n return arr.some(identity);\n}\n\nfunction splitAt(splitPoint, arrOrStr) {\n return [arrOrStr.slice(0, splitPoint), arrOrStr.slice(splitPoint, arrOrStr.length)];\n}\n\nfunction splitRightWhenAccum(fn, acc, arr) {\n var result = false;\n\n for (var index = arr.length; index > 0; index--) {\n\n var _fn = fn(arr[index - 1], acc);\n\n result = _fn[0];\n acc = _fn[1];\n\n if (result) {\n return splitAt(index - 1, arr);\n }\n }\n\n return [[], arr];\n}\n\nfunction spread(fn) {\n return function (args) {\n return fn.apply(void 0, args);\n };\n}\n\nfunction sum(numbers) {\n return numbers.reduce(add, 0);\n}\n\nfunction take(count, arr) {\n return arr.slice(0, count);\n}\n\nfunction takeRightWhileFrom(predicate, startIndex, arr) {\n var endIndex = findLastIndexFrom(function (element) {\n return !predicate(element);\n }, startIndex, arr);\n return endIndex === startIndex ? [] : arr.slice(endIndex + 1, startIndex + 1);\n}\n\nfunction takeRightWhile(predicate, arr) {\n return takeRightWhileFrom(predicate, arr.length - 1, arr);\n}\n\nfunction throttle(ms, fn) {\n var lastCall = Date.now() - 2 * ms;\n var trailingId;\n\n var invoke = function invoke() {\n lastCall = Date.now();\n fn.apply(void 0, arguments);\n };\n\n return function () {\n var now = Date.now();\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (now - lastCall >= ms) {\n invoke.apply(void 0, args);\n return;\n }\n\n clearTimeout(trailingId);\n trailingId = setTimeout.apply(void 0, [invoke, lastCall - now + ms].concat(args));\n };\n}\n\nfunction toArray(arrayLike) {\n return Array.prototype.slice.call(arrayLike);\n}\n\nvar toFixedNumber = function toFixedNumber(num, digits) {\n return Number(num.toFixed(digits));\n};\n\nvar toPairs = function toPairs(obj) {\n return Object.keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n};\n\nfunction trailingThrottle(ms, fn) {\n var lastCall = Date.now() - 2 * ms;\n var trailingId;\n\n var invoke = function invoke() {\n lastCall = Date.now();\n return fn.apply(void 0, arguments);\n };\n\n return function () {\n var now = Date.now();\n\n if (now - lastCall >= ms) {\n lastCall = Date.now();\n }\n\n clearTimeout(trailingId);\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n trailingId = setTimeout.apply(void 0, [invoke, lastCall - now + ms].concat(args));\n };\n}\n\nfunction leadingThrottle(ms, fn) {\n var lastCall = 0;\n return function () {\n var now = Date.now();\n\n if (now - lastCall >= ms) {\n lastCall = Date.now();\n fn.apply(void 0, arguments);\n }\n };\n}\n\nvar stringCompare = function stringCompare(strA, strB) {\n if (strA === strB) {\n return 0;\n }\n\n return strA < strB ? -1 : 1;\n};\n\nvar leadingWhiteSpace = /^\\s+/;\nfunction trimStart(str) {\n return str.replace(leadingWhiteSpace, '');\n}\n\nvar trailingWhiteSpace = /\\s+$/;\nfunction trimEnd(str) {\n return str.replace(trailingWhiteSpace, '');\n}\n\nfunction repeat(count, text) {\n return Array(count + 1).join(text);\n}\n\nfunction uniqBy(iteratee, arr) {\n // with polyfills this could be just: return Array.from(new Set(arr.map(iteratee)))\n var seen = [];\n return arr.filter(function (element) {\n var key = iteratee(element);\n\n if (seen.indexOf(key) === -1) {\n seen.push(key);\n return true;\n }\n\n return false;\n });\n}\n\nfunction uniq(arr) {\n return uniqBy(identity, arr);\n}\n\nfunction update(index, newElement, arr) {\n return [].concat(arr.slice(0, index), [newElement], arr.slice(index + 1, arr.length));\n}\n\nfunction without(removed, arr) {\n return arr.filter(function (element) {\n return removed.indexOf(element) === -1;\n });\n}\n\nfunction zipWith(zipper, arrayA, arrayB) {\n return arrayA.map(function (elementA, index) {\n return zipper(elementA, arrayB[index]);\n });\n}\n\nfunction zip(arrayA, arrayB) {\n return zipWith(pair, arrayA, arrayB);\n}\n\nexport { add, assign, camelCase, capitalizeFirstLetter, chain, chunk, cloneDeep, compact, compose, debounce, mapKeys as deepMapKeys, deepMerge, defaultTo, drop, dropRight, ensureArray, entries, filledArray, find, findIndex, findKey, findLast, findLastIndex, findLastIndexFrom, flatMap, flatten, forOwn, fromPairs, generateRandomId, generateUniqueId, get, getOr, groupBy, groupKeys, hasOwn, identity, includes, isArray, isEmpty, isFalsy, isNil, isObject, isPromise, isTruthy, keyBy, keys, last, leadingThrottle, mapKeys$1 as mapKeys, mapValues, mapValuesIndexed, memoize, memoizeOne, memoizeWith, merge, mergeAll, noop, numericSortBy, omit, omitBy, omitByIndexed, once, over, overArgs, pair, partitionObject, pick, pickBy, pickByIndexed, pickOwn, randomInt, range, reject, removeAt, repeat, set, shallowEqual, shortenLongText, shuffle, sign, sliceDiff, snakeCase, someAreTruthy, splitAt, splitRightWhenAccum, spread, stringCompare, sum, take, takeLast, takeRightWhile, takeRightWhileFrom, throttle, toArray, toFixedNumber, toPairs, trailingThrottle, trimEnd, trimStart, uniq, uniqBy, update, values, without, zip, zipWith };\n","import { createElement, useContext, useRef, Fragment } from 'react';\nimport '@emotion/cache';\nimport { h as hasOwnProperty, E as Emotion, c as createEmotionProps, w as withEmotionCache, T as ThemeContext } from './emotion-element-6a883da9.browser.esm.js';\nexport { C as CacheProvider, T as ThemeContext, a as ThemeProvider, _ as __unsafe_useEmotionCache, u as useTheme, w as withEmotionCache, b as withTheme } from './emotion-element-6a883da9.browser.esm.js';\nimport '@babel/runtime/helpers/extends';\nimport '@emotion/weak-memoize';\nimport 'hoist-non-react-statics';\nimport '../_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js';\nimport { insertStyles, registerStyles, getRegisteredStyles } from '@emotion/utils';\nimport { serializeStyles } from '@emotion/serialize';\nimport { useInsertionEffectWithLayoutFallback, useInsertionEffectAlwaysWithSyncFallback } from '@emotion/use-insertion-effect-with-fallbacks';\n\nvar pkg = {\n\tname: \"@emotion/react\",\n\tversion: \"11.10.4\",\n\tmain: \"dist/emotion-react.cjs.js\",\n\tmodule: \"dist/emotion-react.esm.js\",\n\tbrowser: {\n\t\t\"./dist/emotion-react.esm.js\": \"./dist/emotion-react.browser.esm.js\"\n\t},\n\texports: {\n\t\t\".\": {\n\t\t\tmodule: {\n\t\t\t\tworker: \"./dist/emotion-react.worker.esm.js\",\n\t\t\t\tbrowser: \"./dist/emotion-react.browser.esm.js\",\n\t\t\t\t\"default\": \"./dist/emotion-react.esm.js\"\n\t\t\t},\n\t\t\t\"default\": \"./dist/emotion-react.cjs.js\"\n\t\t},\n\t\t\"./jsx-runtime\": {\n\t\t\tmodule: {\n\t\t\t\tworker: \"./jsx-runtime/dist/emotion-react-jsx-runtime.worker.esm.js\",\n\t\t\t\tbrowser: \"./jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js\",\n\t\t\t\t\"default\": \"./jsx-runtime/dist/emotion-react-jsx-runtime.esm.js\"\n\t\t\t},\n\t\t\t\"default\": \"./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.js\"\n\t\t},\n\t\t\"./_isolated-hnrs\": {\n\t\t\tmodule: {\n\t\t\t\tworker: \"./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.worker.esm.js\",\n\t\t\t\tbrowser: \"./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js\",\n\t\t\t\t\"default\": \"./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.esm.js\"\n\t\t\t},\n\t\t\t\"default\": \"./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.js\"\n\t\t},\n\t\t\"./jsx-dev-runtime\": {\n\t\t\tmodule: {\n\t\t\t\tworker: \"./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.worker.esm.js\",\n\t\t\t\tbrowser: \"./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js\",\n\t\t\t\t\"default\": \"./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.esm.js\"\n\t\t\t},\n\t\t\t\"default\": \"./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.js\"\n\t\t},\n\t\t\"./package.json\": \"./package.json\",\n\t\t\"./types/css-prop\": \"./types/css-prop.d.ts\",\n\t\t\"./macro\": \"./macro.js\"\n\t},\n\ttypes: \"types/index.d.ts\",\n\tfiles: [\n\t\t\"src\",\n\t\t\"dist\",\n\t\t\"jsx-runtime\",\n\t\t\"jsx-dev-runtime\",\n\t\t\"_isolated-hnrs\",\n\t\t\"types/*.d.ts\",\n\t\t\"macro.js\",\n\t\t\"macro.d.ts\",\n\t\t\"macro.js.flow\"\n\t],\n\tsideEffects: false,\n\tauthor: \"Emotion Contributors\",\n\tlicense: \"MIT\",\n\tscripts: {\n\t\t\"test:typescript\": \"dtslint types\"\n\t},\n\tdependencies: {\n\t\t\"@babel/runtime\": \"^7.18.3\",\n\t\t\"@emotion/babel-plugin\": \"^11.10.0\",\n\t\t\"@emotion/cache\": \"^11.10.0\",\n\t\t\"@emotion/serialize\": \"^1.1.0\",\n\t\t\"@emotion/use-insertion-effect-with-fallbacks\": \"^1.0.0\",\n\t\t\"@emotion/utils\": \"^1.2.0\",\n\t\t\"@emotion/weak-memoize\": \"^0.3.0\",\n\t\t\"hoist-non-react-statics\": \"^3.3.1\"\n\t},\n\tpeerDependencies: {\n\t\t\"@babel/core\": \"^7.0.0\",\n\t\treact: \">=16.8.0\"\n\t},\n\tpeerDependenciesMeta: {\n\t\t\"@babel/core\": {\n\t\t\toptional: true\n\t\t},\n\t\t\"@types/react\": {\n\t\t\toptional: true\n\t\t}\n\t},\n\tdevDependencies: {\n\t\t\"@babel/core\": \"^7.18.5\",\n\t\t\"@definitelytyped/dtslint\": \"0.0.112\",\n\t\t\"@emotion/css\": \"11.10.0\",\n\t\t\"@emotion/css-prettifier\": \"1.1.0\",\n\t\t\"@emotion/server\": \"11.10.0\",\n\t\t\"@emotion/styled\": \"11.10.4\",\n\t\t\"html-tag-names\": \"^1.1.2\",\n\t\treact: \"16.14.0\",\n\t\t\"svg-tag-names\": \"^1.1.1\",\n\t\ttypescript: \"^4.5.5\"\n\t},\n\trepository: \"https://github.com/emotion-js/emotion/tree/main/packages/react\",\n\tpublishConfig: {\n\t\taccess: \"public\"\n\t},\n\t\"umd:main\": \"dist/emotion-react.umd.min.js\",\n\tpreconstruct: {\n\t\tentrypoints: [\n\t\t\t\"./index.js\",\n\t\t\t\"./jsx-runtime.js\",\n\t\t\t\"./jsx-dev-runtime.js\",\n\t\t\t\"./_isolated-hnrs.js\"\n\t\t],\n\t\tumdName: \"emotionReact\",\n\t\texports: {\n\t\t\tenvConditions: [\n\t\t\t\t\"browser\",\n\t\t\t\t\"worker\"\n\t\t\t],\n\t\t\textra: {\n\t\t\t\t\"./types/css-prop\": \"./types/css-prop.d.ts\",\n\t\t\t\t\"./macro\": \"./macro.js\"\n\t\t\t}\n\t\t}\n\t}\n};\n\nvar jsx = function jsx(type, props) {\n var args = arguments;\n\n if (props == null || !hasOwnProperty.call(props, 'css')) {\n // $FlowFixMe\n return createElement.apply(undefined, args);\n }\n\n var argsLength = args.length;\n var createElementArgArray = new Array(argsLength);\n createElementArgArray[0] = Emotion;\n createElementArgArray[1] = createEmotionProps(type, props);\n\n for (var i = 2; i < argsLength; i++) {\n createElementArgArray[i] = args[i];\n } // $FlowFixMe\n\n\n return createElement.apply(null, createElementArgArray);\n};\n\nvar warnedAboutCssPropForGlobal = false; // maintain place over rerenders.\n// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild\n// initial client-side render from SSR, use place of hydrating tag\n\nvar Global = /* #__PURE__ */withEmotionCache(function (props, cache) {\n if (process.env.NODE_ENV !== 'production' && !warnedAboutCssPropForGlobal && ( // check for className as well since the user is\n // probably using the custom createElement which\n // means it will be turned into a className prop\n // $FlowFixMe I don't really want to add it to the type since it shouldn't be used\n props.className || props.css)) {\n console.error(\"It looks like you're using the css prop on Global, did you mean to use the styles prop instead?\");\n warnedAboutCssPropForGlobal = true;\n }\n\n var styles = props.styles;\n var serialized = serializeStyles([styles], undefined, useContext(ThemeContext));\n // but it is based on a constant that will never change at runtime\n // it's effectively like having two implementations and switching them out\n // so it's not actually breaking anything\n\n\n var sheetRef = useRef();\n useInsertionEffectWithLayoutFallback(function () {\n var key = cache.key + \"-global\"; // use case of https://github.com/emotion-js/emotion/issues/2675\n\n var sheet = new cache.sheet.constructor({\n key: key,\n nonce: cache.sheet.nonce,\n container: cache.sheet.container,\n speedy: cache.sheet.isSpeedy\n });\n var rehydrating = false; // $FlowFixMe\n\n var node = document.querySelector(\"style[data-emotion=\\\"\" + key + \" \" + serialized.name + \"\\\"]\");\n\n if (cache.sheet.tags.length) {\n sheet.before = cache.sheet.tags[0];\n }\n\n if (node !== null) {\n rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other s\n\n node.setAttribute('data-emotion', key);\n sheet.hydrate([node]);\n }\n\n sheetRef.current = [sheet, rehydrating];\n return function () {\n sheet.flush();\n };\n }, [cache]);\n useInsertionEffectWithLayoutFallback(function () {\n var sheetRefCurrent = sheetRef.current;\n var sheet = sheetRefCurrent[0],\n rehydrating = sheetRefCurrent[1];\n\n if (rehydrating) {\n sheetRefCurrent[1] = false;\n return;\n }\n\n if (serialized.next !== undefined) {\n // insert keyframes\n insertStyles(cache, serialized.next, true);\n }\n\n if (sheet.tags.length) {\n // if this doesn't exist then it will be null so the style element will be appended\n var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;\n sheet.before = element;\n sheet.flush();\n }\n\n cache.insert(\"\", serialized, sheet, false);\n }, [cache, serialized.name]);\n return null;\n});\n\nif (process.env.NODE_ENV !== 'production') {\n Global.displayName = 'EmotionGlobal';\n}\n\nfunction css() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return serializeStyles(args);\n}\n\nvar keyframes = function keyframes() {\n var insertable = css.apply(void 0, arguments);\n var name = \"animation-\" + insertable.name; // $FlowFixMe\n\n return {\n name: name,\n styles: \"@keyframes \" + name + \"{\" + insertable.styles + \"}\",\n anim: 1,\n toString: function toString() {\n return \"_EMO_\" + this.name + \"_\" + this.styles + \"_EMO_\";\n }\n };\n};\n\nvar classnames = function classnames(args) {\n var len = args.length;\n var i = 0;\n var cls = '';\n\n for (; i < len; i++) {\n var arg = args[i];\n if (arg == null) continue;\n var toAdd = void 0;\n\n switch (typeof arg) {\n case 'boolean':\n break;\n\n case 'object':\n {\n if (Array.isArray(arg)) {\n toAdd = classnames(arg);\n } else {\n if (process.env.NODE_ENV !== 'production' && arg.styles !== undefined && arg.name !== undefined) {\n console.error('You have passed styles created with `css` from `@emotion/react` package to the `cx`.\\n' + '`cx` is meant to compose class names (strings) so you should convert those styles to a class name by passing them to the `css` received from component.');\n }\n\n toAdd = '';\n\n for (var k in arg) {\n if (arg[k] && k) {\n toAdd && (toAdd += ' ');\n toAdd += k;\n }\n }\n }\n\n break;\n }\n\n default:\n {\n toAdd = arg;\n }\n }\n\n if (toAdd) {\n cls && (cls += ' ');\n cls += toAdd;\n }\n }\n\n return cls;\n};\n\nfunction merge(registered, css, className) {\n var registeredStyles = [];\n var rawClassName = getRegisteredStyles(registered, registeredStyles, className);\n\n if (registeredStyles.length < 2) {\n return className;\n }\n\n return rawClassName + css(registeredStyles);\n}\n\nvar Insertion = function Insertion(_ref) {\n var cache = _ref.cache,\n serializedArr = _ref.serializedArr;\n var rules = useInsertionEffectAlwaysWithSyncFallback(function () {\n\n for (var i = 0; i < serializedArr.length; i++) {\n var res = insertStyles(cache, serializedArr[i], false);\n }\n });\n\n return null;\n};\n\nvar ClassNames = /* #__PURE__ */withEmotionCache(function (props, cache) {\n var hasRendered = false;\n var serializedArr = [];\n\n var css = function css() {\n if (hasRendered && process.env.NODE_ENV !== 'production') {\n throw new Error('css can only be used during render');\n }\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var serialized = serializeStyles(args, cache.registered);\n serializedArr.push(serialized); // registration has to happen here as the result of this might get consumed by `cx`\n\n registerStyles(cache, serialized, false);\n return cache.key + \"-\" + serialized.name;\n };\n\n var cx = function cx() {\n if (hasRendered && process.env.NODE_ENV !== 'production') {\n throw new Error('cx can only be used during render');\n }\n\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return merge(cache.registered, css, classnames(args));\n };\n\n var content = {\n css: css,\n cx: cx,\n theme: useContext(ThemeContext)\n };\n var ele = props.children(content);\n hasRendered = true;\n return /*#__PURE__*/createElement(Fragment, null, /*#__PURE__*/createElement(Insertion, {\n cache: cache,\n serializedArr: serializedArr\n }), ele);\n});\n\nif (process.env.NODE_ENV !== 'production') {\n ClassNames.displayName = 'EmotionClassNames';\n}\n\nif (process.env.NODE_ENV !== 'production') {\n var isBrowser = \"object\" !== 'undefined'; // #1727 for some reason Jest evaluates modules twice if some consuming module gets mocked with jest.mock\n\n var isJest = typeof jest !== 'undefined';\n\n if (isBrowser && !isJest) {\n // globalThis has wide browser support - https://caniuse.com/?search=globalThis, Node.js 12 and later\n var globalContext = // $FlowIgnore\n typeof globalThis !== 'undefined' ? globalThis // eslint-disable-line no-undef\n : isBrowser ? window : global;\n var globalKey = \"__EMOTION_REACT_\" + pkg.version.split('.')[0] + \"__\";\n\n if (globalContext[globalKey]) {\n console.warn('You are loading @emotion/react when it is already loaded. Running ' + 'multiple instances may cause problems. This can happen if multiple ' + 'versions are used, or if multiple builds of the same version are ' + 'used.');\n }\n\n globalContext[globalKey] = true;\n }\n}\n\nexport { ClassNames, Global, jsx as createElement, css, jsx, keyframes };\n","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","export default {\n disabled: false\n};","import React from 'react';\nexport default React.createContext(null);","export var forceReflow = function forceReflow(node) {\n return node.scrollTop;\n};","import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport config from './config';\nimport { timeoutsShape } from './utils/PropTypes';\nimport TransitionGroupContext from './TransitionGroupContext';\nimport { forceReflow } from './utils/reflow';\nexport var UNMOUNTED = 'unmounted';\nexport var EXITED = 'exited';\nexport var ENTERING = 'entering';\nexport var ENTERED = 'entered';\nexport var EXITING = 'exiting';\n/**\n * The Transition component lets you describe a transition from one component\n * state to another _over time_ with a simple declarative API. Most commonly\n * it's used to animate the mounting and unmounting of a component, but can also\n * be used to describe in-place transition states as well.\n *\n * ---\n *\n * **Note**: `Transition` is a platform-agnostic base component. If you're using\n * transitions in CSS, you'll probably want to use\n * [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)\n * instead. It inherits all the features of `Transition`, but contains\n * additional features necessary to play nice with CSS transitions (hence the\n * name of the component).\n *\n * ---\n *\n * By default the `Transition` component does not alter the behavior of the\n * component it renders, it only tracks \"enter\" and \"exit\" states for the\n * components. It's up to you to give meaning and effect to those states. For\n * example we can add styles to a component when it enters or exits:\n *\n * ```jsx\n * import { Transition } from 'react-transition-group';\n *\n * const duration = 300;\n *\n * const defaultStyle = {\n * transition: `opacity ${duration}ms ease-in-out`,\n * opacity: 0,\n * }\n *\n * const transitionStyles = {\n * entering: { opacity: 1 },\n * entered: { opacity: 1 },\n * exiting: { opacity: 0 },\n * exited: { opacity: 0 },\n * };\n *\n * const Fade = ({ in: inProp }) => (\n * \n * {state => (\n *
    \n * I'm a fade Transition!\n *
    \n * )}\n *
    \n * );\n * ```\n *\n * There are 4 main states a Transition can be in:\n * - `'entering'`\n * - `'entered'`\n * - `'exiting'`\n * - `'exited'`\n *\n * Transition state is toggled via the `in` prop. When `true` the component\n * begins the \"Enter\" stage. During this stage, the component will shift from\n * its current transition state, to `'entering'` for the duration of the\n * transition and then to the `'entered'` stage once it's complete. Let's take\n * the following example (we'll use the\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):\n *\n * ```jsx\n * function App() {\n * const [inProp, setInProp] = useState(false);\n * return (\n *
    \n * \n * {state => (\n * // ...\n * )}\n * \n * \n *
    \n * );\n * }\n * ```\n *\n * When the button is clicked the component will shift to the `'entering'` state\n * and stay there for 500ms (the value of `timeout`) before it finally switches\n * to `'entered'`.\n *\n * When `in` is `false` the same thing happens except the state moves from\n * `'exiting'` to `'exited'`.\n */\n\nvar Transition = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Transition, _React$Component);\n\n function Transition(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n var parentGroup = context; // In the context of a TransitionGroup all enters are really appears\n\n var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;\n var initialStatus;\n _this.appearStatus = null;\n\n if (props.in) {\n if (appear) {\n initialStatus = EXITED;\n _this.appearStatus = ENTERING;\n } else {\n initialStatus = ENTERED;\n }\n } else {\n if (props.unmountOnExit || props.mountOnEnter) {\n initialStatus = UNMOUNTED;\n } else {\n initialStatus = EXITED;\n }\n }\n\n _this.state = {\n status: initialStatus\n };\n _this.nextCallback = null;\n return _this;\n }\n\n Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {\n var nextIn = _ref.in;\n\n if (nextIn && prevState.status === UNMOUNTED) {\n return {\n status: EXITED\n };\n }\n\n return null;\n } // getSnapshotBeforeUpdate(prevProps) {\n // let nextStatus = null\n // if (prevProps !== this.props) {\n // const { status } = this.state\n // if (this.props.in) {\n // if (status !== ENTERING && status !== ENTERED) {\n // nextStatus = ENTERING\n // }\n // } else {\n // if (status === ENTERING || status === ENTERED) {\n // nextStatus = EXITING\n // }\n // }\n // }\n // return { nextStatus }\n // }\n ;\n\n var _proto = Transition.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.updateStatus(true, this.appearStatus);\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps) {\n var nextStatus = null;\n\n if (prevProps !== this.props) {\n var status = this.state.status;\n\n if (this.props.in) {\n if (status !== ENTERING && status !== ENTERED) {\n nextStatus = ENTERING;\n }\n } else {\n if (status === ENTERING || status === ENTERED) {\n nextStatus = EXITING;\n }\n }\n }\n\n this.updateStatus(false, nextStatus);\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.cancelNextCallback();\n };\n\n _proto.getTimeouts = function getTimeouts() {\n var timeout = this.props.timeout;\n var exit, enter, appear;\n exit = enter = appear = timeout;\n\n if (timeout != null && typeof timeout !== 'number') {\n exit = timeout.exit;\n enter = timeout.enter; // TODO: remove fallback for next major\n\n appear = timeout.appear !== undefined ? timeout.appear : enter;\n }\n\n return {\n exit: exit,\n enter: enter,\n appear: appear\n };\n };\n\n _proto.updateStatus = function updateStatus(mounting, nextStatus) {\n if (mounting === void 0) {\n mounting = false;\n }\n\n if (nextStatus !== null) {\n // nextStatus will always be ENTERING or EXITING.\n this.cancelNextCallback();\n\n if (nextStatus === ENTERING) {\n if (this.props.unmountOnExit || this.props.mountOnEnter) {\n var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this); // https://github.com/reactjs/react-transition-group/pull/749\n // With unmountOnExit or mountOnEnter, the enter animation should happen at the transition between `exited` and `entering`.\n // To make the animation happen, we have to separate each rendering and avoid being processed as batched.\n\n if (node) forceReflow(node);\n }\n\n this.performEnter(mounting);\n } else {\n this.performExit();\n }\n } else if (this.props.unmountOnExit && this.state.status === EXITED) {\n this.setState({\n status: UNMOUNTED\n });\n }\n };\n\n _proto.performEnter = function performEnter(mounting) {\n var _this2 = this;\n\n var enter = this.props.enter;\n var appearing = this.context ? this.context.isMounting : mounting;\n\n var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],\n maybeNode = _ref2[0],\n maybeAppearing = _ref2[1];\n\n var timeouts = this.getTimeouts();\n var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED\n // if we are mounting and running this it means appear _must_ be set\n\n if (!mounting && !enter || config.disabled) {\n this.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode);\n });\n return;\n }\n\n this.props.onEnter(maybeNode, maybeAppearing);\n this.safeSetState({\n status: ENTERING\n }, function () {\n _this2.props.onEntering(maybeNode, maybeAppearing);\n\n _this2.onTransitionEnd(enterTimeout, function () {\n _this2.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode, maybeAppearing);\n });\n });\n });\n };\n\n _proto.performExit = function performExit() {\n var _this3 = this;\n\n var exit = this.props.exit;\n var timeouts = this.getTimeouts();\n var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED\n\n if (!exit || config.disabled) {\n this.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n return;\n }\n\n this.props.onExit(maybeNode);\n this.safeSetState({\n status: EXITING\n }, function () {\n _this3.props.onExiting(maybeNode);\n\n _this3.onTransitionEnd(timeouts.exit, function () {\n _this3.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n });\n });\n };\n\n _proto.cancelNextCallback = function cancelNextCallback() {\n if (this.nextCallback !== null) {\n this.nextCallback.cancel();\n this.nextCallback = null;\n }\n };\n\n _proto.safeSetState = function safeSetState(nextState, callback) {\n // This shouldn't be necessary, but there are weird race conditions with\n // setState callbacks and unmounting in testing, so always make sure that\n // we can cancel any pending setState callbacks after we unmount.\n callback = this.setNextCallback(callback);\n this.setState(nextState, callback);\n };\n\n _proto.setNextCallback = function setNextCallback(callback) {\n var _this4 = this;\n\n var active = true;\n\n this.nextCallback = function (event) {\n if (active) {\n active = false;\n _this4.nextCallback = null;\n callback(event);\n }\n };\n\n this.nextCallback.cancel = function () {\n active = false;\n };\n\n return this.nextCallback;\n };\n\n _proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {\n this.setNextCallback(handler);\n var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);\n var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;\n\n if (!node || doesNotHaveTimeoutOrListener) {\n setTimeout(this.nextCallback, 0);\n return;\n }\n\n if (this.props.addEndListener) {\n var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],\n maybeNode = _ref3[0],\n maybeNextCallback = _ref3[1];\n\n this.props.addEndListener(maybeNode, maybeNextCallback);\n }\n\n if (timeout != null) {\n setTimeout(this.nextCallback, timeout);\n }\n };\n\n _proto.render = function render() {\n var status = this.state.status;\n\n if (status === UNMOUNTED) {\n return null;\n }\n\n var _this$props = this.props,\n children = _this$props.children,\n _in = _this$props.in,\n _mountOnEnter = _this$props.mountOnEnter,\n _unmountOnExit = _this$props.unmountOnExit,\n _appear = _this$props.appear,\n _enter = _this$props.enter,\n _exit = _this$props.exit,\n _timeout = _this$props.timeout,\n _addEndListener = _this$props.addEndListener,\n _onEnter = _this$props.onEnter,\n _onEntering = _this$props.onEntering,\n _onEntered = _this$props.onEntered,\n _onExit = _this$props.onExit,\n _onExiting = _this$props.onExiting,\n _onExited = _this$props.onExited,\n _nodeRef = _this$props.nodeRef,\n childProps = _objectWithoutPropertiesLoose(_this$props, [\"children\", \"in\", \"mountOnEnter\", \"unmountOnExit\", \"appear\", \"enter\", \"exit\", \"timeout\", \"addEndListener\", \"onEnter\", \"onEntering\", \"onEntered\", \"onExit\", \"onExiting\", \"onExited\", \"nodeRef\"]);\n\n return (\n /*#__PURE__*/\n // allows for nested Transitions\n React.createElement(TransitionGroupContext.Provider, {\n value: null\n }, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))\n );\n };\n\n return Transition;\n}(React.Component);\n\nTransition.contextType = TransitionGroupContext;\nTransition.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * A React reference to DOM element that need to transition:\n * https://stackoverflow.com/a/51127130/4671932\n *\n * - When `nodeRef` prop is used, `node` is not passed to callback functions\n * (e.g. `onEnter`) because user already has direct access to the node.\n * - When changing `key` prop of `Transition` in a `TransitionGroup` a new\n * `nodeRef` need to be provided to `Transition` with changed `key` prop\n * (see\n * [test/CSSTransition-test.js](https://github.com/reactjs/react-transition-group/blob/13435f897b3ab71f6e19d724f145596f5910581c/test/CSSTransition-test.js#L362-L437)).\n */\n nodeRef: PropTypes.shape({\n current: typeof Element === 'undefined' ? PropTypes.any : function (propValue, key, componentName, location, propFullName, secret) {\n var value = propValue[key];\n return PropTypes.instanceOf(value && 'ownerDocument' in value ? value.ownerDocument.defaultView.Element : Element)(propValue, key, componentName, location, propFullName, secret);\n }\n }),\n\n /**\n * A `function` child can be used instead of a React element. This function is\n * called with the current transition status (`'entering'`, `'entered'`,\n * `'exiting'`, `'exited'`), which can be used to apply context\n * specific props to a component.\n *\n * ```jsx\n * \n * {state => (\n * \n * )}\n * \n * ```\n */\n children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,\n\n /**\n * Show the component; triggers the enter or exit states\n */\n in: PropTypes.bool,\n\n /**\n * By default the child component is mounted immediately along with\n * the parent `Transition` component. If you want to \"lazy mount\" the component on the\n * first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay\n * mounted, even on \"exited\", unless you also specify `unmountOnExit`.\n */\n mountOnEnter: PropTypes.bool,\n\n /**\n * By default the child component stays mounted after it reaches the `'exited'` state.\n * Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.\n */\n unmountOnExit: PropTypes.bool,\n\n /**\n * By default the child component does not perform the enter transition when\n * it first mounts, regardless of the value of `in`. If you want this\n * behavior, set both `appear` and `in` to `true`.\n *\n * > **Note**: there are no special appear states like `appearing`/`appeared`, this prop\n * > only adds an additional enter transition. However, in the\n * > `` component that first enter transition does result in\n * > additional `.appear-*` classes, that way you can choose to style it\n * > differently.\n */\n appear: PropTypes.bool,\n\n /**\n * Enable or disable enter transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * Enable or disable exit transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * The duration of the transition, in milliseconds.\n * Required unless `addEndListener` is provided.\n *\n * You may specify a single timeout for all transitions:\n *\n * ```jsx\n * timeout={500}\n * ```\n *\n * or individually:\n *\n * ```jsx\n * timeout={{\n * appear: 500,\n * enter: 300,\n * exit: 500,\n * }}\n * ```\n *\n * - `appear` defaults to the value of `enter`\n * - `enter` defaults to `0`\n * - `exit` defaults to `0`\n *\n * @type {number | { enter?: number, exit?: number, appear?: number }}\n */\n timeout: function timeout(props) {\n var pt = timeoutsShape;\n if (!props.addEndListener) pt = pt.isRequired;\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return pt.apply(void 0, [props].concat(args));\n },\n\n /**\n * Add a custom transition end trigger. Called with the transitioning\n * DOM node and a `done` callback. Allows for more fine grained transition end\n * logic. Timeouts are still used as a fallback if provided.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * ```jsx\n * addEndListener={(node, done) => {\n * // use the css transitionend event to mark the finish of a transition\n * node.addEventListener('transitionend', done, false);\n * }}\n * ```\n */\n addEndListener: PropTypes.func,\n\n /**\n * Callback fired before the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEnter: PropTypes.func,\n\n /**\n * Callback fired after the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * Callback fired after the \"entered\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEntered: PropTypes.func,\n\n /**\n * Callback fired before the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExit: PropTypes.func,\n\n /**\n * Callback fired after the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExiting: PropTypes.func,\n\n /**\n * Callback fired after the \"exited\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExited: PropTypes.func\n} : {}; // Name the function so it is clearer in the documentation\n\nfunction noop() {}\n\nTransition.defaultProps = {\n in: false,\n mountOnEnter: false,\n unmountOnExit: false,\n appear: false,\n enter: true,\n exit: true,\n onEnter: noop,\n onEntering: noop,\n onEntered: noop,\n onExit: noop,\n onExiting: noop,\n onExited: noop\n};\nTransition.UNMOUNTED = UNMOUNTED;\nTransition.EXITED = EXITED;\nTransition.ENTERING = ENTERING;\nTransition.ENTERED = ENTERED;\nTransition.EXITING = EXITING;\nexport default Transition;","function replaceClassName(origClass, classToRemove) {\n return origClass.replace(new RegExp(\"(^|\\\\s)\" + classToRemove + \"(?:\\\\s|$)\", 'g'), '$1').replace(/\\s+/g, ' ').replace(/^\\s*|\\s*$/g, '');\n}\n/**\n * Removes a CSS class from a given element.\n * \n * @param element the element\n * @param className the CSS class name\n */\n\n\nexport default function removeClass(element, className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (typeof element.className === 'string') {\n element.className = replaceClassName(element.className, className);\n } else {\n element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n }\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport addOneClass from 'dom-helpers/addClass';\nimport removeOneClass from 'dom-helpers/removeClass';\nimport React from 'react';\nimport Transition from './Transition';\nimport { classNamesShape } from './utils/PropTypes';\nimport { forceReflow } from './utils/reflow';\n\nvar _addClass = function addClass(node, classes) {\n return node && classes && classes.split(' ').forEach(function (c) {\n return addOneClass(node, c);\n });\n};\n\nvar removeClass = function removeClass(node, classes) {\n return node && classes && classes.split(' ').forEach(function (c) {\n return removeOneClass(node, c);\n });\n};\n/**\n * A transition component inspired by the excellent\n * [ng-animate](https://docs.angularjs.org/api/ngAnimate) library, you should\n * use it if you're using CSS transitions or animations. It's built upon the\n * [`Transition`](https://reactcommunity.org/react-transition-group/transition)\n * component, so it inherits all of its props.\n *\n * `CSSTransition` applies a pair of class names during the `appear`, `enter`,\n * and `exit` states of the transition. The first class is applied and then a\n * second `*-active` class in order to activate the CSS transition. After the\n * transition, matching `*-done` class names are applied to persist the\n * transition state.\n *\n * ```jsx\n * function App() {\n * const [inProp, setInProp] = useState(false);\n * return (\n *
    \n * \n *
    \n * {\"I'll receive my-node-* classes\"}\n *
    \n *
    \n * \n *
    \n * );\n * }\n * ```\n *\n * When the `in` prop is set to `true`, the child component will first receive\n * the class `example-enter`, then the `example-enter-active` will be added in\n * the next tick. `CSSTransition` [forces a\n * reflow](https://github.com/reactjs/react-transition-group/blob/5007303e729a74be66a21c3e2205e4916821524b/src/CSSTransition.js#L208-L215)\n * between before adding the `example-enter-active`. This is an important trick\n * because it allows us to transition between `example-enter` and\n * `example-enter-active` even though they were added immediately one after\n * another. Most notably, this is what makes it possible for us to animate\n * _appearance_.\n *\n * ```css\n * .my-node-enter {\n * opacity: 0;\n * }\n * .my-node-enter-active {\n * opacity: 1;\n * transition: opacity 200ms;\n * }\n * .my-node-exit {\n * opacity: 1;\n * }\n * .my-node-exit-active {\n * opacity: 0;\n * transition: opacity 200ms;\n * }\n * ```\n *\n * `*-active` classes represent which styles you want to animate **to**, so it's\n * important to add `transition` declaration only to them, otherwise transitions\n * might not behave as intended! This might not be obvious when the transitions\n * are symmetrical, i.e. when `*-enter-active` is the same as `*-exit`, like in\n * the example above (minus `transition`), but it becomes apparent in more\n * complex transitions.\n *\n * **Note**: If you're using the\n * [`appear`](http://reactcommunity.org/react-transition-group/transition#Transition-prop-appear)\n * prop, make sure to define styles for `.appear-*` classes as well.\n */\n\n\nvar CSSTransition = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(CSSTransition, _React$Component);\n\n function CSSTransition() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n _this.appliedClasses = {\n appear: {},\n enter: {},\n exit: {}\n };\n\n _this.onEnter = function (maybeNode, maybeAppearing) {\n var _this$resolveArgument = _this.resolveArguments(maybeNode, maybeAppearing),\n node = _this$resolveArgument[0],\n appearing = _this$resolveArgument[1];\n\n _this.removeClasses(node, 'exit');\n\n _this.addClass(node, appearing ? 'appear' : 'enter', 'base');\n\n if (_this.props.onEnter) {\n _this.props.onEnter(maybeNode, maybeAppearing);\n }\n };\n\n _this.onEntering = function (maybeNode, maybeAppearing) {\n var _this$resolveArgument2 = _this.resolveArguments(maybeNode, maybeAppearing),\n node = _this$resolveArgument2[0],\n appearing = _this$resolveArgument2[1];\n\n var type = appearing ? 'appear' : 'enter';\n\n _this.addClass(node, type, 'active');\n\n if (_this.props.onEntering) {\n _this.props.onEntering(maybeNode, maybeAppearing);\n }\n };\n\n _this.onEntered = function (maybeNode, maybeAppearing) {\n var _this$resolveArgument3 = _this.resolveArguments(maybeNode, maybeAppearing),\n node = _this$resolveArgument3[0],\n appearing = _this$resolveArgument3[1];\n\n var type = appearing ? 'appear' : 'enter';\n\n _this.removeClasses(node, type);\n\n _this.addClass(node, type, 'done');\n\n if (_this.props.onEntered) {\n _this.props.onEntered(maybeNode, maybeAppearing);\n }\n };\n\n _this.onExit = function (maybeNode) {\n var _this$resolveArgument4 = _this.resolveArguments(maybeNode),\n node = _this$resolveArgument4[0];\n\n _this.removeClasses(node, 'appear');\n\n _this.removeClasses(node, 'enter');\n\n _this.addClass(node, 'exit', 'base');\n\n if (_this.props.onExit) {\n _this.props.onExit(maybeNode);\n }\n };\n\n _this.onExiting = function (maybeNode) {\n var _this$resolveArgument5 = _this.resolveArguments(maybeNode),\n node = _this$resolveArgument5[0];\n\n _this.addClass(node, 'exit', 'active');\n\n if (_this.props.onExiting) {\n _this.props.onExiting(maybeNode);\n }\n };\n\n _this.onExited = function (maybeNode) {\n var _this$resolveArgument6 = _this.resolveArguments(maybeNode),\n node = _this$resolveArgument6[0];\n\n _this.removeClasses(node, 'exit');\n\n _this.addClass(node, 'exit', 'done');\n\n if (_this.props.onExited) {\n _this.props.onExited(maybeNode);\n }\n };\n\n _this.resolveArguments = function (maybeNode, maybeAppearing) {\n return _this.props.nodeRef ? [_this.props.nodeRef.current, maybeNode] // here `maybeNode` is actually `appearing`\n : [maybeNode, maybeAppearing];\n };\n\n _this.getClassNames = function (type) {\n var classNames = _this.props.classNames;\n var isStringClassNames = typeof classNames === 'string';\n var prefix = isStringClassNames && classNames ? classNames + \"-\" : '';\n var baseClassName = isStringClassNames ? \"\" + prefix + type : classNames[type];\n var activeClassName = isStringClassNames ? baseClassName + \"-active\" : classNames[type + \"Active\"];\n var doneClassName = isStringClassNames ? baseClassName + \"-done\" : classNames[type + \"Done\"];\n return {\n baseClassName: baseClassName,\n activeClassName: activeClassName,\n doneClassName: doneClassName\n };\n };\n\n return _this;\n }\n\n var _proto = CSSTransition.prototype;\n\n _proto.addClass = function addClass(node, type, phase) {\n var className = this.getClassNames(type)[phase + \"ClassName\"];\n\n var _this$getClassNames = this.getClassNames('enter'),\n doneClassName = _this$getClassNames.doneClassName;\n\n if (type === 'appear' && phase === 'done' && doneClassName) {\n className += \" \" + doneClassName;\n } // This is to force a repaint,\n // which is necessary in order to transition styles when adding a class name.\n\n\n if (phase === 'active') {\n if (node) forceReflow(node);\n }\n\n if (className) {\n this.appliedClasses[type][phase] = className;\n\n _addClass(node, className);\n }\n };\n\n _proto.removeClasses = function removeClasses(node, type) {\n var _this$appliedClasses$ = this.appliedClasses[type],\n baseClassName = _this$appliedClasses$.base,\n activeClassName = _this$appliedClasses$.active,\n doneClassName = _this$appliedClasses$.done;\n this.appliedClasses[type] = {};\n\n if (baseClassName) {\n removeClass(node, baseClassName);\n }\n\n if (activeClassName) {\n removeClass(node, activeClassName);\n }\n\n if (doneClassName) {\n removeClass(node, doneClassName);\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n _ = _this$props.classNames,\n props = _objectWithoutPropertiesLoose(_this$props, [\"classNames\"]);\n\n return /*#__PURE__*/React.createElement(Transition, _extends({}, props, {\n onEnter: this.onEnter,\n onEntered: this.onEntered,\n onEntering: this.onEntering,\n onExit: this.onExit,\n onExiting: this.onExiting,\n onExited: this.onExited\n }));\n };\n\n return CSSTransition;\n}(React.Component);\n\nCSSTransition.defaultProps = {\n classNames: ''\n};\nCSSTransition.propTypes = process.env.NODE_ENV !== \"production\" ? _extends({}, Transition.propTypes, {\n /**\n * The animation classNames applied to the component as it appears, enters,\n * exits or has finished the transition. A single name can be provided, which\n * will be suffixed for each stage, e.g. `classNames=\"fade\"` applies:\n *\n * - `fade-appear`, `fade-appear-active`, `fade-appear-done`\n * - `fade-enter`, `fade-enter-active`, `fade-enter-done`\n * - `fade-exit`, `fade-exit-active`, `fade-exit-done`\n *\n * A few details to note about how these classes are applied:\n *\n * 1. They are _joined_ with the ones that are already defined on the child\n * component, so if you want to add some base styles, you can use\n * `className` without worrying that it will be overridden.\n *\n * 2. If the transition component mounts with `in={false}`, no classes are\n * applied yet. You might be expecting `*-exit-done`, but if you think\n * about it, a component cannot finish exiting if it hasn't entered yet.\n *\n * 2. `fade-appear-done` and `fade-enter-done` will _both_ be applied. This\n * allows you to define different behavior for when appearing is done and\n * when regular entering is done, using selectors like\n * `.fade-enter-done:not(.fade-appear-done)`. For example, you could apply\n * an epic entrance animation when element first appears in the DOM using\n * [Animate.css](https://daneden.github.io/animate.css/). Otherwise you can\n * simply use `fade-enter-done` for defining both cases.\n *\n * Each individual classNames can also be specified independently like:\n *\n * ```js\n * classNames={{\n * appear: 'my-appear',\n * appearActive: 'my-active-appear',\n * appearDone: 'my-done-appear',\n * enter: 'my-enter',\n * enterActive: 'my-active-enter',\n * enterDone: 'my-done-enter',\n * exit: 'my-exit',\n * exitActive: 'my-active-exit',\n * exitDone: 'my-done-exit',\n * }}\n * ```\n *\n * If you want to set these classes using CSS Modules:\n *\n * ```js\n * import styles from './styles.css';\n * ```\n *\n * you might want to use camelCase in your CSS file, that way could simply\n * spread them instead of listing them one by one:\n *\n * ```js\n * classNames={{ ...styles }}\n * ```\n *\n * @type {string | {\n * appear?: string,\n * appearActive?: string,\n * appearDone?: string,\n * enter?: string,\n * enterActive?: string,\n * enterDone?: string,\n * exit?: string,\n * exitActive?: string,\n * exitDone?: string,\n * }}\n */\n classNames: classNamesShape,\n\n /**\n * A `` callback fired immediately after the 'enter' or 'appear' class is\n * applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEnter: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'enter-active' or\n * 'appear-active' class is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'enter' or\n * 'appear' classes are **removed** and the `done` class is added to the DOM node.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntered: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit' class is\n * applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement)\n */\n onExit: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit-active' is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement)\n */\n onExiting: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit' classes\n * are **removed** and the `exit-done` class is added to the DOM node.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement)\n */\n onExited: PropTypes.func\n}) : {};\nexport default CSSTransition;","import hasClass from './hasClass';\n/**\n * Adds a CSS class to a given element.\n * \n * @param element the element\n * @param className the CSS class name\n */\n\nexport default function addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!hasClass(element, className)) if (typeof element.className === 'string') element.className = element.className + \" \" + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + \" \" + className);\n}","/**\n * Checks if a given element has a CSS class.\n * \n * @param element the element\n * @param className the CSS class name\n */\nexport default function hasClass(element, className) {\n if (element.classList) return !!className && element.classList.contains(className);\n return (\" \" + (element.className.baseVal || element.className) + \" \").indexOf(\" \" + className + \" \") !== -1;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","import { Children, cloneElement, isValidElement } from 'react';\n/**\n * Given `this.props.children`, return an object mapping key to child.\n *\n * @param {*} children `this.props.children`\n * @return {object} Mapping of key to child\n */\n\nexport function getChildMapping(children, mapFn) {\n var mapper = function mapper(child) {\n return mapFn && isValidElement(child) ? mapFn(child) : child;\n };\n\n var result = Object.create(null);\n if (children) Children.map(children, function (c) {\n return c;\n }).forEach(function (child) {\n // run the map function here instead so that the key is the computed one\n result[child.key] = mapper(child);\n });\n return result;\n}\n/**\n * When you're adding or removing children some may be added or removed in the\n * same render pass. We want to show *both* since we want to simultaneously\n * animate elements in and out. This function takes a previous set of keys\n * and a new set of keys and merges them with its best guess of the correct\n * ordering. In the future we may expose some of the utilities in\n * ReactMultiChild to make this easy, but for now React itself does not\n * directly have this concept of the union of prevChildren and nextChildren\n * so we implement it here.\n *\n * @param {object} prev prev children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @param {object} next next children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @return {object} a key set that contains all keys in `prev` and all keys\n * in `next` in a reasonable order.\n */\n\nexport function mergeChildMappings(prev, next) {\n prev = prev || {};\n next = next || {};\n\n function getValueForKey(key) {\n return key in next ? next[key] : prev[key];\n } // For each key of `next`, the list of keys to insert before that key in\n // the combined list\n\n\n var nextKeysPending = Object.create(null);\n var pendingKeys = [];\n\n for (var prevKey in prev) {\n if (prevKey in next) {\n if (pendingKeys.length) {\n nextKeysPending[prevKey] = pendingKeys;\n pendingKeys = [];\n }\n } else {\n pendingKeys.push(prevKey);\n }\n }\n\n var i;\n var childMapping = {};\n\n for (var nextKey in next) {\n if (nextKeysPending[nextKey]) {\n for (i = 0; i < nextKeysPending[nextKey].length; i++) {\n var pendingNextKey = nextKeysPending[nextKey][i];\n childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);\n }\n }\n\n childMapping[nextKey] = getValueForKey(nextKey);\n } // Finally, add the keys which didn't appear before any key in `next`\n\n\n for (i = 0; i < pendingKeys.length; i++) {\n childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);\n }\n\n return childMapping;\n}\n\nfunction getProp(child, prop, props) {\n return props[prop] != null ? props[prop] : child.props[prop];\n}\n\nexport function getInitialChildMapping(props, onExited) {\n return getChildMapping(props.children, function (child) {\n return cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: true,\n appear: getProp(child, 'appear', props),\n enter: getProp(child, 'enter', props),\n exit: getProp(child, 'exit', props)\n });\n });\n}\nexport function getNextChildMapping(nextProps, prevChildMapping, onExited) {\n var nextChildMapping = getChildMapping(nextProps.children);\n var children = mergeChildMappings(prevChildMapping, nextChildMapping);\n Object.keys(children).forEach(function (key) {\n var child = children[key];\n if (!isValidElement(child)) return;\n var hasPrev = (key in prevChildMapping);\n var hasNext = (key in nextChildMapping);\n var prevChild = prevChildMapping[key];\n var isLeaving = isValidElement(prevChild) && !prevChild.props.in; // item is new (entering)\n\n if (hasNext && (!hasPrev || isLeaving)) {\n // console.log('entering', key)\n children[key] = cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: true,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n } else if (!hasNext && hasPrev && !isLeaving) {\n // item is old (exiting)\n // console.log('leaving', key)\n children[key] = cloneElement(child, {\n in: false\n });\n } else if (hasNext && hasPrev && isValidElement(prevChild)) {\n // item hasn't changed transition states\n // copy over the last transition props;\n // console.log('unchanged', key)\n children[key] = cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: prevChild.props.in,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n }\n });\n return children;\n}","import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _assertThisInitialized from \"@babel/runtime/helpers/esm/assertThisInitialized\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport TransitionGroupContext from './TransitionGroupContext';\nimport { getChildMapping, getInitialChildMapping, getNextChildMapping } from './utils/ChildMapping';\n\nvar values = Object.values || function (obj) {\n return Object.keys(obj).map(function (k) {\n return obj[k];\n });\n};\n\nvar defaultProps = {\n component: 'div',\n childFactory: function childFactory(child) {\n return child;\n }\n};\n/**\n * The `` component manages a set of transition components\n * (`` and ``) in a list. Like with the transition\n * components, `` is a state machine for managing the mounting\n * and unmounting of components over time.\n *\n * Consider the example below. As items are removed or added to the TodoList the\n * `in` prop is toggled automatically by the ``.\n *\n * Note that `` does not define any animation behavior!\n * Exactly _how_ a list item animates is up to the individual transition\n * component. This means you can mix and match animations across different list\n * items.\n */\n\nvar TransitionGroup = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(TransitionGroup, _React$Component);\n\n function TransitionGroup(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n\n var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear\n\n\n _this.state = {\n contextValue: {\n isMounting: true\n },\n handleExited: handleExited,\n firstRender: true\n };\n return _this;\n }\n\n var _proto = TransitionGroup.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.mounted = true;\n this.setState({\n contextValue: {\n isMounting: false\n }\n });\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.mounted = false;\n };\n\n TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {\n var prevChildMapping = _ref.children,\n handleExited = _ref.handleExited,\n firstRender = _ref.firstRender;\n return {\n children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),\n firstRender: false\n };\n } // node is `undefined` when user provided `nodeRef` prop\n ;\n\n _proto.handleExited = function handleExited(child, node) {\n var currentChildMapping = getChildMapping(this.props.children);\n if (child.key in currentChildMapping) return;\n\n if (child.props.onExited) {\n child.props.onExited(node);\n }\n\n if (this.mounted) {\n this.setState(function (state) {\n var children = _extends({}, state.children);\n\n delete children[child.key];\n return {\n children: children\n };\n });\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n Component = _this$props.component,\n childFactory = _this$props.childFactory,\n props = _objectWithoutPropertiesLoose(_this$props, [\"component\", \"childFactory\"]);\n\n var contextValue = this.state.contextValue;\n var children = values(this.state.children).map(childFactory);\n delete props.appear;\n delete props.enter;\n delete props.exit;\n\n if (Component === null) {\n return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {\n value: contextValue\n }, children);\n }\n\n return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {\n value: contextValue\n }, /*#__PURE__*/React.createElement(Component, props, children));\n };\n\n return TransitionGroup;\n}(React.Component);\n\nTransitionGroup.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * `` renders a `
    ` by default. You can change this\n * behavior by providing a `component` prop.\n * If you use React v16+ and would like to avoid a wrapping `
    ` element\n * you can pass in `component={null}`. This is useful if the wrapping div\n * borks your css styles.\n */\n component: PropTypes.any,\n\n /**\n * A set of `` components, that are toggled `in` and out as they\n * leave. the `` will inject specific transition props, so\n * remember to spread them through if you are wrapping the `` as\n * with our `` example.\n *\n * While this component is meant for multiple `Transition` or `CSSTransition`\n * children, sometimes you may want to have a single transition child with\n * content that you want to be transitioned out and in when you change it\n * (e.g. routes, images etc.) In that case you can change the `key` prop of\n * the transition child as you change its content, this will cause\n * `TransitionGroup` to transition the child out and back in.\n */\n children: PropTypes.node,\n\n /**\n * A convenience prop that enables or disables appear animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n appear: PropTypes.bool,\n\n /**\n * A convenience prop that enables or disables enter animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * A convenience prop that enables or disables exit animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * You may need to apply reactive updates to a child as it is exiting.\n * This is generally done by using `cloneElement` however in the case of an exiting\n * child the element has already been removed and not accessible to the consumer.\n *\n * If you do need to update a child as it leaves you can provide a `childFactory`\n * to wrap every child, even the ones that are leaving.\n *\n * @type Function(child: ReactElement) -> ReactElement\n */\n childFactory: PropTypes.func\n} : {};\nTransitionGroup.defaultProps = defaultProps;\nexport default TransitionGroup;","export default function _taggedTemplateLiteralLoose(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n strings.raw = raw;\n return strings;\n}","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e))for(t=0;t {};\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {useCallback, useEffect, useRef, useState} from 'react';\nimport {useLayoutEffect} from './useLayoutEffect';\nimport {useSSRSafeId} from '@react-aria/ssr';\nimport {useValueEffect} from './';\n\nlet idsUpdaterMap: Map void> = new Map();\n\n/**\n * If a default is not provided, generate an id.\n * @param defaultId - Default component id.\n */\nexport function useId(defaultId?: string): string {\n let [value, setValue] = useState(defaultId);\n let nextId = useRef(null);\n\n let res = useSSRSafeId(value);\n\n let updateValue = useCallback((val) => {\n nextId.current = val;\n }, []);\n\n idsUpdaterMap.set(res, updateValue);\n\n useLayoutEffect(() => {\n let r = res;\n return () => {\n idsUpdaterMap.delete(r);\n };\n }, [res]);\n\n // This cannot cause an infinite loop because the ref is updated first.\n // eslint-disable-next-line\n useEffect(() => {\n let newId = nextId.current;\n if (newId) {\n nextId.current = null;\n setValue(newId);\n }\n });\n\n return res;\n}\n\n/**\n * Merges two ids.\n * Different ids will trigger a side-effect and re-render components hooked up with `useId`.\n */\nexport function mergeIds(idA: string, idB: string): string {\n if (idA === idB) {\n return idA;\n }\n\n let setIdA = idsUpdaterMap.get(idA);\n if (setIdA) {\n setIdA(idB);\n return idB;\n }\n\n let setIdB = idsUpdaterMap.get(idB);\n if (setIdB) {\n setIdB(idA);\n return idA;\n }\n\n return idB;\n}\n\n/**\n * Used to generate an id, and after render, check if that id is rendered so we know\n * if we can use it in places such as labelledby.\n * @param depArray - When to recalculate if the id is in the DOM.\n */\nexport function useSlotId(depArray: ReadonlyArray = []): string {\n let id = useId();\n let [resolvedId, setResolvedId] = useValueEffect(id);\n let updateId = useCallback(() => {\n setResolvedId(function *() {\n yield id;\n\n yield document.getElementById(id) ? id : null;\n });\n }, [id, setResolvedId]);\n\n useLayoutEffect(updateId, [id, updateId, ...depArray]);\n\n return resolvedId;\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n/**\n * Calls all functions in the order they were chained with the same arguments.\n */\nexport function chain(...callbacks: any[]): (...args: any[]) => void {\n return (...args: any[]) => {\n for (let callback of callbacks) {\n if (typeof callback === 'function') {\n callback(...args);\n }\n }\n };\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {chain} from './chain';\nimport clsx from 'clsx';\nimport {mergeIds} from './useId';\n\ninterface Props {\n [key: string]: any\n}\n\n// taken from: https://stackoverflow.com/questions/51603250/typescript-3-parameter-list-intersection-type/51604379#51604379\ntype TupleTypes = { [P in keyof T]: T[P] } extends { [key: number]: infer V } ? V : never;\n// eslint-disable-next-line no-undef, @typescript-eslint/no-unused-vars\ntype UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;\n\n/**\n * Merges multiple props objects together. Event handlers are chained,\n * classNames are combined, and ids are deduplicated - different ids\n * will trigger a side-effect and re-render components hooked up with `useId`.\n * For all other props, the last prop object overrides all previous ones.\n * @param args - Multiple sets of props to merge together.\n */\nexport function mergeProps(...args: T): UnionToIntersection> {\n // Start with a base clone of the first argument. This is a lot faster than starting\n // with an empty object and adding properties as we go.\n let result: Props = {...args[0]};\n for (let i = 1; i < args.length; i++) {\n let props = args[i];\n for (let key in props) {\n let a = result[key];\n let b = props[key];\n\n // Chain events\n if (\n typeof a === 'function' &&\n typeof b === 'function' &&\n // This is a lot faster than a regex.\n key[0] === 'o' &&\n key[1] === 'n' &&\n key.charCodeAt(2) >= /* 'A' */ 65 &&\n key.charCodeAt(2) <= /* 'Z' */ 90\n ) {\n result[key] = chain(a, b);\n\n // Merge classnames, sometimes classNames are empty string which eval to false, so we just need to do a type check\n } else if (\n (key === 'className' || key === 'UNSAFE_className') &&\n typeof a === 'string' &&\n typeof b === 'string'\n ) {\n result[key] = clsx(a, b);\n } else if (key === 'id' && a && b) {\n result.id = mergeIds(a, b);\n // Override others\n } else {\n result[key] = b !== undefined ? b : a;\n }\n }\n }\n\n return result as UnionToIntersection>;\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AriaLabelingProps, DOMProps} from '@react-types/shared';\n\nconst DOMPropNames = new Set([\n 'id'\n]);\n\nconst labelablePropNames = new Set([\n 'aria-label',\n 'aria-labelledby',\n 'aria-describedby',\n 'aria-details'\n]);\n\ninterface Options {\n /**\n * If labelling associated aria properties should be included in the filter.\n */\n labelable?: boolean,\n /**\n * A Set of other property names that should be included in the filter.\n */\n propNames?: Set\n}\n\nconst propRe = /^(data-.*)$/;\n\n/**\n * Filters out all props that aren't valid DOM props or defined via override prop obj.\n * @param props - The component props to be filtered.\n * @param opts - Props to override.\n */\nexport function filterDOMProps(props: DOMProps & AriaLabelingProps, opts: Options = {}): DOMProps & AriaLabelingProps {\n let {labelable, propNames} = opts;\n let filteredProps = {};\n\n for (const prop in props) {\n if (\n Object.prototype.hasOwnProperty.call(props, prop) && (\n DOMPropNames.has(prop) ||\n (labelable && labelablePropNames.has(prop)) ||\n propNames?.has(prop) ||\n propRe.test(prop)\n )\n ) {\n filteredProps[prop] = props[prop];\n }\n }\n\n return filteredProps;\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {FocusableElement} from '@react-types/shared';\n\n// This is a polyfill for element.focus({preventScroll: true});\n// Currently necessary for Safari and old Edge:\n// https://caniuse.com/#feat=mdn-api_htmlelement_focus_preventscroll_option\n// See https://bugs.webkit.org/show_bug.cgi?id=178583\n//\n\n// Original licensing for the following methods can be found in the\n// NOTICE file in the root directory of this source tree.\n// See https://github.com/calvellido/focus-options-polyfill\n\ninterface ScrollableElement {\n element: HTMLElement,\n scrollTop: number,\n scrollLeft: number\n}\n\nexport function focusWithoutScrolling(element: FocusableElement) {\n if (supportsPreventScroll()) {\n element.focus({preventScroll: true});\n } else {\n let scrollableElements = getScrollableElements(element);\n element.focus();\n restoreScrollPosition(scrollableElements);\n }\n}\n\nlet supportsPreventScrollCached: boolean = null;\nfunction supportsPreventScroll() {\n if (supportsPreventScrollCached == null) {\n supportsPreventScrollCached = false;\n try {\n var focusElem = document.createElement('div');\n focusElem.focus({\n get preventScroll() {\n supportsPreventScrollCached = true;\n return true;\n }\n });\n } catch (e) {\n // Ignore\n }\n }\n\n return supportsPreventScrollCached;\n}\n\nfunction getScrollableElements(element: FocusableElement): ScrollableElement[] {\n var parent = element.parentNode;\n var scrollableElements: ScrollableElement[] = [];\n var rootScrollingElement = document.scrollingElement || document.documentElement;\n\n while (parent instanceof HTMLElement && parent !== rootScrollingElement) {\n if (\n parent.offsetHeight < parent.scrollHeight ||\n parent.offsetWidth < parent.scrollWidth\n ) {\n scrollableElements.push({\n element: parent,\n scrollTop: parent.scrollTop,\n scrollLeft: parent.scrollLeft\n });\n }\n parent = parent.parentNode;\n }\n\n if (rootScrollingElement instanceof HTMLElement) {\n scrollableElements.push({\n element: rootScrollingElement,\n scrollTop: rootScrollingElement.scrollTop,\n scrollLeft: rootScrollingElement.scrollLeft\n });\n }\n\n return scrollableElements;\n}\n\nfunction restoreScrollPosition(scrollableElements: ScrollableElement[]) {\n for (let {element, scrollTop, scrollLeft} of scrollableElements) {\n element.scrollTop = scrollTop;\n element.scrollLeft = scrollLeft;\n }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// We store a global list of elements that are currently transitioning,\n// mapped to a set of CSS properties that are transitioning for that element.\n// This is necessary rather than a simple count of transitions because of browser\n// bugs, e.g. Chrome sometimes fires both transitionend and transitioncancel rather\n// than one or the other. So we need to track what's actually transitioning so that\n// we can ignore these duplicate events.\nlet transitionsByElement = new Map>();\n\n// A list of callbacks to call once there are no transitioning elements.\nlet transitionCallbacks = new Set<() => void>();\n\nfunction setupGlobalEvents() {\n if (typeof window === 'undefined') {\n return;\n }\n\n let onTransitionStart = (e: TransitionEvent) => {\n // Add the transitioning property to the list for this element.\n let transitions = transitionsByElement.get(e.target);\n if (!transitions) {\n transitions = new Set();\n transitionsByElement.set(e.target, transitions);\n\n // The transitioncancel event must be registered on the element itself, rather than as a global\n // event. This enables us to handle when the node is deleted from the document while it is transitioning.\n // In that case, the cancel event would have nowhere to bubble to so we need to handle it directly.\n e.target.addEventListener('transitioncancel', onTransitionEnd);\n }\n\n transitions.add(e.propertyName);\n };\n\n let onTransitionEnd = (e: TransitionEvent) => {\n // Remove property from list of transitioning properties.\n let properties = transitionsByElement.get(e.target);\n if (!properties) {\n return;\n }\n\n properties.delete(e.propertyName);\n\n // If empty, remove transitioncancel event, and remove the element from the list of transitioning elements.\n if (properties.size === 0) {\n e.target.removeEventListener('transitioncancel', onTransitionEnd);\n transitionsByElement.delete(e.target);\n }\n\n // If no transitioning elements, call all of the queued callbacks.\n if (transitionsByElement.size === 0) {\n for (let cb of transitionCallbacks) {\n cb();\n }\n\n transitionCallbacks.clear();\n }\n };\n\n document.body.addEventListener('transitionrun', onTransitionStart);\n document.body.addEventListener('transitionend', onTransitionEnd);\n}\n\nif (typeof document !== 'undefined') {\n if (document.readyState !== 'loading') {\n setupGlobalEvents();\n } else {\n document.addEventListener('DOMContentLoaded', setupGlobalEvents);\n }\n}\n\nexport function runAfterTransition(fn: () => void) {\n // Wait one frame to see if an animation starts, e.g. a transition on mount.\n requestAnimationFrame(() => {\n // If no transitions are running, call the function immediately.\n // Otherwise, add it to a list of callbacks to run at the end of the animation.\n if (transitionsByElement.size === 0) {\n fn();\n } else {\n transitionCallbacks.add(fn);\n }\n });\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {MutableRefObject, RefObject} from 'react';\nimport {useLayoutEffect} from './';\n\ninterface ContextValue {\n ref?: MutableRefObject\n}\n\n// Syncs ref from context with ref passed to hook\nexport function useSyncRef(context: ContextValue, ref: RefObject) {\n useLayoutEffect(() => {\n if (context && context.ref && ref) {\n context.ref.current = ref.current;\n return () => {\n context.ref.current = null;\n };\n }\n }, [context, ref]);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {useEffect, useState} from 'react';\n\ninterface ViewportSize {\n width: number,\n height: number\n}\n\n// @ts-ignore\nlet visualViewport = typeof window !== 'undefined' && window.visualViewport;\n\nexport function useViewportSize(): ViewportSize {\n let [size, setSize] = useState(() => getViewportSize());\n\n useEffect(() => {\n // Use visualViewport api to track available height even on iOS virtual keyboard opening\n let onResize = () => {\n setSize(size => {\n let newSize = getViewportSize();\n if (newSize.width === size.width && newSize.height === size.height) {\n return size;\n }\n return newSize;\n });\n };\n\n if (!visualViewport) {\n window.addEventListener('resize', onResize);\n } else {\n visualViewport.addEventListener('resize', onResize);\n }\n\n return () => {\n if (!visualViewport) {\n window.removeEventListener('resize', onResize);\n } else {\n visualViewport.removeEventListener('resize', onResize);\n }\n };\n }, []);\n\n return size;\n}\n\nfunction getViewportSize(): ViewportSize {\n return {\n width: visualViewport?.width || window.innerWidth,\n height: visualViewport?.height || window.innerHeight\n };\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AriaLabelingProps} from '@react-types/shared';\nimport {useLayoutEffect} from './useLayoutEffect';\nimport {useState} from 'react';\n\nlet descriptionId = 0;\nconst descriptionNodes = new Map();\n\nexport function useDescription(description: string): AriaLabelingProps {\n let [id, setId] = useState(null);\n\n useLayoutEffect(() => {\n if (!description) {\n return;\n }\n\n let desc = descriptionNodes.get(description);\n if (!desc) {\n let id = `react-aria-description-${descriptionId++}`;\n setId(id);\n\n let node = document.createElement('div');\n node.id = id;\n node.style.display = 'none';\n node.textContent = description;\n document.body.appendChild(node);\n desc = {refCount: 0, element: node};\n descriptionNodes.set(description, desc);\n } else {\n setId(desc.element.id);\n }\n\n desc.refCount++;\n return () => {\n if (--desc.refCount === 0) {\n desc.element.remove();\n descriptionNodes.delete(description);\n }\n };\n }, [description]);\n\n return {\n 'aria-describedby': description ? id : undefined\n };\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nfunction testUserAgent(re: RegExp) {\n if (typeof window === 'undefined' || window.navigator == null) {\n return false;\n }\n return (\n window.navigator['userAgentData']?.brands.some((brand: {brand: string, version: string}) => re.test(brand.brand))\n ) ||\n re.test(window.navigator.userAgent);\n}\n\nfunction testPlatform(re: RegExp) {\n return typeof window !== 'undefined' && window.navigator != null\n ? re.test(window.navigator['userAgentData']?.platform || window.navigator.platform)\n : false;\n}\n\nexport function isMac() {\n return testPlatform(/^Mac/i);\n}\n\nexport function isIPhone() {\n return testPlatform(/^iPhone/i);\n}\n\nexport function isIPad() {\n return testPlatform(/^iPad/i) ||\n // iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support.\n (isMac() && navigator.maxTouchPoints > 1);\n}\n\nexport function isIOS() {\n return isIPhone() || isIPad();\n}\n\nexport function isAppleDevice() {\n return isMac() || isIOS();\n}\n\nexport function isWebKit() {\n return testUserAgent(/AppleWebKit/i) && !isChrome();\n}\n\nexport function isChrome() {\n return testUserAgent(/Chrome/i);\n}\n\nexport function isAndroid() {\n return testUserAgent(/Android/i);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {isIOS, runAfterTransition} from '@react-aria/utils';\n\n// Safari on iOS starts selecting text on long press. The only way to avoid this, it seems,\n// is to add user-select: none to the entire page. Adding it to the pressable element prevents\n// that element from being selected, but nearby elements may still receive selection. We add\n// user-select: none on touch start, and remove it again on touch end to prevent this.\n// This must be implemented using global state to avoid race conditions between multiple elements.\n\n// There are three possible states due to the delay before removing user-select: none after\n// pointer up. The 'default' state always transitions to the 'disabled' state, which transitions\n// to 'restoring'. The 'restoring' state can either transition back to 'disabled' or 'default'.\n\n// For non-iOS devices, we apply user-select: none to the pressed element instead to avoid possible\n// performance issues that arise from applying and removing user-select: none to the entire page\n// (see https://github.com/adobe/react-spectrum/issues/1609).\ntype State = 'default' | 'disabled' | 'restoring';\n\n// Note that state only matters here for iOS. Non-iOS gets user-select: none applied to the target element\n// rather than at the document level so we just need to apply/remove user-select: none for each pressed element individually\nlet state: State = 'default';\nlet savedUserSelect = '';\nlet modifiedElementMap = new WeakMap();\n\nexport function disableTextSelection(target?: Element) {\n if (isIOS()) {\n if (state === 'default') {\n savedUserSelect = document.documentElement.style.webkitUserSelect;\n document.documentElement.style.webkitUserSelect = 'none';\n }\n\n state = 'disabled';\n } else if (target instanceof HTMLElement || target instanceof SVGElement) {\n // If not iOS, store the target's original user-select and change to user-select: none\n // Ignore state since it doesn't apply for non iOS\n modifiedElementMap.set(target, target.style.userSelect);\n target.style.userSelect = 'none';\n }\n}\n\nexport function restoreTextSelection(target?: Element) {\n if (isIOS()) {\n // If the state is already default, there's nothing to do.\n // If it is restoring, then there's no need to queue a second restore.\n if (state !== 'disabled') {\n return;\n }\n\n state = 'restoring';\n\n // There appears to be a delay on iOS where selection still might occur\n // after pointer up, so wait a bit before removing user-select.\n setTimeout(() => {\n // Wait for any CSS transitions to complete so we don't recompute style\n // for the whole page in the middle of the animation and cause jank.\n runAfterTransition(() => {\n // Avoid race conditions\n if (state === 'restoring') {\n if (document.documentElement.style.webkitUserSelect === 'none') {\n document.documentElement.style.webkitUserSelect = savedUserSelect || '';\n }\n\n savedUserSelect = '';\n state = 'default';\n }\n });\n }, 300);\n } else if (target instanceof HTMLElement || target instanceof SVGElement) {\n // If not iOS, restore the target's original user-select if any\n // Ignore state since it doesn't apply for non iOS\n if (target && modifiedElementMap.has(target)) {\n let targetOldUserSelect = modifiedElementMap.get(target);\n\n if (target.style.userSelect === 'none') {\n target.style.userSelect = targetOldUserSelect;\n }\n\n if (target.getAttribute('style') === '') {\n target.removeAttribute('style');\n }\n modifiedElementMap.delete(target);\n }\n }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {FocusEvent as ReactFocusEvent, useCallback, useRef} from 'react';\nimport {useLayoutEffect} from '@react-aria/utils';\n\n// Original licensing for the following method can be found in the\n// NOTICE file in the root directory of this source tree.\n// See https://github.com/facebook/react/blob/3c713d513195a53788b3f8bb4b70279d68b15bcc/packages/react-interactions/events/src/dom/shared/index.js#L74-L87\n\n// Keyboards, Assistive Technologies, and element.click() all produce a \"virtual\"\n// click event. This is a method of inferring such clicks. Every browser except\n// IE 11 only sets a zero value of \"detail\" for click events that are \"virtual\".\n// However, IE 11 uses a zero value for all click events. For IE 11 we rely on\n// the quirk that it produces click events that are of type PointerEvent, and\n// where only the \"virtual\" click lacks a pointerType field.\n\nexport function isVirtualClick(event: MouseEvent | PointerEvent): boolean {\n // JAWS/NVDA with Firefox.\n if ((event as any).mozInputSource === 0 && event.isTrusted) {\n return true;\n }\n\n return event.detail === 0 && !(event as PointerEvent).pointerType;\n}\n\nexport class SyntheticFocusEvent implements ReactFocusEvent {\n nativeEvent: FocusEvent;\n target: Element;\n currentTarget: Element;\n relatedTarget: Element;\n bubbles: boolean;\n cancelable: boolean;\n defaultPrevented: boolean;\n eventPhase: number;\n isTrusted: boolean;\n timeStamp: number;\n type: string;\n\n constructor(type: string, nativeEvent: FocusEvent) {\n this.nativeEvent = nativeEvent;\n this.target = nativeEvent.target as Element;\n this.currentTarget = nativeEvent.currentTarget as Element;\n this.relatedTarget = nativeEvent.relatedTarget as Element;\n this.bubbles = nativeEvent.bubbles;\n this.cancelable = nativeEvent.cancelable;\n this.defaultPrevented = nativeEvent.defaultPrevented;\n this.eventPhase = nativeEvent.eventPhase;\n this.isTrusted = nativeEvent.isTrusted;\n this.timeStamp = nativeEvent.timeStamp;\n this.type = type;\n }\n\n isDefaultPrevented(): boolean {\n return this.nativeEvent.defaultPrevented;\n }\n\n preventDefault(): void {\n this.defaultPrevented = true;\n this.nativeEvent.preventDefault();\n }\n\n stopPropagation(): void {\n this.nativeEvent.stopPropagation();\n this.isPropagationStopped = () => true;\n }\n\n isPropagationStopped(): boolean {\n return false;\n }\n\n persist() {}\n}\n\nexport function useSyntheticBlurEvent(onBlur: (e: ReactFocusEvent) => void) {\n let stateRef = useRef({\n isFocused: false,\n onBlur,\n observer: null as MutationObserver\n });\n stateRef.current.onBlur = onBlur;\n\n // Clean up MutationObserver on unmount. See below.\n // eslint-disable-next-line arrow-body-style\n useLayoutEffect(() => {\n const state = stateRef.current;\n return () => {\n if (state.observer) {\n state.observer.disconnect();\n state.observer = null;\n }\n };\n }, []);\n\n // This function is called during a React onFocus event.\n return useCallback((e: ReactFocusEvent) => {\n // React does not fire onBlur when an element is disabled. https://github.com/facebook/react/issues/9142\n // Most browsers fire a native focusout event in this case, except for Firefox. In that case, we use a\n // MutationObserver to watch for the disabled attribute, and dispatch these events ourselves.\n // For browsers that do, focusout fires before the MutationObserver, so onBlur should not fire twice.\n if (\n e.target instanceof HTMLButtonElement ||\n e.target instanceof HTMLInputElement ||\n e.target instanceof HTMLTextAreaElement ||\n e.target instanceof HTMLSelectElement\n ) {\n stateRef.current.isFocused = true;\n\n let target = e.target;\n let onBlurHandler = (e: FocusEvent) => {\n stateRef.current.isFocused = false;\n\n if (target.disabled) {\n // For backward compatibility, dispatch a (fake) React synthetic event.\n stateRef.current.onBlur?.(new SyntheticFocusEvent('blur', e));\n }\n\n // We no longer need the MutationObserver once the target is blurred.\n if (stateRef.current.observer) {\n stateRef.current.observer.disconnect();\n stateRef.current.observer = null;\n }\n };\n\n target.addEventListener('focusout', onBlurHandler, {once: true});\n\n stateRef.current.observer = new MutationObserver(() => {\n if (stateRef.current.isFocused && target.disabled) {\n stateRef.current.observer.disconnect();\n target.dispatchEvent(new FocusEvent('blur'));\n target.dispatchEvent(new FocusEvent('focusout', {bubbles: true}));\n }\n });\n\n stateRef.current.observer.observe(target, {attributes: true, attributeFilter: ['disabled']});\n }\n }, []);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {FocusableElement} from '@react-types/shared';\nimport {PressProps} from './usePress';\nimport React, {MutableRefObject} from 'react';\n\ninterface IPressResponderContext extends PressProps {\n register(): void,\n ref?: MutableRefObject\n}\n\nexport const PressResponderContext = React.createContext(null);\nPressResponderContext.displayName = 'PressResponderContext';\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from react.\n// Original licensing for the following can be found in the\n// NOTICE file in the root directory of this source tree.\n// See https://github.com/facebook/react/tree/cc7c1aece46a6b69b41958d731e0fd27c94bfc6c/packages/react-interactions\n\nimport {disableTextSelection, restoreTextSelection} from './textSelection';\nimport {DOMAttributes, FocusableElement, PointerType, PressEvents} from '@react-types/shared';\nimport {focusWithoutScrolling, mergeProps, useGlobalListeners, useSyncRef} from '@react-aria/utils';\nimport {isVirtualClick} from './utils';\nimport {PressResponderContext} from './context';\nimport {RefObject, useContext, useEffect, useMemo, useRef, useState} from 'react';\n\nexport interface PressProps extends PressEvents {\n /** Whether the target is in a controlled press state (e.g. an overlay it triggers is open). */\n isPressed?: boolean,\n /** Whether the press events should be disabled. */\n isDisabled?: boolean,\n /** Whether the target should not receive focus on press. */\n preventFocusOnPress?: boolean,\n /**\n * Whether press events should be canceled when the pointer leaves the target while pressed.\n * By default, this is `false`, which means if the pointer returns back over the target while\n * still pressed, onPressStart will be fired again. If set to `true`, the press is canceled\n * when the pointer leaves the target and onPressStart will not be fired if the pointer returns.\n */\n shouldCancelOnPointerExit?: boolean,\n /** Whether text selection should be enabled on the pressable element. */\n allowTextSelectionOnPress?: boolean\n}\n\nexport interface PressHookProps extends PressProps {\n /** A ref to the target element. */\n ref?: RefObject\n}\n\ninterface PressState {\n isPressed: boolean,\n ignoreEmulatedMouseEvents: boolean,\n ignoreClickAfterPress: boolean,\n didFirePressStart: boolean,\n activePointerId: any,\n target: FocusableElement | null,\n isOverTarget: boolean,\n pointerType: PointerType,\n userSelect?: string\n}\n\ninterface EventBase {\n currentTarget: EventTarget,\n shiftKey: boolean,\n ctrlKey: boolean,\n metaKey: boolean,\n altKey: boolean\n}\n\nexport interface PressResult {\n /** Whether the target is currently pressed. */\n isPressed: boolean,\n /** Props to spread on the target element. */\n pressProps: DOMAttributes\n}\n\nfunction usePressResponderContext(props: PressHookProps): PressHookProps {\n // Consume context from and merge with props.\n let context = useContext(PressResponderContext);\n if (context) {\n let {register, ...contextProps} = context;\n props = mergeProps(contextProps, props) as PressHookProps;\n register();\n }\n useSyncRef(context, props.ref);\n\n return props;\n}\n\n/**\n * Handles press interactions across mouse, touch, keyboard, and screen readers.\n * It normalizes behavior across browsers and platforms, and handles many nuances\n * of dealing with pointer and keyboard events.\n */\nexport function usePress(props: PressHookProps): PressResult {\n let {\n onPress,\n onPressChange,\n onPressStart,\n onPressEnd,\n onPressUp,\n isDisabled,\n isPressed: isPressedProp,\n preventFocusOnPress,\n shouldCancelOnPointerExit,\n allowTextSelectionOnPress,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n ref: _, // Removing `ref` from `domProps` because TypeScript is dumb\n ...domProps\n } = usePressResponderContext(props);\n let propsRef = useRef(null);\n propsRef.current = {onPress, onPressChange, onPressStart, onPressEnd, onPressUp, isDisabled, shouldCancelOnPointerExit};\n\n let [isPressed, setPressed] = useState(false);\n let ref = useRef({\n isPressed: false,\n ignoreEmulatedMouseEvents: false,\n ignoreClickAfterPress: false,\n didFirePressStart: false,\n activePointerId: null,\n target: null,\n isOverTarget: false,\n pointerType: null\n });\n\n let {addGlobalListener, removeAllGlobalListeners} = useGlobalListeners();\n\n let pressProps = useMemo(() => {\n let state = ref.current;\n let triggerPressStart = (originalEvent: EventBase, pointerType: PointerType) => {\n let {onPressStart, onPressChange, isDisabled} = propsRef.current;\n if (isDisabled || state.didFirePressStart) {\n return;\n }\n\n if (onPressStart) {\n onPressStart({\n type: 'pressstart',\n pointerType,\n target: originalEvent.currentTarget as Element,\n shiftKey: originalEvent.shiftKey,\n metaKey: originalEvent.metaKey,\n ctrlKey: originalEvent.ctrlKey,\n altKey: originalEvent.altKey\n });\n }\n\n if (onPressChange) {\n onPressChange(true);\n }\n\n state.didFirePressStart = true;\n setPressed(true);\n };\n\n let triggerPressEnd = (originalEvent: EventBase, pointerType: PointerType, wasPressed = true) => {\n let {onPressEnd, onPressChange, onPress, isDisabled} = propsRef.current;\n if (!state.didFirePressStart) {\n return;\n }\n\n state.ignoreClickAfterPress = true;\n state.didFirePressStart = false;\n\n if (onPressEnd) {\n onPressEnd({\n type: 'pressend',\n pointerType,\n target: originalEvent.currentTarget as Element,\n shiftKey: originalEvent.shiftKey,\n metaKey: originalEvent.metaKey,\n ctrlKey: originalEvent.ctrlKey,\n altKey: originalEvent.altKey\n });\n }\n\n if (onPressChange) {\n onPressChange(false);\n }\n\n setPressed(false);\n\n if (onPress && wasPressed && !isDisabled) {\n onPress({\n type: 'press',\n pointerType,\n target: originalEvent.currentTarget as Element,\n shiftKey: originalEvent.shiftKey,\n metaKey: originalEvent.metaKey,\n ctrlKey: originalEvent.ctrlKey,\n altKey: originalEvent.altKey\n });\n }\n };\n\n let triggerPressUp = (originalEvent: EventBase, pointerType: PointerType) => {\n let {onPressUp, isDisabled} = propsRef.current;\n if (isDisabled) {\n return;\n }\n\n if (onPressUp) {\n onPressUp({\n type: 'pressup',\n pointerType,\n target: originalEvent.currentTarget as Element,\n shiftKey: originalEvent.shiftKey,\n metaKey: originalEvent.metaKey,\n ctrlKey: originalEvent.ctrlKey,\n altKey: originalEvent.altKey\n });\n }\n };\n\n let cancel = (e: EventBase) => {\n if (state.isPressed) {\n if (state.isOverTarget) {\n triggerPressEnd(createEvent(state.target, e), state.pointerType, false);\n }\n state.isPressed = false;\n state.isOverTarget = false;\n state.activePointerId = null;\n state.pointerType = null;\n removeAllGlobalListeners();\n if (!allowTextSelectionOnPress) {\n restoreTextSelection(state.target);\n }\n }\n };\n\n let pressProps: DOMAttributes = {\n onKeyDown(e) {\n if (isValidKeyboardEvent(e.nativeEvent, e.currentTarget) && e.currentTarget.contains(e.target as Element)) {\n if (shouldPreventDefaultKeyboard(e.target as Element, e.key)) {\n e.preventDefault();\n }\n e.stopPropagation();\n\n // If the event is repeating, it may have started on a different element\n // after which focus moved to the current element. Ignore these events and\n // only handle the first key down event.\n if (!state.isPressed && !e.repeat) {\n state.target = e.currentTarget;\n state.isPressed = true;\n triggerPressStart(e, 'keyboard');\n\n // Focus may move before the key up event, so register the event on the document\n // instead of the same element where the key down event occurred.\n addGlobalListener(document, 'keyup', onKeyUp, false);\n }\n } else if (e.key === 'Enter' && isHTMLAnchorLink(e.currentTarget)) {\n // If the target is a link, we won't have handled this above because we want the default\n // browser behavior to open the link when pressing Enter. But we still need to prevent\n // default so that elements above do not also handle it (e.g. table row).\n e.stopPropagation();\n }\n },\n onKeyUp(e) {\n if (isValidKeyboardEvent(e.nativeEvent, e.currentTarget) && !e.repeat && e.currentTarget.contains(e.target as Element)) {\n triggerPressUp(createEvent(state.target, e), 'keyboard');\n }\n },\n onClick(e) {\n if (e && !e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n if (e && e.button === 0) {\n e.stopPropagation();\n if (isDisabled) {\n e.preventDefault();\n }\n\n // If triggered from a screen reader or by using element.click(),\n // trigger as if it were a keyboard click.\n if (!state.ignoreClickAfterPress && !state.ignoreEmulatedMouseEvents && (state.pointerType === 'virtual' || isVirtualClick(e.nativeEvent))) {\n // Ensure the element receives focus (VoiceOver on iOS does not do this)\n if (!isDisabled && !preventFocusOnPress) {\n focusWithoutScrolling(e.currentTarget);\n }\n\n triggerPressStart(e, 'virtual');\n triggerPressUp(e, 'virtual');\n triggerPressEnd(e, 'virtual');\n }\n\n state.ignoreEmulatedMouseEvents = false;\n state.ignoreClickAfterPress = false;\n }\n }\n };\n\n let onKeyUp = (e: KeyboardEvent) => {\n if (state.isPressed && isValidKeyboardEvent(e, state.target)) {\n if (shouldPreventDefaultKeyboard(e.target as Element, e.key)) {\n e.preventDefault();\n }\n e.stopPropagation();\n\n state.isPressed = false;\n let target = e.target as Element;\n triggerPressEnd(createEvent(state.target, e), 'keyboard', state.target.contains(target));\n removeAllGlobalListeners();\n\n // If the target is a link, trigger the click method to open the URL,\n // but defer triggering pressEnd until onClick event handler.\n if (state.target instanceof HTMLElement && state.target.contains(target) && (isHTMLAnchorLink(state.target) || state.target.getAttribute('role') === 'link')) {\n state.target.click();\n }\n }\n };\n\n if (typeof PointerEvent !== 'undefined') {\n pressProps.onPointerDown = (e) => {\n // Only handle left clicks, and ignore events that bubbled through portals.\n if (e.button !== 0 || !e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n // iOS safari fires pointer events from VoiceOver with incorrect coordinates/target.\n // Ignore and let the onClick handler take care of it instead.\n // https://bugs.webkit.org/show_bug.cgi?id=222627\n // https://bugs.webkit.org/show_bug.cgi?id=223202\n if (isVirtualPointerEvent(e.nativeEvent)) {\n state.pointerType = 'virtual';\n return;\n }\n\n // Due to browser inconsistencies, especially on mobile browsers, we prevent\n // default on pointer down and handle focusing the pressable element ourselves.\n if (shouldPreventDefault(e.currentTarget as Element)) {\n e.preventDefault();\n }\n\n state.pointerType = e.pointerType;\n\n e.stopPropagation();\n if (!state.isPressed) {\n state.isPressed = true;\n state.isOverTarget = true;\n state.activePointerId = e.pointerId;\n state.target = e.currentTarget;\n\n if (!isDisabled && !preventFocusOnPress) {\n focusWithoutScrolling(e.currentTarget);\n }\n\n if (!allowTextSelectionOnPress) {\n disableTextSelection(state.target);\n }\n\n triggerPressStart(e, state.pointerType);\n\n addGlobalListener(document, 'pointermove', onPointerMove, false);\n addGlobalListener(document, 'pointerup', onPointerUp, false);\n addGlobalListener(document, 'pointercancel', onPointerCancel, false);\n }\n };\n\n pressProps.onMouseDown = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n if (e.button === 0) {\n // Chrome and Firefox on touch Windows devices require mouse down events\n // to be canceled in addition to pointer events, or an extra asynchronous\n // focus event will be fired.\n if (shouldPreventDefault(e.currentTarget as Element)) {\n e.preventDefault();\n }\n\n e.stopPropagation();\n }\n };\n\n pressProps.onPointerUp = (e) => {\n // iOS fires pointerup with zero width and height, so check the pointerType recorded during pointerdown.\n if (!e.currentTarget.contains(e.target as Element) || state.pointerType === 'virtual') {\n return;\n }\n\n // Only handle left clicks\n // Safari on iOS sometimes fires pointerup events, even\n // when the touch isn't over the target, so double check.\n if (e.button === 0 && isOverTarget(e, e.currentTarget)) {\n triggerPressUp(e, state.pointerType || e.pointerType);\n }\n };\n\n // Safari on iOS < 13.2 does not implement pointerenter/pointerleave events correctly.\n // Use pointer move events instead to implement our own hit testing.\n // See https://bugs.webkit.org/show_bug.cgi?id=199803\n let onPointerMove = (e: PointerEvent) => {\n if (e.pointerId !== state.activePointerId) {\n return;\n }\n\n if (isOverTarget(e, state.target)) {\n if (!state.isOverTarget) {\n state.isOverTarget = true;\n triggerPressStart(createEvent(state.target, e), state.pointerType);\n }\n } else if (state.isOverTarget) {\n state.isOverTarget = false;\n triggerPressEnd(createEvent(state.target, e), state.pointerType, false);\n if (propsRef.current.shouldCancelOnPointerExit) {\n cancel(e);\n }\n }\n };\n\n let onPointerUp = (e: PointerEvent) => {\n if (e.pointerId === state.activePointerId && state.isPressed && e.button === 0) {\n if (isOverTarget(e, state.target)) {\n triggerPressEnd(createEvent(state.target, e), state.pointerType);\n } else if (state.isOverTarget) {\n triggerPressEnd(createEvent(state.target, e), state.pointerType, false);\n }\n\n state.isPressed = false;\n state.isOverTarget = false;\n state.activePointerId = null;\n state.pointerType = null;\n removeAllGlobalListeners();\n if (!allowTextSelectionOnPress) {\n restoreTextSelection(state.target);\n }\n }\n };\n\n let onPointerCancel = (e: PointerEvent) => {\n cancel(e);\n };\n\n pressProps.onDragStart = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n // Safari does not call onPointerCancel when a drag starts, whereas Chrome and Firefox do.\n cancel(e);\n };\n } else {\n pressProps.onMouseDown = (e) => {\n // Only handle left clicks\n if (e.button !== 0 || !e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n // Due to browser inconsistencies, especially on mobile browsers, we prevent\n // default on mouse down and handle focusing the pressable element ourselves.\n if (shouldPreventDefault(e.currentTarget)) {\n e.preventDefault();\n }\n\n e.stopPropagation();\n if (state.ignoreEmulatedMouseEvents) {\n return;\n }\n\n state.isPressed = true;\n state.isOverTarget = true;\n state.target = e.currentTarget;\n state.pointerType = isVirtualClick(e.nativeEvent) ? 'virtual' : 'mouse';\n\n if (!isDisabled && !preventFocusOnPress) {\n focusWithoutScrolling(e.currentTarget);\n }\n\n triggerPressStart(e, state.pointerType);\n\n addGlobalListener(document, 'mouseup', onMouseUp, false);\n };\n\n pressProps.onMouseEnter = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n e.stopPropagation();\n if (state.isPressed && !state.ignoreEmulatedMouseEvents) {\n state.isOverTarget = true;\n triggerPressStart(e, state.pointerType);\n }\n };\n\n pressProps.onMouseLeave = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n e.stopPropagation();\n if (state.isPressed && !state.ignoreEmulatedMouseEvents) {\n state.isOverTarget = false;\n triggerPressEnd(e, state.pointerType, false);\n if (propsRef.current.shouldCancelOnPointerExit) {\n cancel(e);\n }\n }\n };\n\n pressProps.onMouseUp = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n if (!state.ignoreEmulatedMouseEvents && e.button === 0) {\n triggerPressUp(e, state.pointerType);\n }\n };\n\n let onMouseUp = (e: MouseEvent) => {\n // Only handle left clicks\n if (e.button !== 0) {\n return;\n }\n\n state.isPressed = false;\n removeAllGlobalListeners();\n\n if (state.ignoreEmulatedMouseEvents) {\n state.ignoreEmulatedMouseEvents = false;\n return;\n }\n\n if (isOverTarget(e, state.target)) {\n triggerPressEnd(createEvent(state.target, e), state.pointerType);\n } else if (state.isOverTarget) {\n triggerPressEnd(createEvent(state.target, e), state.pointerType, false);\n }\n\n state.isOverTarget = false;\n };\n\n pressProps.onTouchStart = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n e.stopPropagation();\n let touch = getTouchFromEvent(e.nativeEvent);\n if (!touch) {\n return;\n }\n state.activePointerId = touch.identifier;\n state.ignoreEmulatedMouseEvents = true;\n state.isOverTarget = true;\n state.isPressed = true;\n state.target = e.currentTarget;\n state.pointerType = 'touch';\n\n // Due to browser inconsistencies, especially on mobile browsers, we prevent default\n // on the emulated mouse event and handle focusing the pressable element ourselves.\n if (!isDisabled && !preventFocusOnPress) {\n focusWithoutScrolling(e.currentTarget);\n }\n\n if (!allowTextSelectionOnPress) {\n disableTextSelection(state.target);\n }\n\n triggerPressStart(e, state.pointerType);\n\n addGlobalListener(window, 'scroll', onScroll, true);\n };\n\n pressProps.onTouchMove = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n e.stopPropagation();\n if (!state.isPressed) {\n return;\n }\n\n let touch = getTouchById(e.nativeEvent, state.activePointerId);\n if (touch && isOverTarget(touch, e.currentTarget)) {\n if (!state.isOverTarget) {\n state.isOverTarget = true;\n triggerPressStart(e, state.pointerType);\n }\n } else if (state.isOverTarget) {\n state.isOverTarget = false;\n triggerPressEnd(e, state.pointerType, false);\n if (propsRef.current.shouldCancelOnPointerExit) {\n cancel(e);\n }\n }\n };\n\n pressProps.onTouchEnd = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n e.stopPropagation();\n if (!state.isPressed) {\n return;\n }\n\n let touch = getTouchById(e.nativeEvent, state.activePointerId);\n if (touch && isOverTarget(touch, e.currentTarget)) {\n triggerPressUp(e, state.pointerType);\n triggerPressEnd(e, state.pointerType);\n } else if (state.isOverTarget) {\n triggerPressEnd(e, state.pointerType, false);\n }\n\n state.isPressed = false;\n state.activePointerId = null;\n state.isOverTarget = false;\n state.ignoreEmulatedMouseEvents = true;\n if (!allowTextSelectionOnPress) {\n restoreTextSelection(state.target);\n }\n removeAllGlobalListeners();\n };\n\n pressProps.onTouchCancel = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n e.stopPropagation();\n if (state.isPressed) {\n cancel(e);\n }\n };\n\n let onScroll = (e: Event) => {\n if (state.isPressed && (e.target as Element).contains(state.target)) {\n cancel({\n currentTarget: state.target,\n shiftKey: false,\n ctrlKey: false,\n metaKey: false,\n altKey: false\n });\n }\n };\n\n pressProps.onDragStart = (e) => {\n if (!e.currentTarget.contains(e.target as Element)) {\n return;\n }\n\n cancel(e);\n };\n }\n\n return pressProps;\n }, [addGlobalListener, isDisabled, preventFocusOnPress, removeAllGlobalListeners, allowTextSelectionOnPress]);\n\n // Remove user-select: none in case component unmounts immediately after pressStart\n // eslint-disable-next-line arrow-body-style\n useEffect(() => {\n return () => {\n if (!allowTextSelectionOnPress) {\n restoreTextSelection(ref.current.target);\n }\n };\n }, [allowTextSelectionOnPress]);\n\n return {\n isPressed: isPressedProp || isPressed,\n pressProps: mergeProps(domProps, pressProps)\n };\n}\n\nfunction isHTMLAnchorLink(target: Element): boolean {\n return target.tagName === 'A' && target.hasAttribute('href');\n}\n\nfunction isValidKeyboardEvent(event: KeyboardEvent, currentTarget: Element): boolean {\n const {key, code} = event;\n const element = currentTarget as HTMLElement;\n const role = element.getAttribute('role');\n // Accessibility for keyboards. Space and Enter only.\n // \"Spacebar\" is for IE 11\n return (\n (key === 'Enter' || key === ' ' || key === 'Spacebar' || code === 'Space') &&\n !((element instanceof HTMLInputElement && !isValidInputKey(element, key)) ||\n element instanceof HTMLTextAreaElement ||\n element.isContentEditable) &&\n // A link with a valid href should be handled natively,\n // unless it also has role='button' and was triggered using Space.\n (!isHTMLAnchorLink(element) || (role === 'button' && key !== 'Enter')) &&\n // An element with role='link' should only trigger with Enter key\n !(role === 'link' && key !== 'Enter')\n );\n}\n\nfunction getTouchFromEvent(event: TouchEvent): Touch | null {\n const {targetTouches} = event;\n if (targetTouches.length > 0) {\n return targetTouches[0];\n }\n return null;\n}\n\nfunction getTouchById(\n event: TouchEvent,\n pointerId: null | number\n): null | Touch {\n const changedTouches = event.changedTouches;\n for (let i = 0; i < changedTouches.length; i++) {\n const touch = changedTouches[i];\n if (touch.identifier === pointerId) {\n return touch;\n }\n }\n return null;\n}\n\nfunction createEvent(target: FocusableElement, e: EventBase): EventBase {\n return {\n currentTarget: target,\n shiftKey: e.shiftKey,\n ctrlKey: e.ctrlKey,\n metaKey: e.metaKey,\n altKey: e.altKey\n };\n}\n\ninterface Rect {\n top: number,\n right: number,\n bottom: number,\n left: number\n}\n\ninterface EventPoint {\n clientX: number,\n clientY: number,\n width?: number,\n height?: number,\n radiusX?: number,\n radiusY?: number\n}\n\nfunction getPointClientRect(point: EventPoint): Rect {\n let offsetX = (point.width / 2) || point.radiusX || 0;\n let offsetY = (point.height / 2) || point.radiusY || 0;\n\n return {\n top: point.clientY - offsetY,\n right: point.clientX + offsetX,\n bottom: point.clientY + offsetY,\n left: point.clientX - offsetX\n };\n}\n\nfunction areRectanglesOverlapping(a: Rect, b: Rect) {\n // check if they cannot overlap on x axis\n if (a.left > b.right || b.left > a.right) {\n return false;\n }\n // check if they cannot overlap on y axis\n if (a.top > b.bottom || b.top > a.bottom) {\n return false;\n }\n return true;\n}\n\nfunction isOverTarget(point: EventPoint, target: Element) {\n let rect = target.getBoundingClientRect();\n let pointRect = getPointClientRect(point);\n return areRectanglesOverlapping(rect, pointRect);\n}\n\nfunction shouldPreventDefault(target: Element) {\n // We cannot prevent default if the target is a draggable element.\n return !(target instanceof HTMLElement) || !target.draggable;\n}\n\nfunction shouldPreventDefaultKeyboard(target: Element, key: string) {\n if (target instanceof HTMLInputElement) {\n return !isValidInputKey(target, key);\n }\n\n if (target instanceof HTMLButtonElement) {\n return target.type !== 'submit';\n }\n\n return true;\n}\n\nconst nonTextInputTypes = new Set([\n 'checkbox',\n 'radio',\n 'range',\n 'color',\n 'file',\n 'image',\n 'button',\n 'submit',\n 'reset'\n]);\n\nfunction isValidInputKey(target: HTMLInputElement, key: string) {\n // Only space should toggle checkboxes and radios, not enter.\n return target.type === 'checkbox' || target.type === 'radio'\n ? key === ' '\n : nonTextInputTypes.has(target.type);\n}\n\nfunction isVirtualPointerEvent(event: PointerEvent) {\n // If the pointer size is zero, then we assume it's from a screen reader.\n // Android TalkBack double tap will sometimes return a event with width and height of 1\n // and pointerType === 'mouse' so we need to check for a specific combination of event attributes.\n // Cannot use \"event.pressure === 0\" as the sole check due to Safari pointer events always returning pressure === 0\n // instead of .5, see https://bugs.webkit.org/show_bug.cgi?id=206216. event.pointerType === 'mouse' is to distingush\n // Talkback double tap from Windows Firefox touch screen press\n return (\n (event.width === 0 && event.height === 0) ||\n (event.width === 1 &&\n event.height === 1 &&\n event.pressure === 0 &&\n event.detail === 0 &&\n event.pointerType === 'mouse'\n )\n );\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {useCallback, useEffect, useRef} from 'react';\n\ninterface GlobalListeners {\n addGlobalListener(el: EventTarget, type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void,\n addGlobalListener(el: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void,\n removeGlobalListener(el: EventTarget, type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void,\n removeGlobalListener(el: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void,\n removeAllGlobalListeners(): void\n}\n\nexport function useGlobalListeners(): GlobalListeners {\n let globalListeners = useRef(new Map());\n let addGlobalListener = useCallback((eventTarget, type, listener, options) => {\n // Make sure we remove the listener after it is called with the `once` option.\n let fn = options?.once ? (...args) => {\n globalListeners.current.delete(listener);\n listener(...args);\n } : listener;\n globalListeners.current.set(listener, {type, eventTarget, fn, options});\n eventTarget.addEventListener(type, listener, options);\n }, []);\n let removeGlobalListener = useCallback((eventTarget, type, listener, options) => {\n let fn = globalListeners.current.get(listener)?.fn || listener;\n eventTarget.removeEventListener(type, fn, options);\n globalListeners.current.delete(listener);\n }, []);\n let removeAllGlobalListeners = useCallback(() => {\n globalListeners.current.forEach((value, key) => {\n removeGlobalListener(value.eventTarget, value.type, key, value.options);\n });\n }, [removeGlobalListener]);\n\n // eslint-disable-next-line arrow-body-style\n useEffect(() => {\n return removeAllGlobalListeners;\n }, [removeAllGlobalListeners]);\n\n return {addGlobalListener, removeGlobalListener, removeAllGlobalListeners};\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from react.\n// Original licensing for the following can be found in the\n// NOTICE file in the root directory of this source tree.\n// See https://github.com/facebook/react/tree/cc7c1aece46a6b69b41958d731e0fd27c94bfc6c/packages/react-interactions\n\nimport {isMac} from '@react-aria/utils';\nimport {isVirtualClick} from './utils';\nimport {useEffect, useState} from 'react';\n\nexport type Modality = 'keyboard' | 'pointer' | 'virtual';\ntype HandlerEvent = PointerEvent | MouseEvent | KeyboardEvent | FocusEvent;\ntype Handler = (modality: Modality, e: HandlerEvent) => void;\nexport type FocusVisibleHandler = (isFocusVisible: boolean) => void;\ninterface FocusVisibleProps {\n /** Whether the element is a text input. */\n isTextInput?: boolean,\n /** Whether the element will be auto focused. */\n autoFocus?: boolean\n}\n\nexport interface FocusVisibleResult {\n /** Whether keyboard focus is visible globally. */\n isFocusVisible: boolean\n}\n\nlet currentModality = null;\nlet changeHandlers = new Set();\nlet hasSetupGlobalListeners = false;\nlet hasEventBeforeFocus = false;\nlet hasBlurredWindowRecently = false;\n\n// Only Tab or Esc keys will make focus visible on text input elements\nconst FOCUS_VISIBLE_INPUT_KEYS = {\n Tab: true,\n Escape: true\n};\n\nfunction triggerChangeHandlers(modality: Modality, e: HandlerEvent) {\n for (let handler of changeHandlers) {\n handler(modality, e);\n }\n}\n\n/**\n * Helper function to determine if a KeyboardEvent is unmodified and could make keyboard focus styles visible.\n */\nfunction isValidKey(e: KeyboardEvent) {\n // Control and Shift keys trigger when navigating back to the tab with keyboard.\n return !(e.metaKey || (!isMac() && e.altKey) || e.ctrlKey || e.key === 'Control' || e.key === 'Shift' || e.key === 'Meta');\n}\n\n\nfunction handleKeyboardEvent(e: KeyboardEvent) {\n hasEventBeforeFocus = true;\n if (isValidKey(e)) {\n currentModality = 'keyboard';\n triggerChangeHandlers('keyboard', e);\n }\n}\n\nfunction handlePointerEvent(e: PointerEvent | MouseEvent) {\n currentModality = 'pointer';\n if (e.type === 'mousedown' || e.type === 'pointerdown') {\n hasEventBeforeFocus = true;\n triggerChangeHandlers('pointer', e);\n }\n}\n\nfunction handleClickEvent(e: MouseEvent) {\n if (isVirtualClick(e)) {\n hasEventBeforeFocus = true;\n currentModality = 'virtual';\n }\n}\n\nfunction handleFocusEvent(e: FocusEvent) {\n // Firefox fires two extra focus events when the user first clicks into an iframe:\n // first on the window, then on the document. We ignore these events so they don't\n // cause keyboard focus rings to appear.\n if (e.target === window || e.target === document) {\n return;\n }\n\n // If a focus event occurs without a preceding keyboard or pointer event, switch to virtual modality.\n // This occurs, for example, when navigating a form with the next/previous buttons on iOS.\n if (!hasEventBeforeFocus && !hasBlurredWindowRecently) {\n currentModality = 'virtual';\n triggerChangeHandlers('virtual', e);\n }\n\n hasEventBeforeFocus = false;\n hasBlurredWindowRecently = false;\n}\n\nfunction handleWindowBlur() {\n // When the window is blurred, reset state. This is necessary when tabbing out of the window,\n // for example, since a subsequent focus event won't be fired.\n hasEventBeforeFocus = false;\n hasBlurredWindowRecently = true;\n}\n\n/**\n * Setup global event listeners to control when keyboard focus style should be visible.\n */\nfunction setupGlobalFocusEvents() {\n if (typeof window === 'undefined' || hasSetupGlobalListeners) {\n return;\n }\n\n // Programmatic focus() calls shouldn't affect the current input modality.\n // However, we need to detect other cases when a focus event occurs without\n // a preceding user event (e.g. screen reader focus). Overriding the focus\n // method on HTMLElement.prototype is a bit hacky, but works.\n let focus = HTMLElement.prototype.focus;\n HTMLElement.prototype.focus = function () {\n hasEventBeforeFocus = true;\n focus.apply(this, arguments);\n };\n\n document.addEventListener('keydown', handleKeyboardEvent, true);\n document.addEventListener('keyup', handleKeyboardEvent, true);\n document.addEventListener('click', handleClickEvent, true);\n\n // Register focus events on the window so they are sure to happen\n // before React's event listeners (registered on the document).\n window.addEventListener('focus', handleFocusEvent, true);\n window.addEventListener('blur', handleWindowBlur, false);\n\n if (typeof PointerEvent !== 'undefined') {\n document.addEventListener('pointerdown', handlePointerEvent, true);\n document.addEventListener('pointermove', handlePointerEvent, true);\n document.addEventListener('pointerup', handlePointerEvent, true);\n } else {\n document.addEventListener('mousedown', handlePointerEvent, true);\n document.addEventListener('mousemove', handlePointerEvent, true);\n document.addEventListener('mouseup', handlePointerEvent, true);\n }\n\n hasSetupGlobalListeners = true;\n}\n\nif (typeof document !== 'undefined') {\n if (document.readyState !== 'loading') {\n setupGlobalFocusEvents();\n } else {\n document.addEventListener('DOMContentLoaded', setupGlobalFocusEvents);\n }\n}\n\n/**\n * If true, keyboard focus is visible.\n */\nexport function isFocusVisible(): boolean {\n return currentModality !== 'pointer';\n}\n\nexport function getInteractionModality(): Modality {\n return currentModality;\n}\n\nexport function setInteractionModality(modality: Modality) {\n currentModality = modality;\n triggerChangeHandlers(modality, null);\n}\n\n/**\n * Keeps state of the current modality.\n */\nexport function useInteractionModality(): Modality {\n setupGlobalFocusEvents();\n\n let [modality, setModality] = useState(currentModality);\n useEffect(() => {\n let handler = () => {\n setModality(currentModality);\n };\n\n changeHandlers.add(handler);\n return () => {\n changeHandlers.delete(handler);\n };\n }, []);\n\n return modality;\n}\n\n/**\n * If this is attached to text input component, return if the event is a focus event (Tab/Escape keys pressed) so that\n * focus visible style can be properly set.\n */\nfunction isKeyboardFocusEvent(isTextInput: boolean, modality: Modality, e: HandlerEvent) {\n return !(isTextInput && modality === 'keyboard' && e instanceof KeyboardEvent && !FOCUS_VISIBLE_INPUT_KEYS[e.key]);\n}\n\n/**\n * Manages focus visible state for the page, and subscribes individual components for updates.\n */\nexport function useFocusVisible(props: FocusVisibleProps = {}): FocusVisibleResult {\n let {isTextInput, autoFocus} = props;\n let [isFocusVisibleState, setFocusVisible] = useState(autoFocus || isFocusVisible());\n useFocusVisibleListener((isFocusVisible) => {\n setFocusVisible(isFocusVisible);\n }, [isTextInput], {isTextInput});\n\n return {isFocusVisible: isFocusVisibleState};\n}\n\n/**\n * Listens for trigger change and reports if focus is visible (i.e., modality is not pointer).\n */\nexport function useFocusVisibleListener(fn: FocusVisibleHandler, deps: ReadonlyArray, opts?: {isTextInput?: boolean}): void {\n setupGlobalFocusEvents();\n\n useEffect(() => {\n let handler = (modality: Modality, e: HandlerEvent) => {\n if (!isKeyboardFocusEvent(opts?.isTextInput, modality, e)) {\n return;\n }\n fn(isFocusVisible());\n };\n changeHandlers.add(handler);\n return () => {\n changeHandlers.delete(handler);\n };\n }, deps);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {BaseEvent} from '@react-types/shared';\nimport {SyntheticEvent} from 'react';\n\n/**\n * This function wraps a React event handler to make stopPropagation the default, and support continuePropagation instead.\n */\nexport function createEventHandler(handler: (e: BaseEvent) => void): (e: T) => void {\n if (!handler) {\n return;\n }\n\n let shouldStopPropagation = true;\n return (e: T) => {\n let event: BaseEvent = {\n ...e,\n preventDefault() {\n e.preventDefault();\n },\n isDefaultPrevented() {\n return e.isDefaultPrevented();\n },\n stopPropagation() {\n console.error('stopPropagation is now the default behavior for events in React Spectrum. You can use continuePropagation() to revert this behavior.');\n },\n continuePropagation() {\n shouldStopPropagation = false;\n }\n };\n\n handler(event);\n\n if (shouldStopPropagation) {\n e.stopPropagation();\n }\n };\n}\n","import { useRef, useCallback } from 'react';\n\nvar updateRef = function updateRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n return;\n }\n ref.current = value;\n};\n\nvar useComposedRef = function useComposedRef(libRef, userRef) {\n var prevUserRef = useRef();\n return useCallback(function (instance) {\n libRef.current = instance;\n\n if (prevUserRef.current) {\n updateRef(prevUserRef.current, null);\n }\n\n prevUserRef.current = userRef;\n\n if (!userRef) {\n return;\n }\n\n updateRef(userRef, instance);\n }, [userRef]);\n};\n\nexport default useComposedRef;\n","import { useLayoutEffect } from 'react';\n\nvar index = useLayoutEffect ;\n\nexport default index;\n","import * as React from 'react';\nimport useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';\n\nvar useLatest = function useLatest(value) {\n var ref = React.useRef(value);\n useIsomorphicLayoutEffect(function () {\n ref.current = value;\n });\n return ref;\n};\n\nexport { useLatest as default };\n","import { useEffect } from 'react';\nimport arePassiveEventsSupported from 'are-passive-events-supported';\nimport useLatest from 'use-latest';\n\nvar MOUSEDOWN = 'mousedown';\nvar TOUCHSTART = 'touchstart';\nvar events = [MOUSEDOWN, TOUCHSTART];\n\nvar getAddOptions = function getAddOptions(event) {\n if (event === TOUCHSTART && arePassiveEventsSupported()) {\n return {\n passive: true\n };\n }\n};\n\nvar currentDocument = document ;\nfunction useOnClickOutside(ref, handler, _temp) {\n var _ref = _temp === void 0 ? {} : _temp,\n _ref$document = _ref.document,\n document = _ref$document === void 0 ? currentDocument : _ref$document;\n\n var handlerRef = useLatest(handler);\n useEffect(function () {\n if (!handler) {\n return;\n }\n\n var listener = function listener(event) {\n if (!ref.current || !handlerRef.current || ref.current.contains(event.target)) {\n return;\n }\n\n handlerRef.current(event);\n };\n\n events.forEach(function (event) {\n document.addEventListener(event, listener, getAddOptions(event));\n });\n return function () {\n events.forEach(function (event) {\n document.removeEventListener(event, listener);\n });\n };\n }, [!handler]);\n}\n\nexport { useOnClickOutside as default };\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","import { __assign } from 'tslib';\n\nvar clamp = function (min, max) { return function (v) {\r\n return Math.max(Math.min(v, max), min);\r\n}; };\r\nvar sanitize = function (v) { return (v % 1 ? Number(v.toFixed(5)) : v); };\r\nvar floatRegex = /(-)?(\\d[\\d\\.]*)/g;\r\nvar colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\\((-?[\\d\\.]+%?[,\\s]+){2,3}\\s*\\/*\\s*[\\d\\.]+%?\\))/gi;\r\nvar singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\\((-?[\\d\\.]+%?[,\\s]+){2,3}\\s*\\/*\\s*[\\d\\.]+%?\\))$/i;\n\nvar number = {\r\n test: function (v) { return typeof v === 'number'; },\r\n parse: parseFloat,\r\n transform: function (v) { return v; }\r\n};\r\nvar alpha = __assign(__assign({}, number), { transform: clamp(0, 1) });\r\nvar scale = __assign(__assign({}, number), { default: 1 });\n\nvar createUnitType = function (unit) { return ({\r\n test: function (v) {\r\n return typeof v === 'string' && v.endsWith(unit) && v.split(' ').length === 1;\r\n },\r\n parse: parseFloat,\r\n transform: function (v) { return \"\" + v + unit; }\r\n}); };\r\nvar degrees = createUnitType('deg');\r\nvar percent = createUnitType('%');\r\nvar px = createUnitType('px');\r\nvar vh = createUnitType('vh');\r\nvar vw = createUnitType('vw');\r\nvar progressPercentage = __assign(__assign({}, percent), { parse: function (v) { return percent.parse(v) / 100; }, transform: function (v) { return percent.transform(v * 100); } });\n\nvar getValueFromFunctionString = function (value) {\r\n return value.substring(value.indexOf('(') + 1, value.lastIndexOf(')'));\r\n};\r\nvar clampRgbUnit = clamp(0, 255);\r\nvar isRgba = function (v) { return v.red !== undefined; };\r\nvar isHsla = function (v) { return v.hue !== undefined; };\r\nfunction getValuesAsArray(value) {\r\n return getValueFromFunctionString(value)\r\n .replace(/(,|\\/)/g, ' ')\r\n .split(/ \\s*/);\r\n}\r\nvar splitColorValues = function (terms) {\r\n return function (v) {\r\n if (typeof v !== 'string')\r\n return v;\r\n var values = {};\r\n var valuesArray = getValuesAsArray(v);\r\n for (var i = 0; i < 4; i++) {\r\n values[terms[i]] =\r\n valuesArray[i] !== undefined ? parseFloat(valuesArray[i]) : 1;\r\n }\r\n return values;\r\n };\r\n};\r\nvar rgbaTemplate = function (_a) {\r\n var red = _a.red, green = _a.green, blue = _a.blue, _b = _a.alpha, alpha = _b === void 0 ? 1 : _b;\r\n return \"rgba(\" + red + \", \" + green + \", \" + blue + \", \" + alpha + \")\";\r\n};\r\nvar hslaTemplate = function (_a) {\r\n var hue = _a.hue, saturation = _a.saturation, lightness = _a.lightness, _b = _a.alpha, alpha = _b === void 0 ? 1 : _b;\r\n return \"hsla(\" + hue + \", \" + saturation + \", \" + lightness + \", \" + alpha + \")\";\r\n};\r\nvar rgbUnit = __assign(__assign({}, number), { transform: function (v) { return Math.round(clampRgbUnit(v)); } });\r\nfunction isColorString(color, colorType) {\r\n return color.startsWith(colorType) && singleColorRegex.test(color);\r\n}\r\nvar rgba = {\r\n test: function (v) { return (typeof v === 'string' ? isColorString(v, 'rgb') : isRgba(v)); },\r\n parse: splitColorValues(['red', 'green', 'blue', 'alpha']),\r\n transform: function (_a) {\r\n var red = _a.red, green = _a.green, blue = _a.blue, _b = _a.alpha, alpha$1 = _b === void 0 ? 1 : _b;\r\n return rgbaTemplate({\r\n red: rgbUnit.transform(red),\r\n green: rgbUnit.transform(green),\r\n blue: rgbUnit.transform(blue),\r\n alpha: sanitize(alpha.transform(alpha$1))\r\n });\r\n }\r\n};\r\nvar hsla = {\r\n test: function (v) { return (typeof v === 'string' ? isColorString(v, 'hsl') : isHsla(v)); },\r\n parse: splitColorValues(['hue', 'saturation', 'lightness', 'alpha']),\r\n transform: function (_a) {\r\n var hue = _a.hue, saturation = _a.saturation, lightness = _a.lightness, _b = _a.alpha, alpha$1 = _b === void 0 ? 1 : _b;\r\n return hslaTemplate({\r\n hue: Math.round(hue),\r\n saturation: percent.transform(sanitize(saturation)),\r\n lightness: percent.transform(sanitize(lightness)),\r\n alpha: sanitize(alpha.transform(alpha$1))\r\n });\r\n }\r\n};\r\nvar hex = __assign(__assign({}, rgba), { test: function (v) { return typeof v === 'string' && isColorString(v, '#'); }, parse: function (v) {\r\n var r = '';\r\n var g = '';\r\n var b = '';\r\n if (v.length > 4) {\r\n r = v.substr(1, 2);\r\n g = v.substr(3, 2);\r\n b = v.substr(5, 2);\r\n }\r\n else {\r\n r = v.substr(1, 1);\r\n g = v.substr(2, 1);\r\n b = v.substr(3, 1);\r\n r += r;\r\n g += g;\r\n b += b;\r\n }\r\n return {\r\n red: parseInt(r, 16),\r\n green: parseInt(g, 16),\r\n blue: parseInt(b, 16),\r\n alpha: 1\r\n };\r\n } });\r\nvar color = {\r\n test: function (v) {\r\n return (typeof v === 'string' && singleColorRegex.test(v)) ||\r\n isRgba(v) ||\r\n isHsla(v);\r\n },\r\n parse: function (v) {\r\n if (rgba.test(v)) {\r\n return rgba.parse(v);\r\n }\r\n else if (hsla.test(v)) {\r\n return hsla.parse(v);\r\n }\r\n else if (hex.test(v)) {\r\n return hex.parse(v);\r\n }\r\n return v;\r\n },\r\n transform: function (v) {\r\n if (isRgba(v)) {\r\n return rgba.transform(v);\r\n }\r\n else if (isHsla(v)) {\r\n return hsla.transform(v);\r\n }\r\n return v;\r\n }\r\n};\n\nvar COLOR_TOKEN = '${c}';\r\nvar NUMBER_TOKEN = '${n}';\r\nvar convertNumbersToZero = function (v) {\r\n return typeof v === 'number' ? 0 : v;\r\n};\r\nvar complex = {\r\n test: function (v) {\r\n if (typeof v !== 'string' || !isNaN(v))\r\n return false;\r\n var numValues = 0;\r\n var foundNumbers = v.match(floatRegex);\r\n var foundColors = v.match(colorRegex);\r\n if (foundNumbers)\r\n numValues += foundNumbers.length;\r\n if (foundColors)\r\n numValues += foundColors.length;\r\n return numValues > 0;\r\n },\r\n parse: function (v) {\r\n var input = v;\r\n var parsed = [];\r\n var foundColors = input.match(colorRegex);\r\n if (foundColors) {\r\n input = input.replace(colorRegex, COLOR_TOKEN);\r\n parsed.push.apply(parsed, foundColors.map(color.parse));\r\n }\r\n var foundNumbers = input.match(floatRegex);\r\n if (foundNumbers) {\r\n parsed.push.apply(parsed, foundNumbers.map(number.parse));\r\n }\r\n return parsed;\r\n },\r\n createTransformer: function (prop) {\r\n var template = prop;\r\n var token = 0;\r\n var foundColors = prop.match(colorRegex);\r\n var numColors = foundColors ? foundColors.length : 0;\r\n if (foundColors) {\r\n for (var i = 0; i < numColors; i++) {\r\n template = template.replace(foundColors[i], COLOR_TOKEN);\r\n token++;\r\n }\r\n }\r\n var foundNumbers = template.match(floatRegex);\r\n var numNumbers = foundNumbers ? foundNumbers.length : 0;\r\n if (foundNumbers) {\r\n for (var i = 0; i < numNumbers; i++) {\r\n template = template.replace(foundNumbers[i], NUMBER_TOKEN);\r\n token++;\r\n }\r\n }\r\n return function (v) {\r\n var output = template;\r\n for (var i = 0; i < token; i++) {\r\n output = output.replace(i < numColors ? COLOR_TOKEN : NUMBER_TOKEN, i < numColors ? color.transform(v[i]) : sanitize(v[i]));\r\n }\r\n return output;\r\n };\r\n },\r\n getAnimatableNone: function (target) {\r\n var parsedTarget = complex.parse(target);\r\n var targetTransformer = complex.createTransformer(target);\r\n return targetTransformer(parsedTarget.map(convertNumbersToZero));\r\n }\r\n};\n\nexport { alpha, color, complex, degrees, hex, hsla, number, percent, progressPercentage, px, rgbUnit, rgba, scale, vh, vw };\n","import { invariant } from 'hey-listen';\n\nvar prevTime = 0;\nvar onNextFrame = typeof window !== 'undefined' && window.requestAnimationFrame !== undefined ? function (callback) {\n return window.requestAnimationFrame(callback);\n} : function (callback) {\n var timestamp = Date.now();\n var timeToCall = Math.max(0, 16.7 - (timestamp - prevTime));\n prevTime = timestamp + timeToCall;\n setTimeout(function () {\n return callback(prevTime);\n }, timeToCall);\n};\n\nvar createStep = function (setRunNextFrame) {\n var processToRun = [];\n var processToRunNextFrame = [];\n var numThisFrame = 0;\n var isProcessing = false;\n var i = 0;\n var cancelled = new WeakSet();\n var toKeepAlive = new WeakSet();\n var renderStep = {\n cancel: function (process) {\n var indexOfCallback = processToRunNextFrame.indexOf(process);\n cancelled.add(process);\n if (indexOfCallback !== -1) {\n processToRunNextFrame.splice(indexOfCallback, 1);\n }\n },\n process: function (frame) {\n var _a;\n isProcessing = true;\n _a = [processToRunNextFrame, processToRun], processToRun = _a[0], processToRunNextFrame = _a[1];\n processToRunNextFrame.length = 0;\n numThisFrame = processToRun.length;\n if (numThisFrame) {\n var process_1;\n for (i = 0; i < numThisFrame; i++) {\n process_1 = processToRun[i];\n process_1(frame);\n if (toKeepAlive.has(process_1) === true && !cancelled.has(process_1)) {\n renderStep.schedule(process_1);\n setRunNextFrame(true);\n }\n }\n }\n isProcessing = false;\n },\n schedule: function (process, keepAlive, immediate) {\n if (keepAlive === void 0) {\n keepAlive = false;\n }\n if (immediate === void 0) {\n immediate = false;\n }\n invariant(typeof process === \"function\", \"Argument must be a function\");\n var addToCurrentBuffer = immediate && isProcessing;\n var buffer = addToCurrentBuffer ? processToRun : processToRunNextFrame;\n cancelled.delete(process);\n if (keepAlive) toKeepAlive.add(process);\n if (buffer.indexOf(process) === -1) {\n buffer.push(process);\n if (addToCurrentBuffer) numThisFrame = processToRun.length;\n }\n }\n };\n return renderStep;\n};\n\nvar maxElapsed = 40;\nvar defaultElapsed = 1 / 60 * 1000;\nvar useDefaultElapsed = true;\nvar willRunNextFrame = false;\nvar isProcessing = false;\nvar frame = {\n delta: 0,\n timestamp: 0\n};\nvar stepsOrder = [\"read\", \"update\", \"preRender\", \"render\", \"postRender\"];\nvar setWillRunNextFrame = function (willRun) {\n return willRunNextFrame = willRun;\n};\nvar steps = /*#__PURE__*/stepsOrder.reduce(function (acc, key) {\n acc[key] = createStep(setWillRunNextFrame);\n return acc;\n}, {});\nvar sync = /*#__PURE__*/stepsOrder.reduce(function (acc, key) {\n var step = steps[key];\n acc[key] = function (process, keepAlive, immediate) {\n if (keepAlive === void 0) {\n keepAlive = false;\n }\n if (immediate === void 0) {\n immediate = false;\n }\n if (!willRunNextFrame) startLoop();\n step.schedule(process, keepAlive, immediate);\n return process;\n };\n return acc;\n}, {});\nvar cancelSync = /*#__PURE__*/stepsOrder.reduce(function (acc, key) {\n acc[key] = steps[key].cancel;\n return acc;\n}, {});\nvar processStep = function (stepId) {\n return steps[stepId].process(frame);\n};\nvar processFrame = function (timestamp) {\n willRunNextFrame = false;\n frame.delta = useDefaultElapsed ? defaultElapsed : Math.max(Math.min(timestamp - frame.timestamp, maxElapsed), 1);\n if (!useDefaultElapsed) defaultElapsed = frame.delta;\n frame.timestamp = timestamp;\n isProcessing = true;\n stepsOrder.forEach(processStep);\n isProcessing = false;\n if (willRunNextFrame) {\n useDefaultElapsed = false;\n onNextFrame(processFrame);\n }\n};\nvar startLoop = function () {\n willRunNextFrame = true;\n useDefaultElapsed = true;\n if (!isProcessing) onNextFrame(processFrame);\n};\nvar getFrameData = function () {\n return frame;\n};\n\nexport default sync;\nexport { cancelSync, getFrameData };\n","import { hsla, rgba, hex, color, complex } from 'style-value-types';\nimport { invariant } from 'hey-listen';\nimport { getFrameData } from 'framesync';\nimport { createAnticipateEasing, createBackIn, createExpoIn, cubicBezier, linear, easeIn, easeOut, easeInOut, circIn, circOut, circInOut, backIn, backOut, backInOut, anticipate, reversed, mirrored } from '@popmotion/easing';\nexport { createAnticipateEasing, createBackIn, createExpoIn, cubicBezier, linear, easeIn, easeOut, easeInOut, circIn, circOut, circInOut, backIn, backOut, backInOut, anticipate, reversed, mirrored } from '@popmotion/easing';\n\nvar zeroPoint = {\r\n x: 0,\r\n y: 0,\r\n z: 0\r\n};\r\nvar isNum = function (v) { return typeof v === 'number'; };\n\nvar radiansToDegrees = (function (radians) { return (radians * 180) / Math.PI; });\n\nvar angle = (function (a, b) {\r\n if (b === void 0) { b = zeroPoint; }\r\n return radiansToDegrees(Math.atan2(b.y - a.y, b.x - a.x));\r\n});\n\nvar applyOffset = (function (from, to) {\r\n var hasReceivedFrom = true;\r\n if (to === undefined) {\r\n to = from;\r\n hasReceivedFrom = false;\r\n }\r\n return function (v) {\r\n if (hasReceivedFrom) {\r\n return v - from + to;\r\n }\r\n else {\r\n from = v;\r\n hasReceivedFrom = true;\r\n return to;\r\n }\r\n };\r\n});\n\nvar curryRange = (function (func) { return function (min, max, v) { return (v !== undefined ? func(min, max, v) : function (cv) { return func(min, max, cv); }); }; });\n\nvar clamp = function (min, max, v) {\r\n return Math.min(Math.max(v, min), max);\r\n};\r\nvar clamp$1 = curryRange(clamp);\n\nvar conditional = (function (check, apply) { return function (v) {\r\n return check(v) ? apply(v) : v;\r\n}; });\n\nvar degreesToRadians = (function (degrees) { return (degrees * Math.PI) / 180; });\n\nvar isPoint = (function (point) {\r\n return point.hasOwnProperty('x') && point.hasOwnProperty('y');\r\n});\n\nvar isPoint3D = (function (point) {\r\n return isPoint(point) && point.hasOwnProperty('z');\r\n});\n\nvar distance1D = function (a, b) { return Math.abs(a - b); };\r\nvar distance = (function (a, b) {\r\n if (b === void 0) { b = zeroPoint; }\r\n if (isNum(a) && isNum(b)) {\r\n return distance1D(a, b);\r\n }\r\n else if (isPoint(a) && isPoint(b)) {\r\n var xDelta = distance1D(a.x, b.x);\r\n var yDelta = distance1D(a.y, b.y);\r\n var zDelta = isPoint3D(a) && isPoint3D(b) ? distance1D(a.z, b.z) : 0;\r\n return Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2) + Math.pow(zDelta, 2));\r\n }\r\n return 0;\r\n});\n\nvar progress = (function (from, to, value) {\r\n var toFromDifference = to - from;\r\n return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;\r\n});\n\nvar mix = (function (from, to, progress) {\r\n return -progress * from + progress * to + from;\r\n});\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\n\nvar mixLinearColor = function (from, to, v) {\r\n var fromExpo = from * from;\r\n var toExpo = to * to;\r\n return Math.sqrt(Math.max(0, v * (toExpo - fromExpo) + fromExpo));\r\n};\r\nvar colorTypes = [hex, rgba, hsla];\r\nvar getColorType = function (v) {\r\n return colorTypes.find(function (type) { return type.test(v); });\r\n};\r\nvar notAnimatable = function (color$$1) {\r\n return \"'\" + color$$1 + \"' is not an animatable color. Use the equivalent color code instead.\";\r\n};\r\nvar mixColor = (function (from, to) {\r\n var fromColorType = getColorType(from);\r\n var toColorType = getColorType(to);\r\n invariant(!!fromColorType, notAnimatable(from));\r\n invariant(!!toColorType, notAnimatable(to));\r\n invariant(fromColorType.transform === toColorType.transform, 'Both colors must be hex/RGBA, OR both must be HSLA.');\r\n var fromColor = fromColorType.parse(from);\r\n var toColor = toColorType.parse(to);\r\n var blended = __assign({}, fromColor);\r\n var mixFunc = fromColorType === hsla ? mix : mixLinearColor;\r\n return function (v) {\r\n for (var key in blended) {\r\n if (key !== 'alpha') {\r\n blended[key] = mixFunc(fromColor[key], toColor[key], v);\r\n }\r\n }\r\n blended.alpha = mix(fromColor.alpha, toColor.alpha, v);\r\n return fromColorType.transform(blended);\r\n };\r\n});\n\nvar combineFunctions = function (a, b) { return function (v) { return b(a(v)); }; };\r\nvar pipe = (function () {\r\n var transformers = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n transformers[_i] = arguments[_i];\r\n }\r\n return transformers.reduce(combineFunctions);\r\n});\n\nvar mixArray = function (from, to) {\r\n var output = from.slice();\r\n var numValues = output.length;\r\n var blendValue = from.map(function (fromThis, i) {\r\n var toThis = to[i];\r\n if (isNum(fromThis)) {\r\n return function (v) { return mix(fromThis, toThis, v); };\r\n }\r\n else if (color.test(fromThis)) {\r\n return mixColor(fromThis, toThis);\r\n }\r\n else {\r\n return mixComplex(fromThis, toThis);\r\n }\r\n });\r\n return function (v) {\r\n for (var i = 0; i < numValues; i++) {\r\n output[i] = blendValue[i](v);\r\n }\r\n return output;\r\n };\r\n};\r\nvar mixComplex = function (from, to) {\r\n var template = complex.createTransformer(from);\r\n var parsedFrom = complex.parse(from);\r\n invariant(from === complex.createTransformer(to)(parsedFrom), \"Complex values '\" + from + \"' and '\" + to + \"' are of different format.\");\r\n return pipe(mixArray(parsedFrom, complex.parse(to)), template);\r\n};\n\nvar mixNumber = function (from, to) { return function (p) { return mix(from, to, p); }; };\r\nfunction detectMixerFactory(v) {\r\n if (typeof v === 'number') {\r\n return mixNumber;\r\n }\r\n if (color.test(v)) {\r\n return mixColor;\r\n }\r\n else {\r\n return mixComplex;\r\n }\r\n}\r\nfunction createMixers(output, ease, customMixer) {\r\n var mixers = [];\r\n var mixerFactory = customMixer || detectMixerFactory(output[0]);\r\n var numMixers = output.length - 1;\r\n for (var i = 0; i < numMixers; i++) {\r\n var mixer = mixerFactory(output[i], output[i + 1]);\r\n if (ease) {\r\n var easingFunction = Array.isArray(ease) ? ease[i] : ease;\r\n mixer = pipe(easingFunction, mixer);\r\n }\r\n mixers.push(mixer);\r\n }\r\n return mixers;\r\n}\r\nfunction fastInterpolate(_a, _b) {\r\n var from = _a[0], to = _a[1];\r\n var mixer = _b[0];\r\n return function (v) { return mixer(progress(from, to, v)); };\r\n}\r\nfunction slowInterpolate(input, mixers) {\r\n var inputLength = input.length;\r\n var lastInputIndex = inputLength - 1;\r\n return function (v) {\r\n var mixerIndex = 0;\r\n var foundMixerIndex = false;\r\n if (v <= input[0]) {\r\n foundMixerIndex = true;\r\n }\r\n else if (v >= input[lastInputIndex]) {\r\n mixerIndex = lastInputIndex - 1;\r\n foundMixerIndex = true;\r\n }\r\n if (!foundMixerIndex) {\r\n var i = 1;\r\n for (; i < inputLength; i++) {\r\n if (input[i] > v || i === lastInputIndex) {\r\n break;\r\n }\r\n }\r\n mixerIndex = i - 1;\r\n }\r\n var progressInRange = progress(input[mixerIndex], input[mixerIndex + 1], v);\r\n return mixers[mixerIndex](progressInRange);\r\n };\r\n}\r\nfunction interpolate(input, output, _a) {\r\n var _b = _a === void 0 ? {} : _a, _c = _b.clamp, clamp = _c === void 0 ? true : _c, ease = _b.ease, mixer = _b.mixer;\r\n var inputLength = input.length;\r\n invariant(inputLength === output.length, 'Both input and output ranges must be the same length');\r\n invariant(!ease || !Array.isArray(ease) || ease.length === inputLength - 1, 'Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values.');\r\n if (input[0] > input[inputLength - 1]) {\r\n input = [].concat(input);\r\n output = [].concat(output);\r\n input.reverse();\r\n output.reverse();\r\n }\r\n var mixers = createMixers(output, ease, mixer);\r\n var interpolator = inputLength === 2\r\n ? fastInterpolate(input, mixers)\r\n : slowInterpolate(input, mixers);\r\n return clamp\r\n ? pipe(clamp$1(input[0], input[inputLength - 1]), interpolator)\r\n : interpolator;\r\n}\n\nvar pointFromVector = (function (origin, angle, distance) {\r\n angle = degreesToRadians(angle);\r\n return {\r\n x: distance * Math.cos(angle) + origin.x,\r\n y: distance * Math.sin(angle) + origin.y\r\n };\r\n});\n\nvar toDecimal = (function (num, precision) {\r\n if (precision === void 0) { precision = 2; }\r\n precision = Math.pow(10, precision);\r\n return Math.round(num * precision) / precision;\r\n});\n\nvar smoothFrame = (function (prevValue, nextValue, duration, smoothing) {\r\n if (smoothing === void 0) { smoothing = 0; }\r\n return toDecimal(prevValue +\r\n (duration * (nextValue - prevValue)) / Math.max(smoothing, duration));\r\n});\n\nvar smooth = (function (strength) {\r\n if (strength === void 0) { strength = 50; }\r\n var previousValue = 0;\r\n var lastUpdated = 0;\r\n return function (v) {\r\n var currentFramestamp = getFrameData().timestamp;\r\n var timeDelta = currentFramestamp !== lastUpdated ? currentFramestamp - lastUpdated : 0;\r\n var newValue = timeDelta\r\n ? smoothFrame(previousValue, v, timeDelta, strength)\r\n : previousValue;\r\n lastUpdated = currentFramestamp;\r\n previousValue = newValue;\r\n return newValue;\r\n };\r\n});\n\nvar snap = (function (points) {\r\n if (typeof points === 'number') {\r\n return function (v) { return Math.round(v / points) * points; };\r\n }\r\n else {\r\n var i_1 = 0;\r\n var numPoints_1 = points.length;\r\n return function (v) {\r\n var lastDistance = Math.abs(points[0] - v);\r\n for (i_1 = 1; i_1 < numPoints_1; i_1++) {\r\n var point = points[i_1];\r\n var distance = Math.abs(point - v);\r\n if (distance === 0)\r\n return point;\r\n if (distance > lastDistance)\r\n return points[i_1 - 1];\r\n if (i_1 === numPoints_1 - 1)\r\n return point;\r\n lastDistance = distance;\r\n }\r\n };\r\n }\r\n});\n\nvar identity = function (v) { return v; };\r\nvar springForce = function (alterDisplacement) {\r\n if (alterDisplacement === void 0) { alterDisplacement = identity; }\r\n return curryRange(function (constant, origin, v) {\r\n var displacement = origin - v;\r\n var springModifiedDisplacement = -(0 - constant + 1) * (0 - alterDisplacement(Math.abs(displacement)));\r\n return displacement <= 0\r\n ? origin + springModifiedDisplacement\r\n : origin - springModifiedDisplacement;\r\n });\r\n};\r\nvar springForceLinear = springForce();\r\nvar springForceExpo = springForce(Math.sqrt);\n\nvar velocityPerFrame = (function (xps, frameDuration) {\r\n return isNum(xps) ? xps / (1000 / frameDuration) : 0;\r\n});\n\nvar velocityPerSecond = (function (velocity, frameDuration) {\r\n return frameDuration ? velocity * (1000 / frameDuration) : 0;\r\n});\n\nvar wrap = function (min, max, v) {\r\n var rangeSize = max - min;\r\n return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;\r\n};\r\nvar wrap$1 = curryRange(wrap);\n\nvar clampProgress = clamp$1(0, 1);\r\nvar steps = (function (steps, direction) {\r\n if (direction === void 0) { direction = 'end'; }\r\n return function (progress) {\r\n progress =\r\n direction === 'end' ? Math.min(progress, 0.999) : Math.max(progress, 0.001);\r\n var expanded = progress * steps;\r\n var rounded = direction === 'end' ? Math.floor(expanded) : Math.ceil(expanded);\r\n return clampProgress(rounded / steps);\r\n };\r\n});\n\nexport { angle, applyOffset, clamp$1 as clamp, conditional, degreesToRadians, distance, interpolate, isPoint, isPoint3D, mix, mixArray, mixColor, mixComplex, pipe, pointFromVector, progress, radiansToDegrees, smooth, smoothFrame, snap, springForce, springForceExpo, springForceLinear, steps, toDecimal, velocityPerFrame, velocityPerSecond, wrap$1 as wrap };\n","import useConstant from 'use-constant';\nexport { default as useConstant } from 'use-constant';\nexport { default as useComposedRef } from 'use-composed-ref';\nimport useLatest from 'use-latest';\nexport { default as useLatest } from 'use-latest';\nexport { default as useOnClickOutside } from 'use-onclickoutside';\nimport usePrevious from 'use-previous';\nexport { default as usePrevious } from 'use-previous';\nimport useSmoothScroll from 'use-smooth-scroll';\nexport { default as useSmoothScroll } from 'use-smooth-scroll';\nimport { useSubscription } from 'use-subscription';\nexport { useSubscription } from 'use-subscription';\nimport { useEffect, useCallback, useState, useMemo, useRef, useContext, createContext } from 'react';\nimport { includes, last, toArray, noop } from '@livechat/data-utils';\nimport { isScrollOnTop, isScrollOnBottom } from '@livechat/dom-utils';\nimport { useFocusWithin } from '@react-aria/interactions';\nimport { useFrame } from 'react-frame-component';\n\n/**\n * Runs React.useEffect with empty deps to call effect only on mount.\n */\n\nfunction useOnMount(effect) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(effect, []);\n}\n\nfunction clamp(min, max, value) {\n return Math.min(Math.max(value, min), max);\n}\n\nfunction sign(value) {\n return value < 0 ? -1 : 1;\n}\n\nfunction handleDeltaValue(newValue, currentValue) {\n var increment = currentValue + newValue / 100;\n return clamp(0, 1, increment);\n}\n\nfunction useAnimatedScrollDelta(scrollingDeltaSource, callback) {\n var callbackRef = useLatest(callback);\n useOnMount(function () {\n var valueX = 0;\n var valueY = 0;\n var directionX = 1;\n var directionY = 1;\n var wheelTimeoutX = 0;\n var wheelTimeoutY = 0;\n var autoAnimateRaf = 0;\n\n var tick = function tick(x, y) {\n valueX = handleDeltaValue(x, valueX);\n valueY = handleDeltaValue(y, valueY);\n callbackRef.current({\n x: valueX,\n y: valueY\n });\n };\n\n var autoAnimate = function autoAnimate(axis) {\n var updateX = (axis === 'x' || axis === 'xy') && valueX > 0 && valueX < 1;\n var updateY = (axis === 'y' || axis === 'xy') && valueY > 0 && valueY < 1;\n\n if (updateX || updateY) {\n var x = updateX ? 5 * directionX : 0;\n var y = updateY ? 5 * directionY : 0;\n tick(x, y);\n autoAnimateRaf = requestAnimationFrame(function () {\n return autoAnimate(axis);\n });\n }\n };\n\n var handleScrollDelta = function handleScrollDelta(_ref) {\n var deltaX = _ref.deltaX,\n deltaY = _ref.deltaY;\n\n if (Math.abs(deltaX) > 8) {\n tick(deltaX, 0);\n directionX = sign(deltaX);\n clearTimeout(wheelTimeoutX);\n wheelTimeoutX = window.setTimeout(function () {\n return autoAnimate('x');\n }, 50);\n }\n\n if (Math.abs(deltaY) > 8) {\n tick(0, deltaY);\n directionY = sign(deltaY);\n clearTimeout(wheelTimeoutY);\n wheelTimeoutY = window.setTimeout(function () {\n return autoAnimate('y');\n }, 50);\n }\n };\n\n var unsubscribeDeltaSource = scrollingDeltaSource.subscribe(handleScrollDelta);\n return function () {\n unsubscribeDeltaSource();\n clearTimeout(wheelTimeoutX);\n clearTimeout(wheelTimeoutY);\n cancelAnimationFrame(autoAnimateRaf);\n };\n });\n}\n\nvar getAncestors = function getAncestors(node, ownerDocument) {\n var ancestors = new Set();\n var current = node;\n\n while (current = current.parentElement) {\n if (ownerDocument.body === current) {\n return ancestors;\n }\n\n ancestors.add(current);\n }\n\n return ancestors;\n};\n\nvar ariaHide = function ariaHide(elements, options) {\n elements.forEach(function (element) {\n if (element === options.modalElement) {\n return;\n }\n\n if (!options.ancestors.has(element)) {\n var originalValue = element.getAttribute('aria-hidden');\n options.originalValues.set(element, originalValue);\n element.setAttribute('aria-hidden', 'true');\n return;\n }\n\n if (!element.children) {\n // IE11 doesn't support .children on SVG elements\n return;\n }\n\n ariaHide([].slice.call(element.children), options);\n });\n};\n\nvar useAriaIsolation = function useAriaIsolation(ref) {\n useEffect(function () {\n if (!ref) {\n return;\n }\n\n var modalElement = ref.current;\n var ownerDocument = modalElement.ownerDocument || document;\n var ancestors = getAncestors(modalElement, ownerDocument);\n var originalValues = new Map();\n ariaHide([].slice.call(ownerDocument.body.children), {\n ancestors: ancestors,\n originalValues: originalValues,\n modalElement: modalElement\n });\n return function () {\n originalValues.forEach(function (originalValue, element) {\n if (originalValue === null) {\n element.removeAttribute('aria-hidden');\n return;\n }\n\n element.setAttribute('aria-hidden', originalValue);\n });\n };\n }, [ref]);\n};\n\nfunction useDocumentEvent(type, listener, options) {\n useEffect(function () {\n document.addEventListener(type, listener, options);\n return function () {\n return document.removeEventListener(type, listener, options);\n };\n }, [type, listener, options]);\n}\n\nvar useEventPreventDefault = function useEventPreventDefault(type, elemRef) {\n useEffect(function () {\n var elem = elemRef.current;\n\n if (elem) {\n var handleTouchMove = function handleTouchMove(event) {\n event.preventDefault();\n };\n\n elem.addEventListener(type, handleTouchMove, {\n passive: false\n });\n return function () {\n return elem.removeEventListener('touchmove', handleTouchMove);\n };\n }\n }, [type, elemRef]);\n};\n\nvar consumersCount = 0;\nvar focusType = null;\n\nvar setKeyboardType = function setKeyboardType() {\n focusType = 'keyboard';\n};\n\nvar setClickType = function setClickType() {\n focusType = 'click';\n};\n\nvar useFocusTypeTracking = function useFocusTypeTracking(IframeContext) {\n var contextDocument = (IframeContext == null ? void 0 : IframeContext.document) || document;\n useEffect(function () {\n if (consumersCount === 0) {\n contextDocument.addEventListener('keydown', setKeyboardType, true);\n contextDocument.addEventListener('mousedown', setClickType, true);\n contextDocument.addEventListener('touchstart', setClickType, true);\n }\n\n consumersCount++;\n return function () {\n consumersCount--;\n\n if (consumersCount > 0) {\n return;\n }\n\n focusType = null;\n contextDocument.removeEventListener('keydown', setKeyboardType, true);\n contextDocument.removeEventListener('mousedown', setClickType, true);\n contextDocument.removeEventListener('touchstart', setClickType, true);\n };\n }, [contextDocument]);\n return useCallback(function () {\n return focusType;\n }, []);\n};\n\nvar useHover = function useHover(initialValue) {\n if (initialValue === void 0) {\n initialValue = false;\n }\n\n var _React$useState = useState(initialValue),\n isHovered = _React$useState[0],\n setIsHovered = _React$useState[1];\n\n var hoverProps = useMemo(function () {\n return {\n onMouseEnter: function onMouseEnter() {\n return setIsHovered(true);\n },\n onMouseLeave: function onMouseLeave() {\n return setIsHovered(false);\n }\n };\n }, []);\n return [isHovered, hoverProps];\n};\n\nfunction useHTMLElementEvent(element, type, listener, options) {\n useEffect(function () {\n element.addEventListener(type, listener, options);\n return function () {\n return element.removeEventListener(type, listener, options);\n };\n }, [element, type, listener, options]);\n}\n\nvar useKeyboardTriggeredClick = function useKeyboardTriggeredClick(onClick) {\n var handleKeyPress = useCallback(function (_ref) {\n var key = _ref.key;\n\n if (key === 'Enter' || key === ' ') {\n onClick();\n }\n }, [onClick]);\n return {\n onKeyPress: handleKeyPress\n };\n};\n\nfunction useOnGlobalKeydown(keyCode, handler) {\n var handlerRef = useLatest(handler);\n var hasHandler = !!handler;\n useEffect(function () {\n if (!hasHandler) {\n return;\n }\n\n var listener = function listener(event) {\n if (event.keyCode !== keyCode || !handlerRef.current) {\n return;\n }\n\n handlerRef.current(event);\n };\n\n document.addEventListener('keydown', listener);\n return function () {\n return document.removeEventListener('keydown', listener);\n };\n }, [keyCode, hasHandler, handlerRef]);\n}\n\n/**\n * Runs React.useEffect with empty deps to call effect only on unmount.\n */\n\nfunction useOnUnmount(effect) {\n var effectRef = useLatest(effect);\n useEffect(function () {\n return function () {\n return effectRef.current();\n };\n }, [effectRef]);\n}\n\nvar useOnUpdate = function useOnUpdate(callback, inputs) {\n var isMounted = useRef(false);\n useEffect(function () {\n if (!isMounted.current) {\n isMounted.current = true;\n return;\n }\n\n callback(); // eslint-disable-next-line react-hooks/exhaustive-deps\n }, inputs);\n};\n\nvar usePostponedToUpdateCallback = function usePostponedToUpdateCallback(callback) {\n var scheduledRef = useRef(false);\n var latestCallbackRef = useLatest(callback);\n useEffect(function () {\n if (scheduledRef.current) {\n scheduledRef.current = false;\n latestCallbackRef.current();\n }\n });\n return useCallback(function () {\n scheduledRef.current = true;\n }, []);\n};\n\nvar isBrowser = typeof document !== 'undefined';\nvar supportsPassiveEvents;\n\nfunction arePassiveEventsSupported() {\n if (supportsPassiveEvents !== undefined) {\n return supportsPassiveEvents;\n }\n\n if (!isBrowser) {\n supportsPassiveEvents = false;\n return false;\n }\n\n var passive = false;\n var options = {\n // @ts-ignore: this is a temporary object, it doesn't have to return anything\n get passive() {\n passive = true;\n }\n\n };\n\n var noop = function noop() {};\n\n window.addEventListener('t', noop, options);\n window.removeEventListener('t', noop, options);\n supportsPassiveEvents = passive;\n return passive;\n}\n\n/* eslint-disable react-hooks/exhaustive-deps */\nvar DURATION_ZERO = {\n duration: 0\n};\nvar ARE_PASSIVE_EVENTS_SUPPORTED = arePassiveEventsSupported();\nvar SCROLL_KEY_CODES = ['End', 'Home', 'Space', 'PageUp', 'PageDown', 'ArrowUp', 'ArrowDown']; // Currently this hook is not handling resize of scrollable list container.\n// It will be nice improvement for the future to observe list resize and recalculate scroll deps.\n\nfunction useScrollableChatList(listRef, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n firstItemKey = _options.firstItemKey,\n lastItemKey = _options.lastItemKey,\n _options$topThreshold = _options.topThreshold,\n topThreshold = _options$topThreshold === void 0 ? 20 : _options$topThreshold,\n _options$bottomThresh = _options.bottomThreshold,\n bottomThreshold = _options$bottomThresh === void 0 ? 20 : _options$bottomThresh,\n initialScrollTop = _options.initialScrollTop,\n onIsUserScrollingChanged = _options.onIsUserScrollingChanged,\n onIsScrolledToTopChanged = _options.onIsScrolledToTopChanged,\n onIsScrolledToBottomChanged = _options.onIsScrolledToBottomChanged,\n onScrollDeltaChanged = _options.onScrollDeltaChanged,\n _options$isScrollingC = _options.isScrollingChangedTimeout,\n isScrollingChangedTimeout = _options$isScrollingC === void 0 ? 300 : _options$isScrollingC;\n var prevScrollTopRef = useRef(0);\n var prevScrollHeightRef = useRef(0);\n var isInitializedRef = useRef(false);\n var isOnTopRef = useRef(false);\n var isOnBottomRef = useRef(false);\n var isProgramaticScrollingRef = useRef(false);\n var scrollTargetNode = useRef(null);\n var isUserScrollingRef = useRef({\n timeout: 0,\n value: false\n });\n var lastScrollToBottomRef = useRef('none');\n\n var _scrollTo = useSmoothScroll('y', listRef);\n\n var scrollTo = useCallback(function () {\n isProgramaticScrollingRef.current = true;\n\n _scrollTo.apply(void 0, arguments);\n }, [_scrollTo]);\n var prevFirstItemKey = usePrevious(firstItemKey);\n var prevLastItemKey = usePrevious(lastItemKey);\n var handleUserScroll = useCallback(function () {\n isProgramaticScrollingRef.current = false;\n }, []);\n var getIsOnTop = useCallback(function () {\n return isOnTopRef.current;\n }, []);\n var getIsOnBottom = useCallback(function () {\n return isOnBottomRef.current;\n }, []);\n var scrollToTop = useCallback(function (options) {\n return scrollTo(0, options);\n }, [_scrollTo]);\n var scrollToBottom = useCallback(function (options) {\n if (listRef.current) {\n var _listRef$current = listRef.current,\n scrollHeight = _listRef$current.scrollHeight,\n clientHeight = _listRef$current.clientHeight;\n scrollTo(scrollHeight - clientHeight, options);\n lastScrollToBottomRef.current = options && options.duration === 0 ? 'instant' : 'animated';\n }\n }, [listRef, scrollTo]);\n var setScrollTargetNode = useCallback(function (node) {\n return scrollTargetNode.current = node;\n }, []);\n var getIsScrollable = useCallback(function () {\n return !!listRef.current && listRef.current.scrollHeight > listRef.current.clientHeight;\n }, [listRef]);\n var updateIsUserScrolling = useCallback(function () {\n if (!isUserScrollingRef.current.value) {\n isUserScrollingRef.current.value = true;\n onIsUserScrollingChanged && onIsUserScrollingChanged(isUserScrollingRef.current.value);\n }\n\n clearTimeout(isUserScrollingRef.current.timeout);\n isUserScrollingRef.current.timeout = window.setTimeout(function () {\n if (isUserScrollingRef.current.value) {\n isUserScrollingRef.current.value = false;\n onIsUserScrollingChanged && onIsUserScrollingChanged(isUserScrollingRef.current.value);\n }\n }, isScrollingChangedTimeout);\n }, [isScrollingChangedTimeout]);\n var handleScroll = useCallback(function () {\n var node = listRef.current;\n var scrollTop = node.scrollTop,\n scrollHeight = node.scrollHeight;\n var isScrollingUp = prevScrollTopRef.current > scrollTop;\n var isScrollingDown = prevScrollTopRef.current < scrollTop;\n var isNotScrolling = prevScrollTopRef.current === scrollTop;\n var gotDownsized = scrollHeight < prevScrollHeightRef.current;\n var gotUpsized = scrollHeight > prevScrollHeightRef.current;\n var scrollDelta = prevScrollTopRef.current - scrollTop;\n var isMinimalScrollHeightForAnimation = scrollHeight > window.innerHeight * 1.5;\n prevScrollTopRef.current = scrollTop;\n prevScrollHeightRef.current = scrollHeight;\n\n if (getIsScrollable() && !isProgramaticScrollingRef.current) {\n updateIsUserScrolling();\n }\n\n if (isNotScrolling && isInitializedRef.current) {\n return;\n }\n\n if (lastScrollToBottomRef.current === 'instant' || lastScrollToBottomRef.current === 'animated' && isOnBottomRef.current) {\n requestAnimationFrame(function () {\n scrollToBottom({\n duration: 0\n });\n lastScrollToBottomRef.current = 'none';\n });\n }\n\n var keepIsOnTop = isOnTopRef.current && isScrollingUp;\n var keepIsOnBottom = isOnBottomRef.current && (isScrollingDown || gotDownsized || gotUpsized);\n var isOnTop = keepIsOnTop || isScrollOnTop(node, topThreshold);\n var isOnBottom = keepIsOnBottom || isScrollOnBottom(node, bottomThreshold);\n\n if (onIsScrolledToTopChanged) {\n if (!isOnTopRef.current && isOnTop) {\n onIsScrolledToTopChanged(true);\n } else if (isOnTopRef.current && !isOnTop) {\n onIsScrolledToTopChanged(false);\n }\n }\n\n if (onIsScrolledToBottomChanged) {\n if (!isOnBottomRef.current && isOnBottom) {\n onIsScrolledToBottomChanged(true);\n } else if (isOnBottomRef.current && !isOnBottom) {\n onIsScrolledToBottomChanged(false);\n }\n }\n\n isOnTopRef.current = isOnTop;\n isOnBottomRef.current = isOnBottom;\n\n if (!gotUpsized && !isOnTopRef.current && onScrollDeltaChanged && !isOnBottomRef.current && isInitializedRef.current && isUserScrollingRef.current && ARE_PASSIVE_EVENTS_SUPPORTED && !isProgramaticScrollingRef.current && isMinimalScrollHeightForAnimation) {\n onScrollDeltaChanged({\n deltaX: 0,\n deltaY: scrollDelta / 2\n });\n }\n }, [onIsScrolledToTopChanged, onIsScrolledToBottomChanged, updateIsUserScrolling]);\n var handleKeydown = useCallback(function (event) {\n if (includes(event.key, SCROLL_KEY_CODES)) {\n handleUserScroll();\n }\n }, [handleUserScroll]);\n\n var handleScrollTargetNode = function handleScrollTargetNode() {\n scrollTo(scrollTargetNode.current.offsetTop, DURATION_ZERO);\n scrollTargetNode.current = null;\n };\n\n var handleFirstItemKeyChanged = function handleFirstItemKeyChanged() {\n var _ref = listRef.current,\n scrollHeight = _ref.scrollHeight;\n var prevDistanceFromBottom = prevScrollHeightRef.current - prevScrollTopRef.current;\n var preservedScrollTarget = scrollHeight - prevDistanceFromBottom;\n scrollTo(preservedScrollTarget, DURATION_ZERO);\n };\n\n var handleLastItemKeyChanged = function handleLastItemKeyChanged() {\n if (isOnBottomRef.current) {\n scrollToBottom();\n }\n };\n\n var handleMount = function handleMount() {\n if (scrollTargetNode.current) {\n handleScrollTargetNode();\n } else if (typeof initialScrollTop === 'number') {\n scrollTo(initialScrollTop, DURATION_ZERO);\n } else {\n scrollTo(listRef.current.scrollHeight, DURATION_ZERO);\n }\n\n handleScroll();\n isInitializedRef.current = true;\n };\n\n var handleUpdate = function handleUpdate() {\n if (scrollTargetNode.current) {\n handleScrollTargetNode();\n } else {\n if (prevFirstItemKey !== firstItemKey) {\n handleFirstItemKeyChanged();\n }\n\n if (prevLastItemKey !== lastItemKey) {\n handleLastItemKeyChanged();\n }\n }\n };\n\n useDocumentEvent('keydown', handleKeydown);\n useEffect(function () {\n if (isInitializedRef.current === false) {\n handleMount();\n } else {\n handleUpdate();\n }\n });\n useEffect(function () {\n if (listRef.current) {\n var list = listRef.current;\n list.addEventListener('scroll', handleScroll, ARE_PASSIVE_EVENTS_SUPPORTED ? {\n passive: true\n } : undefined);\n return function () {\n return list.removeEventListener('scroll', handleScroll);\n };\n }\n }, [listRef, handleScroll]);\n return {\n scrollTo: scrollTo,\n scrollToTop: scrollToTop,\n scrollToBottom: scrollToBottom,\n getIsOnTop: getIsOnTop,\n getIsOnBottom: getIsOnBottom,\n getIsScrollable: getIsScrollable,\n setScrollTargetNode: setScrollTargetNode,\n onWheel: handleUserScroll,\n onTouchStart: handleUserScroll\n };\n}\n\nvar useStreamState = function useStreamState(stream) {\n return useSubscription({\n getCurrentValue: stream.get,\n subscribe: stream.subscribe\n });\n};\n\nvar useStreamValue = function useStreamValue(initialValue) {\n return useConstant(function () {\n var value = initialValue;\n var subscribed = [];\n return {\n subscribe: function subscribe(callback) {\n subscribed.push(callback);\n return function () {\n subscribed.splice(subscribed.indexOf(callback), 1);\n };\n },\n next: function next(_value) {\n value = _value;\n subscribed.forEach(function (cb) {\n return cb(_value);\n });\n },\n get: function get() {\n return value;\n }\n };\n });\n};\n\nvar useTimeout = function useTimeout(callback, timeout) {\n useEffect(function () {\n var id = setTimeout(callback, timeout);\n return function () {\n return clearTimeout(id);\n };\n }, [callback, timeout]);\n};\n\nfunction useToggle(initialValue) {\n var _React$useState = useState(initialValue),\n value = _React$useState[0],\n setValue = _React$useState[1];\n\n var toggle = useCallback(function () {\n setValue(function (v) {\n return !v;\n });\n }, []);\n return [value, toggle];\n}\n\nvar cache = new Map();\nvar Context = createContext(cache);\nvar MemoryCacheProvider = Context.Provider;\nfunction useInMemoryCache(id) {\n var ctx = useContext(Context);\n\n if (ctx.has(id)) {\n return ctx.get(id);\n }\n\n var ref = {};\n var entry = {\n get: function get() {\n return ref.value;\n },\n set: function set(value) {\n return ref.value = value;\n },\n clear: function clear() {\n return delete ref.value;\n },\n destroy: function destroy() {\n return ctx[\"delete\"](id);\n }\n };\n ctx.set(id, entry);\n return entry;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) {\n var it;\n\n if (typeof Symbol === \"undefined\" || o[Symbol.iterator] == null) {\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n return function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n\n it = o[Symbol.iterator]();\n return it.next.bind(it);\n}\n\nvar ROLE_ROW_SELECTOR = '[role=\"row\"]';\nvar ROLE_GRID_CELL_SELECTOR = '[role=\"gridcell\"]';\nvar FOCUSABLE_ELEMENTS_SELECTOR = 'a, button, input, textarea, select';\n\nvar isInInput = function isInInput(event) {\n var _target$attributes$ty, _target$attributes$ty2;\n\n var target = event.target;\n return target.tagName === 'TEXTAREA' || target.tagName === 'INPUT' && ((_target$attributes$ty = target.attributes['type']) == null ? void 0 : _target$attributes$ty.value) === 'text' || target.tagName === 'INPUT' && ((_target$attributes$ty2 = target.attributes['type']) == null ? void 0 : _target$attributes$ty2.value) === 'email';\n};\n\nvar isInMenu = function isInMenu(event) {\n var _event$target$attribu;\n\n return ['menu', 'menuitem'].includes((_event$target$attribu = event.target.attributes.getNamedItem('role')) == null ? void 0 : _event$target$attribu.value);\n};\n\nvar MutationObserverConstructor = window.MutationObserver || window['WebKitMutationObserver'];\nfunction useRovingTabIndex(_ref) {\n var mainElementRef = _ref.mainElementRef,\n itemsCount = _ref.itemsCount,\n _ref$startAt = _ref.startAt,\n startAt = _ref$startAt === void 0 ? 'last' : _ref$startAt,\n _ref$tableEdgeReached = _ref.tableEdgeReached,\n tableEdgeReached = _ref$tableEdgeReached === void 0 ? noop : _ref$tableEdgeReached;\n\n var _React$useState = useState(itemsCount),\n defferedItemsCount = _React$useState[0],\n setDefferedItemsCount = _React$useState[1];\n\n var trapRef = useRef(false);\n var isCellActiveRef = useRef(false);\n var lastTopElementRef = useRef(null);\n var lastRowRef = useRef(null);\n var lastCellRef = useRef(null);\n useDocumentEvent('keydown', function (event) {\n if (event.key === 'Tab') {\n trapRef.current = true;\n }\n });\n useDocumentEvent('keyup', function (event) {\n if (event.key === 'Tab') {\n trapRef.current = false;\n }\n });\n\n var getAllFocusableElements = function getAllFocusableElements(element) {\n return element ? toArray(element.querySelectorAll(FOCUSABLE_ELEMENTS_SELECTOR)) : [];\n };\n\n var selectStartElement = useCallback(function (elements) {\n return startAt === 'first' ? elements[0] : last(elements);\n }, [startAt]);\n var setupRovingTabIndex = useCallback(function () {\n var pickTopElement = function pickTopElement(element, direction) {\n var sibling = element[direction + \"Sibling\"];\n\n if (sibling) {\n return sibling.querySelector(ROLE_GRID_CELL_SELECTOR) ? sibling : pickTopElement(sibling, direction);\n } else {\n return null;\n }\n };\n\n var cellMutationObserver = new MutationObserverConstructor(function () {\n if (!isCellActiveRef.current && !lastCellRef.current.contains(document.activeElement)) {\n return;\n }\n\n unselectCell(lastCellRef.current);\n var elements = getAllFocusableElements(lastCellRef.current);\n elements.forEach(function (element) {\n element.tabIndex = 0;\n element.addEventListener('blur', handleElementBlur);\n });\n selectCell(lastCellRef.current, false);\n\n if (elements.length && !lastCellRef.current.contains(document.activeElement)) {\n elements[0].focus();\n }\n });\n var mainElementMutationObserver = new MutationObserverConstructor(function (mutationRecords) {\n for (var _iterator = _createForOfIteratorHelperLoose(mutationRecords), _step; !(_step = _iterator()).done;) {\n var record = _step.value;\n\n for (var _iterator2 = _createForOfIteratorHelperLoose(toArray(record.removedNodes)), _step2; !(_step2 = _iterator2()).done;) {\n var removedNode = _step2.value;\n\n if (removedNode === lastCellRef.current || removedNode.contains(lastCellRef.current)) {\n var _last, _mainElementRef$curre;\n\n var topElement = pickTopElement(record, 'next') || pickTopElement(record, 'previous') || ((_last = last(toArray(((_mainElementRef$curre = mainElementRef.current) == null ? void 0 : _mainElementRef$curre.querySelectorAll(ROLE_ROW_SELECTOR)) || []))) == null ? void 0 : _last.parentElement);\n\n if (topElement) {\n cellMutationObserver.disconnect();\n lastTopElementRef.current = topElement;\n lastRowRef.current = topElement.querySelector(ROLE_ROW_SELECTOR);\n lastCellRef.current = topElement.querySelector(ROLE_GRID_CELL_SELECTOR);\n selectCell(lastCellRef.current);\n }\n\n return;\n }\n }\n }\n });\n\n var handleElementBlur = function handleElementBlur(event) {\n var isLastCellATarget = event.target === lastCellRef.current;\n var isLastCellARelatedTarget = event.relatedTarget === lastCellRef.current;\n var containsEventTarget = lastCellRef.current.contains(event.target);\n var containsEventRelatedTarget = lastCellRef.current.contains(event.relatedTarget);\n\n if (trapRef.current && event.relatedTarget && !isLastCellATarget && (!containsEventRelatedTarget || isLastCellARelatedTarget)) {\n event.preventDefault();\n requestAnimationFrame(function () {\n return event.target.focus();\n });\n return;\n }\n\n if (!containsEventTarget || containsEventRelatedTarget) {\n return;\n }\n\n getOutOfCell();\n };\n\n var getOutOfCell = function getOutOfCell() {\n var elements = getAllFocusableElements(lastCellRef.current);\n elements.forEach(function (element) {\n element.tabIndex = -1;\n element.removeEventListener('blur', handleElementBlur);\n });\n };\n\n var getIntoCell = function getIntoCell() {\n var elements = getAllFocusableElements(lastCellRef.current).filter(function (element) {\n return !element['disabled'];\n });\n elements.forEach(function (element) {\n element.tabIndex = 0;\n element.addEventListener('blur', handleElementBlur);\n });\n\n if (elements.length) {\n elements[0].focus();\n }\n\n isCellActiveRef.current = true;\n };\n\n var handleCellKeydown = function handleCellKeydown(event) {\n if (event.key === ' ' && event.target === lastCellRef.current) {\n event.preventDefault();\n }\n };\n\n var handleCellKeyup = function handleCellKeyup(event) {\n switch (event.key) {\n case ' ': // space\n\n case 'Enter':\n if (event.target === lastCellRef.current) {\n event.preventDefault();\n getIntoCell();\n }\n\n return;\n\n case 'Escape':\n event.preventDefault();\n getOutOfCell();\n requestAnimationFrame(function () {\n return lastCellRef.current.focus();\n });\n return;\n }\n };\n\n var selectCell = function selectCell(cell, focus) {\n if (focus === void 0) {\n focus = true;\n }\n\n cell.tabIndex = 0;\n\n if (focus) {\n cell.focus();\n }\n\n cell.addEventListener('keyup', handleCellKeyup);\n cell.addEventListener('keydown', handleCellKeydown);\n cell.addEventListener('blur', handleElementBlur);\n cellMutationObserver.observe(cell, {\n childList: true,\n subtree: true\n });\n };\n\n var unselectCell = function unselectCell(cell) {\n cell.tabIndex = -1;\n cell.removeEventListener('keyup', handleCellKeyup);\n cell.removeEventListener('keydown', handleCellKeydown);\n cell.removeEventListener('blur', handleElementBlur);\n cellMutationObserver.disconnect();\n };\n\n var findCell = function findCell(direction) {\n var siblingPropName = direction + \"ElementSibling\";\n\n if (!lastRowRef.current || !lastTopElementRef.current || !lastRowRef.current[siblingPropName] && !lastTopElementRef.current[siblingPropName]) {\n tableEdgeReached(direction);\n return;\n }\n\n var currentCell = null;\n var currentRow = lastRowRef.current;\n var currentTopElement = lastTopElementRef.current;\n\n while (!currentCell) {\n if (currentRow && currentRow[siblingPropName]) {\n currentRow = currentRow[siblingPropName];\n currentCell = currentRow.querySelector(ROLE_GRID_CELL_SELECTOR);\n } else if (currentTopElement && currentTopElement[siblingPropName]) {\n currentTopElement = currentTopElement[siblingPropName];\n\n if (currentTopElement.attributes['role'] && currentTopElement.attributes['role'].value === 'row') {\n currentRow = currentTopElement;\n } else {\n var rows = currentTopElement.querySelectorAll(ROLE_ROW_SELECTOR);\n currentRow = direction === 'previous' ? selectStartElement(rows) : rows[0];\n }\n\n currentCell = currentRow ? currentRow.querySelector(ROLE_GRID_CELL_SELECTOR) : null;\n } else {\n tableEdgeReached(direction);\n return;\n }\n }\n\n if (currentTopElement !== lastTopElementRef.current) {\n lastTopElementRef.current = currentTopElement;\n }\n\n if (currentRow !== lastRowRef.current) {\n lastRowRef.current = currentRow;\n }\n\n if (currentCell !== lastCellRef.current) {\n unselectCell(lastCellRef.current);\n selectCell(currentCell);\n lastCellRef.current = currentCell;\n }\n };\n\n var handleMainElementKeydown = function handleMainElementKeydown(event) {\n if (isInInput(event)) {\n event.stopPropagation();\n return;\n }\n\n if (isInMenu(event)) {\n return;\n }\n\n switch (event.key) {\n case 'ArrowUp':\n case 'ArrowLeft':\n event.preventDefault();\n findCell('previous');\n return;\n\n case 'ArrowDown':\n case 'ArrowRight':\n event.preventDefault();\n findCell('next');\n return;\n\n default:\n return;\n }\n };\n\n if (lastCellRef.current) {\n selectCell(lastCellRef.current, false);\n }\n\n var mainElement = mainElementRef.current;\n mainElement.addEventListener('keydown', handleMainElementKeydown);\n mainElementMutationObserver.observe(mainElement, {\n childList: true,\n subtree: true\n });\n return function () {\n cellMutationObserver.disconnect();\n mainElement.removeEventListener('keydown', handleMainElementKeydown);\n mainElementMutationObserver.disconnect();\n };\n }, [lastCellRef, mainElementRef, lastRowRef, lastTopElementRef, tableEdgeReached, selectStartElement]);\n useEffect(function () {\n var timeout = setTimeout(function () {\n return setDefferedItemsCount(itemsCount);\n }, 100);\n return function () {\n return clearTimeout(timeout);\n };\n }, [itemsCount]);\n useEffect(function () {\n if (!mainElementRef.current || !mainElementRef.current.children.length) {\n return;\n }\n\n mainElementRef.current.tabIndex = -1;\n var isIndexActive = mainElementRef.current.contains(document.activeElement);\n var allFocusableElements = getAllFocusableElements(mainElementRef.current);\n allFocusableElements.forEach(function (element) {\n element.tabIndex = -1;\n });\n toArray(mainElementRef.current.querySelectorAll(ROLE_GRID_CELL_SELECTOR)).forEach(function (element) {\n if (!isIndexActive || element !== lastCellRef.current) {\n element.tabIndex = -1;\n }\n });\n var lastChild = selectStartElement(toArray(mainElementRef.current.children));\n var lastChildCell = lastChild ? lastChild.querySelector(ROLE_GRID_CELL_SELECTOR) : null;\n var lastChildFocusableElements = getAllFocusableElements(lastChildCell);\n var hasLastChildCellAutofocus = lastChildCell && lastChildCell !== document.activeElement && lastChildCell.contains(document.activeElement);\n\n var unlockLastChildFocusableElements = function unlockLastChildFocusableElements() {\n return lastChildFocusableElements.forEach(function (element) {\n element.tabIndex = 0;\n });\n };\n\n if (hasLastChildCellAutofocus) {\n unlockLastChildFocusableElements();\n } else {\n lastChildFocusableElements.forEach(function (element) {\n element.addEventListener('focus', unlockLastChildFocusableElements);\n });\n }\n\n if (!isIndexActive || hasLastChildCellAutofocus) {\n lastTopElementRef.current = selectStartElement(toArray(mainElementRef.current.children));\n\n if (!lastTopElementRef.current) {\n return;\n }\n\n var roleAttribute = lastTopElementRef.current.attributes['role'];\n lastRowRef.current = roleAttribute && roleAttribute.value === 'row' ? lastTopElementRef.current : selectStartElement(toArray(lastTopElementRef.current.querySelectorAll(ROLE_ROW_SELECTOR)));\n\n if (lastTopElementRef.current.attributes['role'] && lastTopElementRef.current.attributes['role'].value === 'row') {\n lastRowRef.current = lastTopElementRef.current;\n } else {\n lastRowRef.current = selectStartElement(toArray(lastTopElementRef.current.querySelectorAll(ROLE_ROW_SELECTOR)));\n }\n\n if (!lastRowRef.current) {\n return;\n }\n\n lastCellRef.current = lastRowRef.current.querySelector(ROLE_GRID_CELL_SELECTOR);\n\n if (!lastCellRef.current) {\n return;\n }\n }\n\n var cleanupRovingTabIndex = setupRovingTabIndex();\n return function () {\n cleanupRovingTabIndex();\n lastChildFocusableElements.forEach(function (element) {\n element.removeEventListener('focus', unlockLastChildFocusableElements);\n });\n };\n }, [lastCellRef, lastRowRef, lastTopElementRef, mainElementRef, setupRovingTabIndex, defferedItemsCount, selectStartElement]);\n}\n\nvar useDefferedBeforeUnloadingState = function useDefferedBeforeUnloadingState(preventDefault, timeout) {\n if (preventDefault === void 0) {\n preventDefault = false;\n }\n\n if (timeout === void 0) {\n timeout = 1000;\n }\n\n var _React$useState = useState(false),\n isUnloading = _React$useState[0],\n setIsUnloading = _React$useState[1];\n\n useEffect(function () {\n var cleanUpTimeout;\n\n var onBeforeUnloadHandler = function onBeforeUnloadHandler() {\n if (preventDefault) {\n return;\n }\n\n setIsUnloading(true);\n cleanUpTimeout = window.setTimeout(function () {\n // if we actually stay on page, revert changes\n // 1 second is safe boundary that shouldn't execute in between beforeUnload and actual unload\n setIsUnloading(false);\n }, timeout);\n };\n\n window.addEventListener('beforeunload', onBeforeUnloadHandler);\n return function () {\n window.removeEventListener('beforeunload', onBeforeUnloadHandler);\n\n if (cleanUpTimeout) {\n window.clearTimeout(cleanUpTimeout);\n }\n };\n }, [preventDefault, timeout]);\n return isUnloading;\n};\n\nfunction useDialogFocusWithdrawal(isVisible, onClose) {\n var _React$useState = useState(isVisible),\n deferredIsVisible = _React$useState[0],\n setdeferredIsVisible = _React$useState[1];\n\n var triggerRef = useRef(null);\n\n var handleClose = function handleClose() {\n onClose();\n\n if (triggerRef.current instanceof HTMLElement) {\n triggerRef.current.focus();\n }\n };\n\n useEffect(function () {\n triggerRef.current = isVisible ? document.activeElement : null;\n setdeferredIsVisible(isVisible);\n }, [isVisible, triggerRef]);\n return [deferredIsVisible, handleClose];\n}\n\nvar useIsFocusWithin = function useIsFocusWithin(initialValue) {\n if (initialValue === void 0) {\n initialValue = false;\n }\n\n var _React$useState = useState(initialValue),\n isFocusWithin = _React$useState[0],\n setIsFocusWithin = _React$useState[1];\n\n var _useFocusWithin = useFocusWithin({\n onFocusWithin: function onFocusWithin() {\n setIsFocusWithin(true);\n },\n onBlurWithin: function onBlurWithin() {\n setIsFocusWithin(false);\n }\n }),\n focusWithinProps = _useFocusWithin.focusWithinProps;\n\n return [isFocusWithin, focusWithinProps];\n};\n\nvar useIndirectFocus = function useIndirectFocus(_ref) {\n var _ref$onFocusCallback = _ref.onFocusCallback,\n onFocusCallback = _ref$onFocusCallback === void 0 ? noop : _ref$onFocusCallback,\n _ref$onBlurCallback = _ref.onBlurCallback,\n onBlurCallback = _ref$onBlurCallback === void 0 ? noop : _ref$onBlurCallback;\n\n var _React$useState = useState(false),\n isFocused = _React$useState[0],\n setIsFocused = _React$useState[1];\n\n var frame = useFrame();\n var getFocusType = useFocusTypeTracking(frame);\n\n var onFocus = function onFocus(event) {\n onFocusCallback(event);\n\n if (getFocusType() === 'keyboard') {\n setIsFocused(true);\n }\n };\n\n var onBlur = function onBlur(event) {\n onBlurCallback(event);\n setIsFocused(false);\n };\n\n return {\n isFocused: isFocused,\n onFocus: onFocus,\n onBlur: onBlur\n };\n};\n\nexport { MemoryCacheProvider, useAnimatedScrollDelta, useAriaIsolation, useDefferedBeforeUnloadingState, useDialogFocusWithdrawal, useDocumentEvent, useEventPreventDefault, useFocusTypeTracking, useHTMLElementEvent, useHover, useInMemoryCache, useIndirectFocus, useIsFocusWithin, useKeyboardTriggeredClick, useOnGlobalKeydown, useOnMount, useOnUnmount, useOnUpdate, usePostponedToUpdateCallback, useRovingTabIndex, useScrollableChatList, useStreamState, useStreamValue, useTimeout, useToggle };\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct.js\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"./getPrototypeOf.js\";\nimport setPrototypeOf from \"./setPrototypeOf.js\";\nimport isNativeFunction from \"./isNativeFunction.js\";\nimport construct from \"./construct.js\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","import _extends from '@babel/runtime/helpers/esm/extends';\nimport _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized';\nimport _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose';\nimport _wrapNativeSuper from '@babel/runtime/helpers/esm/wrapNativeSuper';\nimport _taggedTemplateLiteralLoose from '@babel/runtime/helpers/esm/taggedTemplateLiteralLoose';\n\nfunction last() {\n var _ref;\n\n return _ref = arguments.length - 1, _ref < 0 || arguments.length <= _ref ? undefined : arguments[_ref];\n}\n\nfunction negation(a) {\n return -a;\n}\n\nfunction addition(a, b) {\n return a + b;\n}\n\nfunction subtraction(a, b) {\n return a - b;\n}\n\nfunction multiplication(a, b) {\n return a * b;\n}\n\nfunction division(a, b) {\n return a / b;\n}\n\nfunction factorial(a) {\n if (a % 1 || !(+a >= 0)) return NaN;\n if (a > 170) return Infinity;else if (a === 0) return 1;else {\n return a * factorial(a - 1);\n }\n}\n\nfunction power(a, b) {\n return Math.pow(a, b);\n}\n\nfunction sqrt(a) {\n return Math.sqrt(a);\n}\n\nfunction max() {\n return Math.max.apply(Math, arguments);\n}\n\nfunction min() {\n return Math.min.apply(Math, arguments);\n}\n\nfunction comma() {\n return Array.of.apply(Array, arguments);\n}\n\nvar defaultMathSymbols = {\n symbols: {\n '!': {\n postfix: {\n symbol: '!',\n f: factorial,\n notation: 'postfix',\n precedence: 6,\n rightToLeft: 0,\n argCount: 1\n },\n symbol: '!',\n regSymbol: '!'\n },\n '^': {\n infix: {\n symbol: '^',\n f: power,\n notation: 'infix',\n precedence: 5,\n rightToLeft: 1,\n argCount: 2\n },\n symbol: '^',\n regSymbol: '\\\\^'\n },\n '*': {\n infix: {\n symbol: '*',\n f: multiplication,\n notation: 'infix',\n precedence: 4,\n rightToLeft: 0,\n argCount: 2\n },\n symbol: '*',\n regSymbol: '\\\\*'\n },\n '/': {\n infix: {\n symbol: '/',\n f: division,\n notation: 'infix',\n precedence: 4,\n rightToLeft: 0,\n argCount: 2\n },\n symbol: '/',\n regSymbol: '/'\n },\n '+': {\n infix: {\n symbol: '+',\n f: addition,\n notation: 'infix',\n precedence: 2,\n rightToLeft: 0,\n argCount: 2\n },\n prefix: {\n symbol: '+',\n f: last,\n notation: 'prefix',\n precedence: 3,\n rightToLeft: 0,\n argCount: 1\n },\n symbol: '+',\n regSymbol: '\\\\+'\n },\n '-': {\n infix: {\n symbol: '-',\n f: subtraction,\n notation: 'infix',\n precedence: 2,\n rightToLeft: 0,\n argCount: 2\n },\n prefix: {\n symbol: '-',\n f: negation,\n notation: 'prefix',\n precedence: 3,\n rightToLeft: 0,\n argCount: 1\n },\n symbol: '-',\n regSymbol: '-'\n },\n ',': {\n infix: {\n symbol: ',',\n f: comma,\n notation: 'infix',\n precedence: 1,\n rightToLeft: 0,\n argCount: 2\n },\n symbol: ',',\n regSymbol: ','\n },\n '(': {\n prefix: {\n symbol: '(',\n f: last,\n notation: 'prefix',\n precedence: 0,\n rightToLeft: 0,\n argCount: 1\n },\n symbol: '(',\n regSymbol: '\\\\('\n },\n ')': {\n postfix: {\n symbol: ')',\n f: undefined,\n notation: 'postfix',\n precedence: 0,\n rightToLeft: 0,\n argCount: 1\n },\n symbol: ')',\n regSymbol: '\\\\)'\n },\n min: {\n func: {\n symbol: 'min',\n f: min,\n notation: 'func',\n precedence: 0,\n rightToLeft: 0,\n argCount: 1\n },\n symbol: 'min',\n regSymbol: 'min\\\\b'\n },\n max: {\n func: {\n symbol: 'max',\n f: max,\n notation: 'func',\n precedence: 0,\n rightToLeft: 0,\n argCount: 1\n },\n symbol: 'max',\n regSymbol: 'max\\\\b'\n },\n sqrt: {\n func: {\n symbol: 'sqrt',\n f: sqrt,\n notation: 'func',\n precedence: 0,\n rightToLeft: 0,\n argCount: 1\n },\n symbol: 'sqrt',\n regSymbol: 'sqrt\\\\b'\n }\n }\n};\n\n// based on https://github.com/styled-components/styled-components/blob/fcf6f3804c57a14dd7984dfab7bc06ee2edca044/src/utils/error.js\n\n/**\n * Parse errors.md and turn it into a simple hash of code: message\n * @private\n */\nvar ERRORS = {\n \"1\": \"Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\\n\\n\",\n \"2\": \"Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\\n\\n\",\n \"3\": \"Passed an incorrect argument to a color function, please pass a string representation of a color.\\n\\n\",\n \"4\": \"Couldn't generate valid rgb string from %s, it returned %s.\\n\\n\",\n \"5\": \"Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\\n\\n\",\n \"6\": \"Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\\n\\n\",\n \"7\": \"Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\\n\\n\",\n \"8\": \"Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\\n\\n\",\n \"9\": \"Please provide a number of steps to the modularScale helper.\\n\\n\",\n \"10\": \"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\\n\\n\",\n \"11\": \"Invalid value passed as base to modularScale, expected number or em string but got \\\"%s\\\"\\n\\n\",\n \"12\": \"Expected a string ending in \\\"px\\\" or a number passed as the first argument to %s(), got \\\"%s\\\" instead.\\n\\n\",\n \"13\": \"Expected a string ending in \\\"px\\\" or a number passed as the second argument to %s(), got \\\"%s\\\" instead.\\n\\n\",\n \"14\": \"Passed invalid pixel value (\\\"%s\\\") to %s(), please pass a value like \\\"12px\\\" or 12.\\n\\n\",\n \"15\": \"Passed invalid base value (\\\"%s\\\") to %s(), please pass a value like \\\"12px\\\" or 12.\\n\\n\",\n \"16\": \"You must provide a template to this method.\\n\\n\",\n \"17\": \"You passed an unsupported selector state to this method.\\n\\n\",\n \"18\": \"minScreen and maxScreen must be provided as stringified numbers with the same units.\\n\\n\",\n \"19\": \"fromSize and toSize must be provided as stringified numbers with the same units.\\n\\n\",\n \"20\": \"expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\\n\\n\",\n \"21\": \"expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\\n\\n\",\n \"22\": \"expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\\n\\n\",\n \"23\": \"fontFace expects a name of a font-family.\\n\\n\",\n \"24\": \"fontFace expects either the path to the font file(s) or a name of a local copy.\\n\\n\",\n \"25\": \"fontFace expects localFonts to be an array.\\n\\n\",\n \"26\": \"fontFace expects fileFormats to be an array.\\n\\n\",\n \"27\": \"radialGradient requries at least 2 color-stops to properly render.\\n\\n\",\n \"28\": \"Please supply a filename to retinaImage() as the first argument.\\n\\n\",\n \"29\": \"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\\n\\n\",\n \"30\": \"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\\n\\n\",\n \"31\": \"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\\n\\n\",\n \"32\": \"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\\n\\n\",\n \"33\": \"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\\n\\n\",\n \"34\": \"borderRadius expects a radius value as a string or number as the second argument.\\n\\n\",\n \"35\": \"borderRadius expects one of \\\"top\\\", \\\"bottom\\\", \\\"left\\\" or \\\"right\\\" as the first argument.\\n\\n\",\n \"36\": \"Property must be a string value.\\n\\n\",\n \"37\": \"Syntax Error at %s.\\n\\n\",\n \"38\": \"Formula contains a function that needs parentheses at %s.\\n\\n\",\n \"39\": \"Formula is missing closing parenthesis at %s.\\n\\n\",\n \"40\": \"Formula has too many closing parentheses at %s.\\n\\n\",\n \"41\": \"All values in a formula must have the same unit or be unitless.\\n\\n\",\n \"42\": \"Please provide a number of steps to the modularScale helper.\\n\\n\",\n \"43\": \"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\\n\\n\",\n \"44\": \"Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\\n\\n\",\n \"45\": \"Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\\n\\n\",\n \"46\": \"Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\\n\\n\",\n \"47\": \"minScreen and maxScreen must be provided as stringified numbers with the same units.\\n\\n\",\n \"48\": \"fromSize and toSize must be provided as stringified numbers with the same units.\\n\\n\",\n \"49\": \"Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\\n\\n\",\n \"50\": \"Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\\n\\n\",\n \"51\": \"Expects the first argument object to have the properties prop, fromSize, and toSize.\\n\\n\",\n \"52\": \"fontFace expects either the path to the font file(s) or a name of a local copy.\\n\\n\",\n \"53\": \"fontFace expects localFonts to be an array.\\n\\n\",\n \"54\": \"fontFace expects fileFormats to be an array.\\n\\n\",\n \"55\": \"fontFace expects a name of a font-family.\\n\\n\",\n \"56\": \"linearGradient requries at least 2 color-stops to properly render.\\n\\n\",\n \"57\": \"radialGradient requries at least 2 color-stops to properly render.\\n\\n\",\n \"58\": \"Please supply a filename to retinaImage() as the first argument.\\n\\n\",\n \"59\": \"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\\n\\n\",\n \"60\": \"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\\n\\n\",\n \"61\": \"Property must be a string value.\\n\\n\",\n \"62\": \"borderRadius expects a radius value as a string or number as the second argument.\\n\\n\",\n \"63\": \"borderRadius expects one of \\\"top\\\", \\\"bottom\\\", \\\"left\\\" or \\\"right\\\" as the first argument.\\n\\n\",\n \"64\": \"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\\n\\n\",\n \"65\": \"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\\n\\n\",\n \"66\": \"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\\n\\n\",\n \"67\": \"You must provide a template to this method.\\n\\n\",\n \"68\": \"You passed an unsupported selector state to this method.\\n\\n\",\n \"69\": \"Expected a string ending in \\\"px\\\" or a number passed as the first argument to %s(), got %s instead.\\n\\n\",\n \"70\": \"Expected a string ending in \\\"px\\\" or a number passed as the second argument to %s(), got %s instead.\\n\\n\",\n \"71\": \"Passed invalid pixel value %s to %s(), please pass a value like \\\"12px\\\" or 12.\\n\\n\",\n \"72\": \"Passed invalid base value %s to %s(), please pass a value like \\\"12px\\\" or 12.\\n\\n\",\n \"73\": \"Please provide a valid CSS variable.\\n\\n\",\n \"74\": \"CSS variable not found.\\n\\n\",\n \"75\": \"fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\\n\"\n};\n/**\n * super basic version of sprintf\n * @private\n */\n\nfunction format() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var a = args[0];\n var b = [];\n var c;\n\n for (c = 1; c < args.length; c += 1) {\n b.push(args[c]);\n }\n\n b.forEach(function (d) {\n a = a.replace(/%[a-z]/, d);\n });\n return a;\n}\n/**\n * Create an error file out of errors.md for development and a simple web link to the full errors\n * in production mode.\n * @private\n */\n\n\nvar PolishedError = /*#__PURE__*/function (_Error) {\n _inheritsLoose(PolishedError, _Error);\n\n function PolishedError(code) {\n var _this;\n\n if (process.env.NODE_ENV === 'production') {\n _this = _Error.call(this, \"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#\" + code + \" for more information.\") || this;\n } else {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n _this = _Error.call(this, format.apply(void 0, [ERRORS[code]].concat(args))) || this;\n }\n\n return _assertThisInitialized(_this);\n }\n\n return PolishedError;\n}( /*#__PURE__*/_wrapNativeSuper(Error));\n\nvar unitRegExp = /((?!\\w)a|na|hc|mc|dg|me[r]?|xe|ni(?![a-zA-Z])|mm|cp|tp|xp|q(?!s)|hv|xamv|nimv|wv|sm|s(?!\\D|$)|ged|darg?|nrut)/g; // Merges additional math functionality into the defaults.\n\nfunction mergeSymbolMaps(additionalSymbols) {\n var symbolMap = {};\n symbolMap.symbols = additionalSymbols ? _extends({}, defaultMathSymbols.symbols, additionalSymbols.symbols) : _extends({}, defaultMathSymbols.symbols);\n return symbolMap;\n}\n\nfunction exec(operators, values) {\n var _ref;\n\n var op = operators.pop();\n values.push(op.f.apply(op, (_ref = []).concat.apply(_ref, values.splice(-op.argCount))));\n return op.precedence;\n}\n\nfunction calculate(expression, additionalSymbols) {\n var symbolMap = mergeSymbolMaps(additionalSymbols);\n var match;\n var operators = [symbolMap.symbols['('].prefix];\n var values = [];\n var pattern = new RegExp( // Pattern for numbers\n \"\\\\d+(?:\\\\.\\\\d+)?|\" + // ...and patterns for individual operators/function names\n Object.keys(symbolMap.symbols).map(function (key) {\n return symbolMap.symbols[key];\n }) // longer symbols should be listed first\n // $FlowFixMe\n .sort(function (a, b) {\n return b.symbol.length - a.symbol.length;\n }) // $FlowFixMe\n .map(function (val) {\n return val.regSymbol;\n }).join('|') + \"|(\\\\S)\", 'g');\n pattern.lastIndex = 0; // Reset regular expression object\n\n var afterValue = false;\n\n do {\n match = pattern.exec(expression);\n\n var _ref2 = match || [')', undefined],\n token = _ref2[0],\n bad = _ref2[1];\n\n var notNumber = symbolMap.symbols[token];\n var notNewValue = notNumber && !notNumber.prefix && !notNumber.func;\n var notAfterValue = !notNumber || !notNumber.postfix && !notNumber.infix; // Check for syntax errors:\n\n if (bad || (afterValue ? notAfterValue : notNewValue)) {\n throw new PolishedError(37, match ? match.index : expression.length, expression);\n }\n\n if (afterValue) {\n // We either have an infix or postfix operator (they should be mutually exclusive)\n var curr = notNumber.postfix || notNumber.infix;\n\n do {\n var prev = operators[operators.length - 1];\n if ((curr.precedence - prev.precedence || prev.rightToLeft) > 0) break; // Apply previous operator, since it has precedence over current one\n } while (exec(operators, values)); // Exit loop after executing an opening parenthesis or function\n\n\n afterValue = curr.notation === 'postfix';\n\n if (curr.symbol !== ')') {\n operators.push(curr); // Postfix always has precedence over any operator that follows after it\n\n if (afterValue) exec(operators, values);\n }\n } else if (notNumber) {\n // prefix operator or function\n operators.push(notNumber.prefix || notNumber.func);\n\n if (notNumber.func) {\n // Require an opening parenthesis\n match = pattern.exec(expression);\n\n if (!match || match[0] !== '(') {\n throw new PolishedError(38, match ? match.index : expression.length, expression);\n }\n }\n } else {\n // number\n values.push(+token);\n afterValue = true;\n }\n } while (match && operators.length);\n\n if (operators.length) {\n throw new PolishedError(39, match ? match.index : expression.length, expression);\n } else if (match) {\n throw new PolishedError(40, match ? match.index : expression.length, expression);\n } else {\n return values.pop();\n }\n}\n\nfunction reverseString(str) {\n return str.split('').reverse().join('');\n}\n/**\n * Helper for doing math with CSS Units. Accepts a formula as a string. All values in the formula must have the same unit (or be unitless). Supports complex formulas utliziing addition, subtraction, multiplication, division, square root, powers, factorial, min, max, as well as parentheses for order of operation.\n *\n *In cases where you need to do calculations with mixed units where one unit is a [relative length unit](https://developer.mozilla.org/en-US/docs/Web/CSS/length#Relative_length_units), you will want to use [CSS Calc](https://developer.mozilla.org/en-US/docs/Web/CSS/calc).\n *\n * *warning* While we've done everything possible to ensure math safely evalutes formulas expressed as strings, you should always use extreme caution when passing `math` user provided values.\n * @example\n * // Styles as object usage\n * const styles = {\n * fontSize: math('12rem + 8rem'),\n * fontSize: math('(12px + 2px) * 3'),\n * fontSize: math('3px^2 + sqrt(4)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * fontSize: ${math('12rem + 8rem')};\n * fontSize: ${math('(12px + 2px) * 3')};\n * fontSize: ${math('3px^2 + sqrt(4)')};\n * `\n *\n * // CSS as JS Output\n *\n * div: {\n * fontSize: '20rem',\n * fontSize: '42px',\n * fontSize: '11px',\n * }\n */\n\n\nfunction math(formula, additionalSymbols) {\n var reversedFormula = reverseString(formula);\n var formulaMatch = reversedFormula.match(unitRegExp); // Check that all units are the same\n\n if (formulaMatch && !formulaMatch.every(function (unit) {\n return unit === formulaMatch[0];\n })) {\n throw new PolishedError(41);\n }\n\n var cleanFormula = reverseString(reversedFormula.replace(unitRegExp, ''));\n return \"\" + calculate(cleanFormula, additionalSymbols) + (formulaMatch ? reverseString(formulaMatch[0]) : '');\n}\n\nvar cssVariableRegex = /--[\\S]*/g;\n/**\n * Fetches the value of a passed CSS Variable.\n *\n * Passthrough can be enabled (off by default) for when you are unsure of the input and want non-variable values to be returned instead of an error.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * 'background': cssVar('--background-color'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${cssVar('--background-color')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * 'background': 'red'\n * }\n */\n\nfunction cssVar(cssVariable, passThrough) {\n if (!cssVariable || !cssVariable.match(cssVariableRegex)) {\n if (passThrough) return cssVariable;\n throw new PolishedError(73);\n }\n\n var variableValue;\n /* eslint-disable */\n\n /* istanbul ignore next */\n\n if (typeof document !== 'undefined' && document.documentElement !== null) {\n variableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariable);\n }\n /* eslint-enable */\n\n\n if (variableValue) {\n return variableValue.trim();\n } else {\n throw new PolishedError(74);\n }\n}\n\n// @private\nfunction capitalizeString(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\n\nvar positionMap = ['Top', 'Right', 'Bottom', 'Left'];\n\nfunction generateProperty(property, position) {\n if (!property) return position.toLowerCase();\n var splitProperty = property.split('-');\n\n if (splitProperty.length > 1) {\n splitProperty.splice(1, 0, position);\n return splitProperty.reduce(function (acc, val) {\n return \"\" + acc + capitalizeString(val);\n });\n }\n\n var joinedProperty = property.replace(/([a-z])([A-Z])/g, \"$1\" + position + \"$2\");\n return property === joinedProperty ? \"\" + property + position : joinedProperty;\n}\n\nfunction generateStyles(property, valuesWithDefaults) {\n var styles = {};\n\n for (var i = 0; i < valuesWithDefaults.length; i += 1) {\n if (valuesWithDefaults[i] || valuesWithDefaults[i] === 0) {\n styles[generateProperty(property, positionMap[i])] = valuesWithDefaults[i];\n }\n }\n\n return styles;\n}\n/**\n * Enables shorthand for direction-based properties. It accepts a property (hyphenated or camelCased) and up to four values that map to top, right, bottom, and left, respectively. You can optionally pass an empty string to get only the directional values as properties. You can also optionally pass a null argument for a directional value to ignore it.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...directionalProperty('padding', '12px', '24px', '36px', '48px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${directionalProperty('padding', '12px', '24px', '36px', '48px')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'paddingTop': '12px',\n * 'paddingRight': '24px',\n * 'paddingBottom': '36px',\n * 'paddingLeft': '48px'\n * }\n */\n\n\nfunction directionalProperty(property) {\n for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n values[_key - 1] = arguments[_key];\n }\n\n // prettier-ignore\n var firstValue = values[0],\n _values$ = values[1],\n secondValue = _values$ === void 0 ? firstValue : _values$,\n _values$2 = values[2],\n thirdValue = _values$2 === void 0 ? firstValue : _values$2,\n _values$3 = values[3],\n fourthValue = _values$3 === void 0 ? secondValue : _values$3;\n var valuesWithDefaults = [firstValue, secondValue, thirdValue, fourthValue];\n return generateStyles(property, valuesWithDefaults);\n}\n\n/**\n * Check if a string ends with something\n * @private\n */\nfunction endsWith(string, suffix) {\n return string.substr(-suffix.length) === suffix;\n}\n\nvar cssRegex = /^([+-]?(?:\\d+|\\d*\\.\\d+))([a-z]*|%)$/;\n/**\n * Returns a given CSS value minus its unit of measure.\n *\n * @deprecated - stripUnit's unitReturn functionality has been marked for deprecation in polished 4.0. It's functionality has been been moved to getValueAndUnit.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * '--dimension': stripUnit('100px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * --dimension: ${stripUnit('100px')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * '--dimension': 100\n * }\n */\n\nfunction stripUnit(value, unitReturn) {\n if (typeof value !== 'string') return unitReturn ? [value, undefined] : value;\n var matchedValue = value.match(cssRegex);\n\n if (unitReturn) {\n // eslint-disable-next-line no-console\n console.warn(\"stripUnit's unitReturn functionality has been marked for deprecation in polished 4.0. It's functionality has been been moved to getValueAndUnit.\");\n if (matchedValue) return [parseFloat(value), matchedValue[2]];\n return [value, undefined];\n }\n\n if (matchedValue) return parseFloat(value);\n return value;\n}\n\n/**\n * Factory function that creates pixel-to-x converters\n * @private\n */\n\nvar pxtoFactory = function pxtoFactory(to) {\n return function (pxval, base) {\n if (base === void 0) {\n base = '16px';\n }\n\n var newPxval = pxval;\n var newBase = base;\n\n if (typeof pxval === 'string') {\n if (!endsWith(pxval, 'px')) {\n throw new PolishedError(69, to, pxval);\n }\n\n newPxval = stripUnit(pxval);\n }\n\n if (typeof base === 'string') {\n if (!endsWith(base, 'px')) {\n throw new PolishedError(70, to, base);\n }\n\n newBase = stripUnit(base);\n }\n\n if (typeof newPxval === 'string') {\n throw new PolishedError(71, pxval, to);\n }\n\n if (typeof newBase === 'string') {\n throw new PolishedError(72, base, to);\n }\n\n return \"\" + newPxval / newBase + to;\n };\n};\n\n/**\n * Convert pixel value to ems. The default base value is 16px, but can be changed by passing a\n * second argument to the function.\n * @function\n * @param {string|number} pxval\n * @param {string|number} [base='16px']\n * @example\n * // Styles as object usage\n * const styles = {\n * 'height': em('16px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * height: ${em('16px')}\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * 'height': '1em'\n * }\n */\n\nvar em = /*#__PURE__*/pxtoFactory('em');\n\nvar cssRegex$1 = /^([+-]?(?:\\d+|\\d*\\.\\d+))([a-z]*|%)$/;\n/**\n * Returns a given CSS value and its unit as elements of an array.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * '--dimension': getValueAndUnit('100px')[0],\n * '--unit': getValueAndUnit('100px')[1],\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * --dimension: ${getValueAndUnit('100px')[0]};\n * --unit: ${getValueAndUnit('100px')[1]};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * '--dimension': 100,\n * '--unit': 'px',\n * }\n */\n\nfunction getValueAndUnit(value) {\n if (typeof value !== 'string') return [value, ''];\n var matchedValue = value.match(cssRegex$1);\n if (matchedValue) return [parseFloat(value), matchedValue[2]];\n return [value, undefined];\n}\n\nvar ratioNames = {\n minorSecond: 1.067,\n majorSecond: 1.125,\n minorThird: 1.2,\n majorThird: 1.25,\n perfectFourth: 1.333,\n augFourth: 1.414,\n perfectFifth: 1.5,\n minorSixth: 1.6,\n goldenSection: 1.618,\n majorSixth: 1.667,\n minorSeventh: 1.778,\n majorSeventh: 1.875,\n octave: 2,\n majorTenth: 2.5,\n majorEleventh: 2.667,\n majorTwelfth: 3,\n doubleOctave: 4\n};\n\nfunction getRatio(ratioName) {\n return ratioNames[ratioName];\n}\n/**\n * Establish consistent measurements and spacial relationships throughout your projects by incrementing an em or rem value up or down a defined scale. We provide a list of commonly used scales as pre-defined variables.\n * @example\n * // Styles as object usage\n * const styles = {\n * // Increment two steps up the default scale\n * 'fontSize': modularScale(2)\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * // Increment two steps up the default scale\n * fontSize: ${modularScale(2)}\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * 'fontSize': '1.77689em'\n * }\n */\n\n\nfunction modularScale(steps, base, ratio) {\n if (base === void 0) {\n base = '1em';\n }\n\n if (ratio === void 0) {\n ratio = 1.333;\n }\n\n if (typeof steps !== 'number') {\n throw new PolishedError(42);\n }\n\n if (typeof ratio === 'string' && !ratioNames[ratio]) {\n throw new PolishedError(43);\n }\n\n var _ref = typeof base === 'string' ? getValueAndUnit(base) : [base, ''],\n realBase = _ref[0],\n unit = _ref[1];\n\n var realRatio = typeof ratio === 'string' ? getRatio(ratio) : ratio;\n\n if (typeof realBase === 'string') {\n throw new PolishedError(44, base);\n }\n\n return \"\" + realBase * Math.pow(realRatio, steps) + (unit || '');\n}\n\n/**\n * Convert pixel value to rems. The default base value is 16px, but can be changed by passing a\n * second argument to the function.\n * @function\n * @param {string|number} pxval\n * @param {string|number} [base='16px']\n * @example\n * // Styles as object usage\n * const styles = {\n * 'height': rem('16px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * height: ${rem('16px')}\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * 'height': '1rem'\n * }\n */\n\nvar rem = /*#__PURE__*/pxtoFactory('rem');\n\n/**\n * Returns a CSS calc formula for linear interpolation of a property between two values. Accepts optional minScreen (defaults to '320px') and maxScreen (defaults to '1200px').\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * fontSize: between('20px', '100px', '400px', '1000px'),\n * fontSize: between('20px', '100px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * fontSize: ${between('20px', '100px', '400px', '1000px')};\n * fontSize: ${between('20px', '100px')}\n * `\n *\n * // CSS as JS Output\n *\n * h1: {\n * 'fontSize': 'calc(-33.33333333333334px + 13.333333333333334vw)',\n * 'fontSize': 'calc(-9.090909090909093px + 9.090909090909092vw)'\n * }\n */\n\nfunction between(fromSize, toSize, minScreen, maxScreen) {\n if (minScreen === void 0) {\n minScreen = '320px';\n }\n\n if (maxScreen === void 0) {\n maxScreen = '1200px';\n }\n\n var _getValueAndUnit = getValueAndUnit(fromSize),\n unitlessFromSize = _getValueAndUnit[0],\n fromSizeUnit = _getValueAndUnit[1];\n\n var _getValueAndUnit2 = getValueAndUnit(toSize),\n unitlessToSize = _getValueAndUnit2[0],\n toSizeUnit = _getValueAndUnit2[1];\n\n var _getValueAndUnit3 = getValueAndUnit(minScreen),\n unitlessMinScreen = _getValueAndUnit3[0],\n minScreenUnit = _getValueAndUnit3[1];\n\n var _getValueAndUnit4 = getValueAndUnit(maxScreen),\n unitlessMaxScreen = _getValueAndUnit4[0],\n maxScreenUnit = _getValueAndUnit4[1];\n\n if (typeof unitlessMinScreen !== 'number' || typeof unitlessMaxScreen !== 'number' || !minScreenUnit || !maxScreenUnit || minScreenUnit !== maxScreenUnit) {\n throw new PolishedError(47);\n }\n\n if (typeof unitlessFromSize !== 'number' || typeof unitlessToSize !== 'number' || fromSizeUnit !== toSizeUnit) {\n throw new PolishedError(48);\n }\n\n if (fromSizeUnit !== minScreenUnit || toSizeUnit !== maxScreenUnit) {\n throw new PolishedError(75);\n }\n\n var slope = (unitlessFromSize - unitlessToSize) / (unitlessMinScreen - unitlessMaxScreen);\n var base = unitlessToSize - slope * unitlessMaxScreen;\n return \"calc(\" + base.toFixed(2) + (fromSizeUnit || '') + \" + \" + (100 * slope).toFixed(2) + \"vw)\";\n}\n\n/**\n * CSS to contain a float (credit to CSSMojo).\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...clearFix(),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${clearFix()}\n * `\n *\n * // CSS as JS Output\n *\n * '&::after': {\n * 'clear': 'both',\n * 'content': '\"\"',\n * 'display': 'table'\n * }\n */\nfunction clearFix(parent) {\n var _ref;\n\n if (parent === void 0) {\n parent = '&';\n }\n\n var pseudoSelector = parent + \"::after\";\n return _ref = {}, _ref[pseudoSelector] = {\n clear: 'both',\n content: '\"\"',\n display: 'table'\n }, _ref;\n}\n\n/**\n * CSS to fully cover an area. Can optionally be passed an offset to act as a \"padding\".\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...cover()\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${cover()}\n * `\n *\n * // CSS as JS Output\n *\n * div: {\n * 'position': 'absolute',\n * 'top': '0',\n * 'right: '0',\n * 'bottom': '0',\n * 'left: '0'\n * }\n */\nfunction cover(offset) {\n if (offset === void 0) {\n offset = 0;\n }\n\n return {\n position: 'absolute',\n top: offset,\n right: offset,\n bottom: offset,\n left: offset\n };\n}\n\n/**\n * CSS to represent truncated text with an ellipsis.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...ellipsis('250px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${ellipsis('250px')}\n * `\n *\n * // CSS as JS Output\n *\n * div: {\n * 'display': 'inline-block',\n * 'maxWidth': '250px',\n * 'overflow': 'hidden',\n * 'textOverflow': 'ellipsis',\n * 'whiteSpace': 'nowrap',\n * 'wordWrap': 'normal'\n * }\n */\nfunction ellipsis(width) {\n if (width === void 0) {\n width = '100%';\n }\n\n return {\n display: 'inline-block',\n maxWidth: width,\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n wordWrap: 'normal'\n };\n}\n\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\n/**\n * Returns a set of media queries that resizes a property (or set of properties) between a provided fromSize and toSize. Accepts optional minScreen (defaults to '320px') and maxScreen (defaults to '1200px') to constrain the interpolation.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...fluidRange(\n * {\n * prop: 'padding',\n * fromSize: '20px',\n * toSize: '100px',\n * },\n * '400px',\n * '1000px',\n * )\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${fluidRange(\n * {\n * prop: 'padding',\n * fromSize: '20px',\n * toSize: '100px',\n * },\n * '400px',\n * '1000px',\n * )}\n * `\n *\n * // CSS as JS Output\n *\n * div: {\n * \"@media (min-width: 1000px)\": Object {\n * \"padding\": \"100px\",\n * },\n * \"@media (min-width: 400px)\": Object {\n * \"padding\": \"calc(-33.33333333333334px + 13.333333333333334vw)\",\n * },\n * \"padding\": \"20px\",\n * }\n */\nfunction fluidRange(cssProp, minScreen, maxScreen) {\n if (minScreen === void 0) {\n minScreen = '320px';\n }\n\n if (maxScreen === void 0) {\n maxScreen = '1200px';\n }\n\n if (!Array.isArray(cssProp) && typeof cssProp !== 'object' || cssProp === null) {\n throw new PolishedError(49);\n }\n\n if (Array.isArray(cssProp)) {\n var mediaQueries = {};\n var fallbacks = {};\n\n for (var _iterator = _createForOfIteratorHelperLoose(cssProp), _step; !(_step = _iterator()).done;) {\n var _extends2, _extends3;\n\n var obj = _step.value;\n\n if (!obj.prop || !obj.fromSize || !obj.toSize) {\n throw new PolishedError(50);\n }\n\n fallbacks[obj.prop] = obj.fromSize;\n mediaQueries[\"@media (min-width: \" + minScreen + \")\"] = _extends({}, mediaQueries[\"@media (min-width: \" + minScreen + \")\"], (_extends2 = {}, _extends2[obj.prop] = between(obj.fromSize, obj.toSize, minScreen, maxScreen), _extends2));\n mediaQueries[\"@media (min-width: \" + maxScreen + \")\"] = _extends({}, mediaQueries[\"@media (min-width: \" + maxScreen + \")\"], (_extends3 = {}, _extends3[obj.prop] = obj.toSize, _extends3));\n }\n\n return _extends({}, fallbacks, mediaQueries);\n } else {\n var _ref, _ref2, _ref3;\n\n if (!cssProp.prop || !cssProp.fromSize || !cssProp.toSize) {\n throw new PolishedError(51);\n }\n\n return _ref3 = {}, _ref3[cssProp.prop] = cssProp.fromSize, _ref3[\"@media (min-width: \" + minScreen + \")\"] = (_ref = {}, _ref[cssProp.prop] = between(cssProp.fromSize, cssProp.toSize, minScreen, maxScreen), _ref), _ref3[\"@media (min-width: \" + maxScreen + \")\"] = (_ref2 = {}, _ref2[cssProp.prop] = cssProp.toSize, _ref2), _ref3;\n }\n}\n\nvar dataURIRegex = /^\\s*data:([a-z]+\\/[a-z-]+(;[a-z-]+=[a-z-]+)?)?(;charset=[a-z0-9-]+)?(;base64)?,[a-z0-9!$&',()*+,;=\\-._~:@/?%\\s]*\\s*$/i;\nvar formatHintMap = {\n woff: 'woff',\n woff2: 'woff2',\n ttf: 'truetype',\n otf: 'opentype',\n eot: 'embedded-opentype',\n svg: 'svg',\n svgz: 'svg'\n};\n\nfunction generateFormatHint(format, formatHint) {\n if (!formatHint) return '';\n return \" format(\\\"\" + formatHintMap[format] + \"\\\")\";\n}\n\nfunction isDataURI(fontFilePath) {\n return !!fontFilePath.replace(/\\s+/g, ' ').match(dataURIRegex);\n}\n\nfunction generateFileReferences(fontFilePath, fileFormats, formatHint) {\n if (isDataURI(fontFilePath)) {\n return \"url(\\\"\" + fontFilePath + \"\\\")\" + generateFormatHint(fileFormats[0], formatHint);\n }\n\n var fileFontReferences = fileFormats.map(function (format) {\n return \"url(\\\"\" + fontFilePath + \".\" + format + \"\\\")\" + generateFormatHint(format, formatHint);\n });\n return fileFontReferences.join(', ');\n}\n\nfunction generateLocalReferences(localFonts) {\n var localFontReferences = localFonts.map(function (font) {\n return \"local(\\\"\" + font + \"\\\")\";\n });\n return localFontReferences.join(', ');\n}\n\nfunction generateSources(fontFilePath, localFonts, fileFormats, formatHint) {\n var fontReferences = [];\n if (localFonts) fontReferences.push(generateLocalReferences(localFonts));\n\n if (fontFilePath) {\n fontReferences.push(generateFileReferences(fontFilePath, fileFormats, formatHint));\n }\n\n return fontReferences.join(', ');\n}\n/**\n * CSS for a @font-face declaration.\n *\n * @example\n * // Styles as object basic usage\n * const styles = {\n * ...fontFace({\n * 'fontFamily': 'Sans-Pro',\n * 'fontFilePath': 'path/to/file'\n * })\n * }\n *\n * // styled-components basic usage\n * const GlobalStyle = createGlobalStyle`${\n * fontFace({\n * 'fontFamily': 'Sans-Pro',\n * 'fontFilePath': 'path/to/file'\n * }\n * )}`\n *\n * // CSS as JS Output\n *\n * '@font-face': {\n * 'fontFamily': 'Sans-Pro',\n * 'src': 'url(\"path/to/file.eot\"), url(\"path/to/file.woff2\"), url(\"path/to/file.woff\"), url(\"path/to/file.ttf\"), url(\"path/to/file.svg\")',\n * }\n */\n\n\nfunction fontFace(_ref) {\n var fontFamily = _ref.fontFamily,\n fontFilePath = _ref.fontFilePath,\n fontStretch = _ref.fontStretch,\n fontStyle = _ref.fontStyle,\n fontVariant = _ref.fontVariant,\n fontWeight = _ref.fontWeight,\n _ref$fileFormats = _ref.fileFormats,\n fileFormats = _ref$fileFormats === void 0 ? ['eot', 'woff2', 'woff', 'ttf', 'svg'] : _ref$fileFormats,\n _ref$formatHint = _ref.formatHint,\n formatHint = _ref$formatHint === void 0 ? false : _ref$formatHint,\n localFonts = _ref.localFonts,\n unicodeRange = _ref.unicodeRange,\n fontDisplay = _ref.fontDisplay,\n fontVariationSettings = _ref.fontVariationSettings,\n fontFeatureSettings = _ref.fontFeatureSettings;\n // Error Handling\n if (!fontFamily) throw new PolishedError(55);\n\n if (!fontFilePath && !localFonts) {\n throw new PolishedError(52);\n }\n\n if (localFonts && !Array.isArray(localFonts)) {\n throw new PolishedError(53);\n }\n\n if (!Array.isArray(fileFormats)) {\n throw new PolishedError(54);\n }\n\n var fontFaceDeclaration = {\n '@font-face': {\n fontFamily: fontFamily,\n src: generateSources(fontFilePath, localFonts, fileFormats, formatHint),\n unicodeRange: unicodeRange,\n fontStretch: fontStretch,\n fontStyle: fontStyle,\n fontVariant: fontVariant,\n fontWeight: fontWeight,\n fontDisplay: fontDisplay,\n fontVariationSettings: fontVariationSettings,\n fontFeatureSettings: fontFeatureSettings\n }\n }; // Removes undefined fields for cleaner css object.\n\n return JSON.parse(JSON.stringify(fontFaceDeclaration));\n}\n\n/**\n * CSS to hide text to show a background image in a SEO-friendly way.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * 'backgroundImage': 'url(logo.png)',\n * ...hideText(),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * backgroundImage: url(logo.png);\n * ${hideText()};\n * `\n *\n * // CSS as JS Output\n *\n * 'div': {\n * 'backgroundImage': 'url(logo.png)',\n * 'textIndent': '101%',\n * 'overflow': 'hidden',\n * 'whiteSpace': 'nowrap',\n * }\n */\nfunction hideText() {\n return {\n textIndent: '101%',\n overflow: 'hidden',\n whiteSpace: 'nowrap'\n };\n}\n\n/**\n * CSS to hide content visually but remain accessible to screen readers.\n * from [HTML5 Boilerplate](https://github.com/h5bp/html5-boilerplate/blob/9a176f57af1cfe8ec70300da4621fb9b07e5fa31/src/css/main.css#L121)\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...hideVisually(),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${hideVisually()};\n * `\n *\n * // CSS as JS Output\n *\n * 'div': {\n * 'border': '0',\n * 'clip': 'rect(0 0 0 0)',\n * 'height': '1px',\n * 'margin': '-1px',\n * 'overflow': 'hidden',\n * 'padding': '0',\n * 'position': 'absolute',\n * 'whiteSpace': 'nowrap',\n * 'width': '1px',\n * }\n */\nfunction hideVisually() {\n return {\n border: '0',\n clip: 'rect(0 0 0 0)',\n height: '1px',\n margin: '-1px',\n overflow: 'hidden',\n padding: '0',\n position: 'absolute',\n whiteSpace: 'nowrap',\n width: '1px'\n };\n}\n\n/**\n * Generates a media query to target HiDPI devices.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * [hiDPI(1.5)]: {\n * width: 200px;\n * }\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${hiDPI(1.5)} {\n * width: 200px;\n * }\n * `\n *\n * // CSS as JS Output\n *\n * '@media only screen and (-webkit-min-device-pixel-ratio: 1.5),\n * only screen and (min--moz-device-pixel-ratio: 1.5),\n * only screen and (-o-min-device-pixel-ratio: 1.5/1),\n * only screen and (min-resolution: 144dpi),\n * only screen and (min-resolution: 1.5dppx)': {\n * 'width': '200px',\n * }\n */\nfunction hiDPI(ratio) {\n if (ratio === void 0) {\n ratio = 1.3;\n }\n\n return \"\\n @media only screen and (-webkit-min-device-pixel-ratio: \" + ratio + \"),\\n only screen and (min--moz-device-pixel-ratio: \" + ratio + \"),\\n only screen and (-o-min-device-pixel-ratio: \" + ratio + \"/1),\\n only screen and (min-resolution: \" + Math.round(ratio * 96) + \"dpi),\\n only screen and (min-resolution: \" + ratio + \"dppx)\\n \";\n}\n\nfunction constructGradientValue(literals) {\n var template = '';\n\n for (var _len = arguments.length, substitutions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n substitutions[_key - 1] = arguments[_key];\n }\n\n for (var i = 0; i < literals.length; i += 1) {\n template += literals[i];\n\n if (i === substitutions.length - 1 && substitutions[i]) {\n var definedValues = substitutions.filter(function (substitute) {\n return !!substitute;\n }); // Adds leading coma if properties preceed color-stops\n\n if (definedValues.length > 1) {\n template = template.slice(0, -1);\n template += \", \" + substitutions[i]; // No trailing space if color-stops is the only param provided\n } else if (definedValues.length === 1) {\n template += \"\" + substitutions[i];\n }\n } else if (substitutions[i]) {\n template += substitutions[i] + \" \";\n }\n }\n\n return template.trim();\n}\n\nvar _templateObject;\n\n/**\n * CSS for declaring a linear gradient, including a fallback background-color. The fallback is either the first color-stop or an explicitly passed fallback color.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...linearGradient({\n colorStops: ['#00FFFF 0%', 'rgba(0, 0, 255, 0) 50%', '#0000FF 95%'],\n toDirection: 'to top right',\n fallback: '#FFF',\n })\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${linearGradient({\n colorStops: ['#00FFFF 0%', 'rgba(0, 0, 255, 0) 50%', '#0000FF 95%'],\n toDirection: 'to top right',\n fallback: '#FFF',\n })}\n *`\n *\n * // CSS as JS Output\n *\n * div: {\n * 'backgroundColor': '#FFF',\n * 'backgroundImage': 'linear-gradient(to top right, #00FFFF 0%, rgba(0, 0, 255, 0) 50%, #0000FF 95%)',\n * }\n */\nfunction linearGradient(_ref) {\n var colorStops = _ref.colorStops,\n fallback = _ref.fallback,\n _ref$toDirection = _ref.toDirection,\n toDirection = _ref$toDirection === void 0 ? '' : _ref$toDirection;\n\n if (!colorStops || colorStops.length < 2) {\n throw new PolishedError(56);\n }\n\n return {\n backgroundColor: fallback || colorStops[0].replace(/,\\s+/g, ',').split(' ')[0].replace(/,(?=\\S)/g, ', '),\n backgroundImage: constructGradientValue(_templateObject || (_templateObject = _taggedTemplateLiteralLoose([\"linear-gradient(\", \"\", \")\"])), toDirection, colorStops.join(', ').replace(/,(?=\\S)/g, ', '))\n };\n}\n\n/**\n * CSS to normalize abnormalities across browsers (normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css)\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...normalize(),\n * }\n *\n * // styled-components usage\n * const GlobalStyle = createGlobalStyle`${normalize()}`\n *\n * // CSS as JS Output\n *\n * html {\n * lineHeight: 1.15,\n * textSizeAdjust: 100%,\n * } ...\n */\nfunction normalize() {\n var _ref;\n\n return [(_ref = {\n html: {\n lineHeight: '1.15',\n textSizeAdjust: '100%'\n },\n body: {\n margin: '0'\n },\n main: {\n display: 'block'\n },\n h1: {\n fontSize: '2em',\n margin: '0.67em 0'\n },\n hr: {\n boxSizing: 'content-box',\n height: '0',\n overflow: 'visible'\n },\n pre: {\n fontFamily: 'monospace, monospace',\n fontSize: '1em'\n },\n a: {\n backgroundColor: 'transparent'\n },\n 'abbr[title]': {\n borderBottom: 'none',\n textDecoration: 'underline'\n }\n }, _ref[\"b,\\n strong\"] = {\n fontWeight: 'bolder'\n }, _ref[\"code,\\n kbd,\\n samp\"] = {\n fontFamily: 'monospace, monospace',\n fontSize: '1em'\n }, _ref.small = {\n fontSize: '80%'\n }, _ref[\"sub,\\n sup\"] = {\n fontSize: '75%',\n lineHeight: '0',\n position: 'relative',\n verticalAlign: 'baseline'\n }, _ref.sub = {\n bottom: '-0.25em'\n }, _ref.sup = {\n top: '-0.5em'\n }, _ref.img = {\n borderStyle: 'none'\n }, _ref[\"button,\\n input,\\n optgroup,\\n select,\\n textarea\"] = {\n fontFamily: 'inherit',\n fontSize: '100%',\n lineHeight: '1.15',\n margin: '0'\n }, _ref[\"button,\\n input\"] = {\n overflow: 'visible'\n }, _ref[\"button,\\n select\"] = {\n textTransform: 'none'\n }, _ref[\"button,\\n html [type=\\\"button\\\"],\\n [type=\\\"reset\\\"],\\n [type=\\\"submit\\\"]\"] = {\n WebkitAppearance: 'button'\n }, _ref[\"button::-moz-focus-inner,\\n [type=\\\"button\\\"]::-moz-focus-inner,\\n [type=\\\"reset\\\"]::-moz-focus-inner,\\n [type=\\\"submit\\\"]::-moz-focus-inner\"] = {\n borderStyle: 'none',\n padding: '0'\n }, _ref[\"button:-moz-focusring,\\n [type=\\\"button\\\"]:-moz-focusring,\\n [type=\\\"reset\\\"]:-moz-focusring,\\n [type=\\\"submit\\\"]:-moz-focusring\"] = {\n outline: '1px dotted ButtonText'\n }, _ref.fieldset = {\n padding: '0.35em 0.625em 0.75em'\n }, _ref.legend = {\n boxSizing: 'border-box',\n color: 'inherit',\n display: 'table',\n maxWidth: '100%',\n padding: '0',\n whiteSpace: 'normal'\n }, _ref.progress = {\n verticalAlign: 'baseline'\n }, _ref.textarea = {\n overflow: 'auto'\n }, _ref[\"[type=\\\"checkbox\\\"],\\n [type=\\\"radio\\\"]\"] = {\n boxSizing: 'border-box',\n padding: '0'\n }, _ref[\"[type=\\\"number\\\"]::-webkit-inner-spin-button,\\n [type=\\\"number\\\"]::-webkit-outer-spin-button\"] = {\n height: 'auto'\n }, _ref['[type=\"search\"]'] = {\n WebkitAppearance: 'textfield',\n outlineOffset: '-2px'\n }, _ref['[type=\"search\"]::-webkit-search-decoration'] = {\n WebkitAppearance: 'none'\n }, _ref['::-webkit-file-upload-button'] = {\n WebkitAppearance: 'button',\n font: 'inherit'\n }, _ref.details = {\n display: 'block'\n }, _ref.summary = {\n display: 'list-item'\n }, _ref.template = {\n display: 'none'\n }, _ref['[hidden]'] = {\n display: 'none'\n }, _ref), {\n 'abbr[title]': {\n textDecoration: 'underline dotted'\n }\n }];\n}\n\nvar _templateObject$1;\n\n/**\n * CSS for declaring a radial gradient, including a fallback background-color. The fallback is either the first color-stop or an explicitly passed fallback color.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...radialGradient({\n * colorStops: ['#00FFFF 0%', 'rgba(0, 0, 255, 0) 50%', '#0000FF 95%'],\n * extent: 'farthest-corner at 45px 45px',\n * position: 'center',\n * shape: 'ellipse',\n * })\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${radialGradient({\n * colorStops: ['#00FFFF 0%', 'rgba(0, 0, 255, 0) 50%', '#0000FF 95%'],\n * extent: 'farthest-corner at 45px 45px',\n * position: 'center',\n * shape: 'ellipse',\n * })}\n *`\n *\n * // CSS as JS Output\n *\n * div: {\n * 'backgroundColor': '#00FFFF',\n * 'backgroundImage': 'radial-gradient(center ellipse farthest-corner at 45px 45px, #00FFFF 0%, rgba(0, 0, 255, 0) 50%, #0000FF 95%)',\n * }\n */\nfunction radialGradient(_ref) {\n var colorStops = _ref.colorStops,\n _ref$extent = _ref.extent,\n extent = _ref$extent === void 0 ? '' : _ref$extent,\n fallback = _ref.fallback,\n _ref$position = _ref.position,\n position = _ref$position === void 0 ? '' : _ref$position,\n _ref$shape = _ref.shape,\n shape = _ref$shape === void 0 ? '' : _ref$shape;\n\n if (!colorStops || colorStops.length < 2) {\n throw new PolishedError(57);\n }\n\n return {\n backgroundColor: fallback || colorStops[0].split(' ')[0],\n backgroundImage: constructGradientValue(_templateObject$1 || (_templateObject$1 = _taggedTemplateLiteralLoose([\"radial-gradient(\", \"\", \"\", \"\", \")\"])), position, shape, extent, colorStops.join(', '))\n };\n}\n\n/**\n * A helper to generate a retina background image and non-retina\n * background image. The retina background image will output to a HiDPI media query. The mixin uses\n * a _2x.png filename suffix by default.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...retinaImage('my-img')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${retinaImage('my-img')}\n * `\n *\n * // CSS as JS Output\n * div {\n * backgroundImage: 'url(my-img.png)',\n * '@media only screen and (-webkit-min-device-pixel-ratio: 1.3),\n * only screen and (min--moz-device-pixel-ratio: 1.3),\n * only screen and (-o-min-device-pixel-ratio: 1.3/1),\n * only screen and (min-resolution: 144dpi),\n * only screen and (min-resolution: 1.5dppx)': {\n * backgroundImage: 'url(my-img_2x.png)',\n * }\n * }\n */\nfunction retinaImage(filename, backgroundSize, extension, retinaFilename, retinaSuffix) {\n var _ref;\n\n if (extension === void 0) {\n extension = 'png';\n }\n\n if (retinaSuffix === void 0) {\n retinaSuffix = '_2x';\n }\n\n if (!filename) {\n throw new PolishedError(58);\n } // Replace the dot at the beginning of the passed extension if one exists\n\n\n var ext = extension.replace(/^\\./, '');\n var rFilename = retinaFilename ? retinaFilename + \".\" + ext : \"\" + filename + retinaSuffix + \".\" + ext;\n return _ref = {\n backgroundImage: \"url(\" + filename + \".\" + ext + \")\"\n }, _ref[hiDPI()] = _extends({\n backgroundImage: \"url(\" + rFilename + \")\"\n }, backgroundSize ? {\n backgroundSize: backgroundSize\n } : {}), _ref;\n}\n\n/* eslint-disable key-spacing */\nvar functionsMap = {\n easeInBack: 'cubic-bezier(0.600, -0.280, 0.735, 0.045)',\n easeInCirc: 'cubic-bezier(0.600, 0.040, 0.980, 0.335)',\n easeInCubic: 'cubic-bezier(0.550, 0.055, 0.675, 0.190)',\n easeInExpo: 'cubic-bezier(0.950, 0.050, 0.795, 0.035)',\n easeInQuad: 'cubic-bezier(0.550, 0.085, 0.680, 0.530)',\n easeInQuart: 'cubic-bezier(0.895, 0.030, 0.685, 0.220)',\n easeInQuint: 'cubic-bezier(0.755, 0.050, 0.855, 0.060)',\n easeInSine: 'cubic-bezier(0.470, 0.000, 0.745, 0.715)',\n easeOutBack: 'cubic-bezier(0.175, 0.885, 0.320, 1.275)',\n easeOutCubic: 'cubic-bezier(0.215, 0.610, 0.355, 1.000)',\n easeOutCirc: 'cubic-bezier(0.075, 0.820, 0.165, 1.000)',\n easeOutExpo: 'cubic-bezier(0.190, 1.000, 0.220, 1.000)',\n easeOutQuad: 'cubic-bezier(0.250, 0.460, 0.450, 0.940)',\n easeOutQuart: 'cubic-bezier(0.165, 0.840, 0.440, 1.000)',\n easeOutQuint: 'cubic-bezier(0.230, 1.000, 0.320, 1.000)',\n easeOutSine: 'cubic-bezier(0.390, 0.575, 0.565, 1.000)',\n easeInOutBack: 'cubic-bezier(0.680, -0.550, 0.265, 1.550)',\n easeInOutCirc: 'cubic-bezier(0.785, 0.135, 0.150, 0.860)',\n easeInOutCubic: 'cubic-bezier(0.645, 0.045, 0.355, 1.000)',\n easeInOutExpo: 'cubic-bezier(1.000, 0.000, 0.000, 1.000)',\n easeInOutQuad: 'cubic-bezier(0.455, 0.030, 0.515, 0.955)',\n easeInOutQuart: 'cubic-bezier(0.770, 0.000, 0.175, 1.000)',\n easeInOutQuint: 'cubic-bezier(0.860, 0.000, 0.070, 1.000)',\n easeInOutSine: 'cubic-bezier(0.445, 0.050, 0.550, 0.950)'\n};\n/* eslint-enable key-spacing */\n\nfunction getTimingFunction(functionName) {\n return functionsMap[functionName];\n}\n/**\n * String to represent common easing functions as demonstrated here: (github.com/jaukia/easie).\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * 'transitionTimingFunction': timingFunctions('easeInQuad')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * transitionTimingFunction: ${timingFunctions('easeInQuad')};\n * `\n *\n * // CSS as JS Output\n *\n * 'div': {\n * 'transitionTimingFunction': 'cubic-bezier(0.550, 0.085, 0.680, 0.530)',\n * }\n */\n\n\nfunction timingFunctions(timingFunction) {\n return getTimingFunction(timingFunction);\n}\n\nvar getBorderWidth = function getBorderWidth(pointingDirection, height, width) {\n var fullWidth = \"\" + width[0] + (width[1] || '');\n var halfWidth = \"\" + width[0] / 2 + (width[1] || '');\n var fullHeight = \"\" + height[0] + (height[1] || '');\n var halfHeight = \"\" + height[0] / 2 + (height[1] || '');\n\n switch (pointingDirection) {\n case 'top':\n return \"0 \" + halfWidth + \" \" + fullHeight + \" \" + halfWidth;\n\n case 'topLeft':\n return fullWidth + \" \" + fullHeight + \" 0 0\";\n\n case 'left':\n return halfHeight + \" \" + fullWidth + \" \" + halfHeight + \" 0\";\n\n case 'bottomLeft':\n return fullWidth + \" 0 0 \" + fullHeight;\n\n case 'bottom':\n return fullHeight + \" \" + halfWidth + \" 0 \" + halfWidth;\n\n case 'bottomRight':\n return \"0 0 \" + fullWidth + \" \" + fullHeight;\n\n case 'right':\n return halfHeight + \" 0 \" + halfHeight + \" \" + fullWidth;\n\n case 'topRight':\n default:\n return \"0 \" + fullWidth + \" \" + fullHeight + \" 0\";\n }\n};\n\nvar getBorderColor = function getBorderColor(pointingDirection, foregroundColor) {\n switch (pointingDirection) {\n case 'top':\n case 'bottomRight':\n return {\n borderBottomColor: foregroundColor\n };\n\n case 'right':\n case 'bottomLeft':\n return {\n borderLeftColor: foregroundColor\n };\n\n case 'bottom':\n case 'topLeft':\n return {\n borderTopColor: foregroundColor\n };\n\n case 'left':\n case 'topRight':\n return {\n borderRightColor: foregroundColor\n };\n\n default:\n throw new PolishedError(59);\n }\n};\n/**\n * CSS to represent triangle with any pointing direction with an optional background color.\n *\n * @example\n * // Styles as object usage\n *\n * const styles = {\n * ...triangle({ pointingDirection: 'right', width: '100px', height: '100px', foregroundColor: 'red' })\n * }\n *\n *\n * // styled-components usage\n * const div = styled.div`\n * ${triangle({ pointingDirection: 'right', width: '100px', height: '100px', foregroundColor: 'red' })}\n *\n *\n * // CSS as JS Output\n *\n * div: {\n * 'borderColor': 'transparent transparent transparent red',\n * 'borderStyle': 'solid',\n * 'borderWidth': '50px 0 50px 100px',\n * 'height': '0',\n * 'width': '0',\n * }\n */\n\n\nfunction triangle(_ref) {\n var pointingDirection = _ref.pointingDirection,\n height = _ref.height,\n width = _ref.width,\n foregroundColor = _ref.foregroundColor,\n _ref$backgroundColor = _ref.backgroundColor,\n backgroundColor = _ref$backgroundColor === void 0 ? 'transparent' : _ref$backgroundColor;\n var widthAndUnit = getValueAndUnit(width);\n var heightAndUnit = getValueAndUnit(height);\n\n if (isNaN(heightAndUnit[0]) || isNaN(widthAndUnit[0])) {\n throw new PolishedError(60);\n }\n\n return _extends({\n width: '0',\n height: '0',\n borderColor: backgroundColor\n }, getBorderColor(pointingDirection, foregroundColor), {\n borderStyle: 'solid',\n borderWidth: getBorderWidth(pointingDirection, heightAndUnit, widthAndUnit)\n });\n}\n\n/**\n * Provides an easy way to change the `wordWrap` property.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...wordWrap('break-word')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${wordWrap('break-word')}\n * `\n *\n * // CSS as JS Output\n *\n * const styles = {\n * overflowWrap: 'break-word',\n * wordWrap: 'break-word',\n * wordBreak: 'break-all',\n * }\n */\nfunction wordWrap(wrap) {\n if (wrap === void 0) {\n wrap = 'break-word';\n }\n\n var wordBreak = wrap === 'break-word' ? 'break-all' : wrap;\n return {\n overflowWrap: wrap,\n wordWrap: wrap,\n wordBreak: wordBreak\n };\n}\n\nfunction colorToInt(color) {\n return Math.round(color * 255);\n}\n\nfunction convertToInt(red, green, blue) {\n return colorToInt(red) + \",\" + colorToInt(green) + \",\" + colorToInt(blue);\n}\n\nfunction hslToRgb(hue, saturation, lightness, convert) {\n if (convert === void 0) {\n convert = convertToInt;\n }\n\n if (saturation === 0) {\n // achromatic\n return convert(lightness, lightness, lightness);\n } // formulae from https://en.wikipedia.org/wiki/HSL_and_HSV\n\n\n var huePrime = (hue % 360 + 360) % 360 / 60;\n var chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;\n var secondComponent = chroma * (1 - Math.abs(huePrime % 2 - 1));\n var red = 0;\n var green = 0;\n var blue = 0;\n\n if (huePrime >= 0 && huePrime < 1) {\n red = chroma;\n green = secondComponent;\n } else if (huePrime >= 1 && huePrime < 2) {\n red = secondComponent;\n green = chroma;\n } else if (huePrime >= 2 && huePrime < 3) {\n green = chroma;\n blue = secondComponent;\n } else if (huePrime >= 3 && huePrime < 4) {\n green = secondComponent;\n blue = chroma;\n } else if (huePrime >= 4 && huePrime < 5) {\n red = secondComponent;\n blue = chroma;\n } else if (huePrime >= 5 && huePrime < 6) {\n red = chroma;\n blue = secondComponent;\n }\n\n var lightnessModification = lightness - chroma / 2;\n var finalRed = red + lightnessModification;\n var finalGreen = green + lightnessModification;\n var finalBlue = blue + lightnessModification;\n return convert(finalRed, finalGreen, finalBlue);\n}\n\nvar namedColorMap = {\n aliceblue: 'f0f8ff',\n antiquewhite: 'faebd7',\n aqua: '00ffff',\n aquamarine: '7fffd4',\n azure: 'f0ffff',\n beige: 'f5f5dc',\n bisque: 'ffe4c4',\n black: '000',\n blanchedalmond: 'ffebcd',\n blue: '0000ff',\n blueviolet: '8a2be2',\n brown: 'a52a2a',\n burlywood: 'deb887',\n cadetblue: '5f9ea0',\n chartreuse: '7fff00',\n chocolate: 'd2691e',\n coral: 'ff7f50',\n cornflowerblue: '6495ed',\n cornsilk: 'fff8dc',\n crimson: 'dc143c',\n cyan: '00ffff',\n darkblue: '00008b',\n darkcyan: '008b8b',\n darkgoldenrod: 'b8860b',\n darkgray: 'a9a9a9',\n darkgreen: '006400',\n darkgrey: 'a9a9a9',\n darkkhaki: 'bdb76b',\n darkmagenta: '8b008b',\n darkolivegreen: '556b2f',\n darkorange: 'ff8c00',\n darkorchid: '9932cc',\n darkred: '8b0000',\n darksalmon: 'e9967a',\n darkseagreen: '8fbc8f',\n darkslateblue: '483d8b',\n darkslategray: '2f4f4f',\n darkslategrey: '2f4f4f',\n darkturquoise: '00ced1',\n darkviolet: '9400d3',\n deeppink: 'ff1493',\n deepskyblue: '00bfff',\n dimgray: '696969',\n dimgrey: '696969',\n dodgerblue: '1e90ff',\n firebrick: 'b22222',\n floralwhite: 'fffaf0',\n forestgreen: '228b22',\n fuchsia: 'ff00ff',\n gainsboro: 'dcdcdc',\n ghostwhite: 'f8f8ff',\n gold: 'ffd700',\n goldenrod: 'daa520',\n gray: '808080',\n green: '008000',\n greenyellow: 'adff2f',\n grey: '808080',\n honeydew: 'f0fff0',\n hotpink: 'ff69b4',\n indianred: 'cd5c5c',\n indigo: '4b0082',\n ivory: 'fffff0',\n khaki: 'f0e68c',\n lavender: 'e6e6fa',\n lavenderblush: 'fff0f5',\n lawngreen: '7cfc00',\n lemonchiffon: 'fffacd',\n lightblue: 'add8e6',\n lightcoral: 'f08080',\n lightcyan: 'e0ffff',\n lightgoldenrodyellow: 'fafad2',\n lightgray: 'd3d3d3',\n lightgreen: '90ee90',\n lightgrey: 'd3d3d3',\n lightpink: 'ffb6c1',\n lightsalmon: 'ffa07a',\n lightseagreen: '20b2aa',\n lightskyblue: '87cefa',\n lightslategray: '789',\n lightslategrey: '789',\n lightsteelblue: 'b0c4de',\n lightyellow: 'ffffe0',\n lime: '0f0',\n limegreen: '32cd32',\n linen: 'faf0e6',\n magenta: 'f0f',\n maroon: '800000',\n mediumaquamarine: '66cdaa',\n mediumblue: '0000cd',\n mediumorchid: 'ba55d3',\n mediumpurple: '9370db',\n mediumseagreen: '3cb371',\n mediumslateblue: '7b68ee',\n mediumspringgreen: '00fa9a',\n mediumturquoise: '48d1cc',\n mediumvioletred: 'c71585',\n midnightblue: '191970',\n mintcream: 'f5fffa',\n mistyrose: 'ffe4e1',\n moccasin: 'ffe4b5',\n navajowhite: 'ffdead',\n navy: '000080',\n oldlace: 'fdf5e6',\n olive: '808000',\n olivedrab: '6b8e23',\n orange: 'ffa500',\n orangered: 'ff4500',\n orchid: 'da70d6',\n palegoldenrod: 'eee8aa',\n palegreen: '98fb98',\n paleturquoise: 'afeeee',\n palevioletred: 'db7093',\n papayawhip: 'ffefd5',\n peachpuff: 'ffdab9',\n peru: 'cd853f',\n pink: 'ffc0cb',\n plum: 'dda0dd',\n powderblue: 'b0e0e6',\n purple: '800080',\n rebeccapurple: '639',\n red: 'f00',\n rosybrown: 'bc8f8f',\n royalblue: '4169e1',\n saddlebrown: '8b4513',\n salmon: 'fa8072',\n sandybrown: 'f4a460',\n seagreen: '2e8b57',\n seashell: 'fff5ee',\n sienna: 'a0522d',\n silver: 'c0c0c0',\n skyblue: '87ceeb',\n slateblue: '6a5acd',\n slategray: '708090',\n slategrey: '708090',\n snow: 'fffafa',\n springgreen: '00ff7f',\n steelblue: '4682b4',\n tan: 'd2b48c',\n teal: '008080',\n thistle: 'd8bfd8',\n tomato: 'ff6347',\n turquoise: '40e0d0',\n violet: 'ee82ee',\n wheat: 'f5deb3',\n white: 'fff',\n whitesmoke: 'f5f5f5',\n yellow: 'ff0',\n yellowgreen: '9acd32'\n};\n/**\n * Checks if a string is a CSS named color and returns its equivalent hex value, otherwise returns the original color.\n * @private\n */\n\nfunction nameToHex(color) {\n if (typeof color !== 'string') return color;\n var normalizedColorName = color.toLowerCase();\n return namedColorMap[normalizedColorName] ? \"#\" + namedColorMap[normalizedColorName] : color;\n}\n\nvar hexRegex = /^#[a-fA-F0-9]{6}$/;\nvar hexRgbaRegex = /^#[a-fA-F0-9]{8}$/;\nvar reducedHexRegex = /^#[a-fA-F0-9]{3}$/;\nvar reducedRgbaHexRegex = /^#[a-fA-F0-9]{4}$/;\nvar rgbRegex = /^rgb\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*\\)$/i;\nvar rgbaRegex = /^rgba\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*([-+]?[0-9]*[.]?[0-9]+)\\s*\\)$/i;\nvar hslRegex = /^hsl\\(\\s*(\\d{0,3}[.]?[0-9]+)\\s*,\\s*(\\d{1,3}[.]?[0-9]?)%\\s*,\\s*(\\d{1,3}[.]?[0-9]?)%\\s*\\)$/i;\nvar hslaRegex = /^hsla\\(\\s*(\\d{0,3}[.]?[0-9]+)\\s*,\\s*(\\d{1,3}[.]?[0-9]?)%\\s*,\\s*(\\d{1,3}[.]?[0-9]?)%\\s*,\\s*([-+]?[0-9]*[.]?[0-9]+)\\s*\\)$/i;\n/**\n * Returns an RgbColor or RgbaColor object. This utility function is only useful\n * if want to extract a color component. With the color util `toColorString` you\n * can convert a RgbColor or RgbaColor object back to a string.\n *\n * @example\n * // Assigns `{ red: 255, green: 0, blue: 0 }` to color1\n * const color1 = parseToRgb('rgb(255, 0, 0)');\n * // Assigns `{ red: 92, green: 102, blue: 112, alpha: 0.75 }` to color2\n * const color2 = parseToRgb('hsla(210, 10%, 40%, 0.75)');\n */\n\nfunction parseToRgb(color) {\n if (typeof color !== 'string') {\n throw new PolishedError(3);\n }\n\n var normalizedColor = nameToHex(color);\n\n if (normalizedColor.match(hexRegex)) {\n return {\n red: parseInt(\"\" + normalizedColor[1] + normalizedColor[2], 16),\n green: parseInt(\"\" + normalizedColor[3] + normalizedColor[4], 16),\n blue: parseInt(\"\" + normalizedColor[5] + normalizedColor[6], 16)\n };\n }\n\n if (normalizedColor.match(hexRgbaRegex)) {\n var alpha = parseFloat((parseInt(\"\" + normalizedColor[7] + normalizedColor[8], 16) / 255).toFixed(2));\n return {\n red: parseInt(\"\" + normalizedColor[1] + normalizedColor[2], 16),\n green: parseInt(\"\" + normalizedColor[3] + normalizedColor[4], 16),\n blue: parseInt(\"\" + normalizedColor[5] + normalizedColor[6], 16),\n alpha: alpha\n };\n }\n\n if (normalizedColor.match(reducedHexRegex)) {\n return {\n red: parseInt(\"\" + normalizedColor[1] + normalizedColor[1], 16),\n green: parseInt(\"\" + normalizedColor[2] + normalizedColor[2], 16),\n blue: parseInt(\"\" + normalizedColor[3] + normalizedColor[3], 16)\n };\n }\n\n if (normalizedColor.match(reducedRgbaHexRegex)) {\n var _alpha = parseFloat((parseInt(\"\" + normalizedColor[4] + normalizedColor[4], 16) / 255).toFixed(2));\n\n return {\n red: parseInt(\"\" + normalizedColor[1] + normalizedColor[1], 16),\n green: parseInt(\"\" + normalizedColor[2] + normalizedColor[2], 16),\n blue: parseInt(\"\" + normalizedColor[3] + normalizedColor[3], 16),\n alpha: _alpha\n };\n }\n\n var rgbMatched = rgbRegex.exec(normalizedColor);\n\n if (rgbMatched) {\n return {\n red: parseInt(\"\" + rgbMatched[1], 10),\n green: parseInt(\"\" + rgbMatched[2], 10),\n blue: parseInt(\"\" + rgbMatched[3], 10)\n };\n }\n\n var rgbaMatched = rgbaRegex.exec(normalizedColor.substring(0, 50));\n\n if (rgbaMatched) {\n return {\n red: parseInt(\"\" + rgbaMatched[1], 10),\n green: parseInt(\"\" + rgbaMatched[2], 10),\n blue: parseInt(\"\" + rgbaMatched[3], 10),\n alpha: parseFloat(\"\" + rgbaMatched[4])\n };\n }\n\n var hslMatched = hslRegex.exec(normalizedColor);\n\n if (hslMatched) {\n var hue = parseInt(\"\" + hslMatched[1], 10);\n var saturation = parseInt(\"\" + hslMatched[2], 10) / 100;\n var lightness = parseInt(\"\" + hslMatched[3], 10) / 100;\n var rgbColorString = \"rgb(\" + hslToRgb(hue, saturation, lightness) + \")\";\n var hslRgbMatched = rgbRegex.exec(rgbColorString);\n\n if (!hslRgbMatched) {\n throw new PolishedError(4, normalizedColor, rgbColorString);\n }\n\n return {\n red: parseInt(\"\" + hslRgbMatched[1], 10),\n green: parseInt(\"\" + hslRgbMatched[2], 10),\n blue: parseInt(\"\" + hslRgbMatched[3], 10)\n };\n }\n\n var hslaMatched = hslaRegex.exec(normalizedColor.substring(0, 50));\n\n if (hslaMatched) {\n var _hue = parseInt(\"\" + hslaMatched[1], 10);\n\n var _saturation = parseInt(\"\" + hslaMatched[2], 10) / 100;\n\n var _lightness = parseInt(\"\" + hslaMatched[3], 10) / 100;\n\n var _rgbColorString = \"rgb(\" + hslToRgb(_hue, _saturation, _lightness) + \")\";\n\n var _hslRgbMatched = rgbRegex.exec(_rgbColorString);\n\n if (!_hslRgbMatched) {\n throw new PolishedError(4, normalizedColor, _rgbColorString);\n }\n\n return {\n red: parseInt(\"\" + _hslRgbMatched[1], 10),\n green: parseInt(\"\" + _hslRgbMatched[2], 10),\n blue: parseInt(\"\" + _hslRgbMatched[3], 10),\n alpha: parseFloat(\"\" + hslaMatched[4])\n };\n }\n\n throw new PolishedError(5);\n}\n\nfunction rgbToHsl(color) {\n // make sure rgb are contained in a set of [0, 255]\n var red = color.red / 255;\n var green = color.green / 255;\n var blue = color.blue / 255;\n var max = Math.max(red, green, blue);\n var min = Math.min(red, green, blue);\n var lightness = (max + min) / 2;\n\n if (max === min) {\n // achromatic\n if (color.alpha !== undefined) {\n return {\n hue: 0,\n saturation: 0,\n lightness: lightness,\n alpha: color.alpha\n };\n } else {\n return {\n hue: 0,\n saturation: 0,\n lightness: lightness\n };\n }\n }\n\n var hue;\n var delta = max - min;\n var saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min);\n\n switch (max) {\n case red:\n hue = (green - blue) / delta + (green < blue ? 6 : 0);\n break;\n\n case green:\n hue = (blue - red) / delta + 2;\n break;\n\n default:\n // blue case\n hue = (red - green) / delta + 4;\n break;\n }\n\n hue *= 60;\n\n if (color.alpha !== undefined) {\n return {\n hue: hue,\n saturation: saturation,\n lightness: lightness,\n alpha: color.alpha\n };\n }\n\n return {\n hue: hue,\n saturation: saturation,\n lightness: lightness\n };\n}\n\n/**\n * Returns an HslColor or HslaColor object. This utility function is only useful\n * if want to extract a color component. With the color util `toColorString` you\n * can convert a HslColor or HslaColor object back to a string.\n *\n * @example\n * // Assigns `{ hue: 0, saturation: 1, lightness: 0.5 }` to color1\n * const color1 = parseToHsl('rgb(255, 0, 0)');\n * // Assigns `{ hue: 128, saturation: 1, lightness: 0.5, alpha: 0.75 }` to color2\n * const color2 = parseToHsl('hsla(128, 100%, 50%, 0.75)');\n */\nfunction parseToHsl(color) {\n // Note: At a later stage we can optimize this function as right now a hsl\n // color would be parsed converted to rgb values and converted back to hsl.\n return rgbToHsl(parseToRgb(color));\n}\n\n/**\n * Reduces hex values if possible e.g. #ff8866 to #f86\n * @private\n */\nvar reduceHexValue = function reduceHexValue(value) {\n if (value.length === 7 && value[1] === value[2] && value[3] === value[4] && value[5] === value[6]) {\n return \"#\" + value[1] + value[3] + value[5];\n }\n\n return value;\n};\n\nfunction numberToHex(value) {\n var hex = value.toString(16);\n return hex.length === 1 ? \"0\" + hex : hex;\n}\n\nfunction colorToHex(color) {\n return numberToHex(Math.round(color * 255));\n}\n\nfunction convertToHex(red, green, blue) {\n return reduceHexValue(\"#\" + colorToHex(red) + colorToHex(green) + colorToHex(blue));\n}\n\nfunction hslToHex(hue, saturation, lightness) {\n return hslToRgb(hue, saturation, lightness, convertToHex);\n}\n\n/**\n * Returns a string value for the color. The returned result is the smallest possible hex notation.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: hsl(359, 0.75, 0.4),\n * background: hsl({ hue: 360, saturation: 0.75, lightness: 0.4 }),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${hsl(359, 0.75, 0.4)};\n * background: ${hsl({ hue: 360, saturation: 0.75, lightness: 0.4 })};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#b3191c\";\n * background: \"#b3191c\";\n * }\n */\nfunction hsl(value, saturation, lightness) {\n if (typeof value === 'number' && typeof saturation === 'number' && typeof lightness === 'number') {\n return hslToHex(value, saturation, lightness);\n } else if (typeof value === 'object' && saturation === undefined && lightness === undefined) {\n return hslToHex(value.hue, value.saturation, value.lightness);\n }\n\n throw new PolishedError(1);\n}\n\n/**\n * Returns a string value for the color. The returned result is the smallest possible rgba or hex notation.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: hsla(359, 0.75, 0.4, 0.7),\n * background: hsla({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0,7 }),\n * background: hsla(359, 0.75, 0.4, 1),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${hsla(359, 0.75, 0.4, 0.7)};\n * background: ${hsla({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0,7 })};\n * background: ${hsla(359, 0.75, 0.4, 1)};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"rgba(179,25,28,0.7)\";\n * background: \"rgba(179,25,28,0.7)\";\n * background: \"#b3191c\";\n * }\n */\nfunction hsla(value, saturation, lightness, alpha) {\n if (typeof value === 'number' && typeof saturation === 'number' && typeof lightness === 'number' && typeof alpha === 'number') {\n return alpha >= 1 ? hslToHex(value, saturation, lightness) : \"rgba(\" + hslToRgb(value, saturation, lightness) + \",\" + alpha + \")\";\n } else if (typeof value === 'object' && saturation === undefined && lightness === undefined && alpha === undefined) {\n return value.alpha >= 1 ? hslToHex(value.hue, value.saturation, value.lightness) : \"rgba(\" + hslToRgb(value.hue, value.saturation, value.lightness) + \",\" + value.alpha + \")\";\n }\n\n throw new PolishedError(2);\n}\n\n/**\n * Returns a string value for the color. The returned result is the smallest possible hex notation.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: rgb(255, 205, 100),\n * background: rgb({ red: 255, green: 205, blue: 100 }),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${rgb(255, 205, 100)};\n * background: ${rgb({ red: 255, green: 205, blue: 100 })};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#ffcd64\";\n * background: \"#ffcd64\";\n * }\n */\nfunction rgb(value, green, blue) {\n if (typeof value === 'number' && typeof green === 'number' && typeof blue === 'number') {\n return reduceHexValue(\"#\" + numberToHex(value) + numberToHex(green) + numberToHex(blue));\n } else if (typeof value === 'object' && green === undefined && blue === undefined) {\n return reduceHexValue(\"#\" + numberToHex(value.red) + numberToHex(value.green) + numberToHex(value.blue));\n }\n\n throw new PolishedError(6);\n}\n\n/**\n * Returns a string value for the color. The returned result is the smallest possible rgba or hex notation.\n *\n * Can also be used to fade a color by passing a hex value or named CSS color along with an alpha value.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: rgba(255, 205, 100, 0.7),\n * background: rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 }),\n * background: rgba(255, 205, 100, 1),\n * background: rgba('#ffffff', 0.4),\n * background: rgba('black', 0.7),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${rgba(255, 205, 100, 0.7)};\n * background: ${rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 })};\n * background: ${rgba(255, 205, 100, 1)};\n * background: ${rgba('#ffffff', 0.4)};\n * background: ${rgba('black', 0.7)};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"rgba(255,205,100,0.7)\";\n * background: \"rgba(255,205,100,0.7)\";\n * background: \"#ffcd64\";\n * background: \"rgba(255,255,255,0.4)\";\n * background: \"rgba(0,0,0,0.7)\";\n * }\n */\nfunction rgba(firstValue, secondValue, thirdValue, fourthValue) {\n if (typeof firstValue === 'string' && typeof secondValue === 'number') {\n var rgbValue = parseToRgb(firstValue);\n return \"rgba(\" + rgbValue.red + \",\" + rgbValue.green + \",\" + rgbValue.blue + \",\" + secondValue + \")\";\n } else if (typeof firstValue === 'number' && typeof secondValue === 'number' && typeof thirdValue === 'number' && typeof fourthValue === 'number') {\n return fourthValue >= 1 ? rgb(firstValue, secondValue, thirdValue) : \"rgba(\" + firstValue + \",\" + secondValue + \",\" + thirdValue + \",\" + fourthValue + \")\";\n } else if (typeof firstValue === 'object' && secondValue === undefined && thirdValue === undefined && fourthValue === undefined) {\n return firstValue.alpha >= 1 ? rgb(firstValue.red, firstValue.green, firstValue.blue) : \"rgba(\" + firstValue.red + \",\" + firstValue.green + \",\" + firstValue.blue + \",\" + firstValue.alpha + \")\";\n }\n\n throw new PolishedError(7);\n}\n\nvar isRgb = function isRgb(color) {\n return typeof color.red === 'number' && typeof color.green === 'number' && typeof color.blue === 'number' && (typeof color.alpha !== 'number' || typeof color.alpha === 'undefined');\n};\n\nvar isRgba = function isRgba(color) {\n return typeof color.red === 'number' && typeof color.green === 'number' && typeof color.blue === 'number' && typeof color.alpha === 'number';\n};\n\nvar isHsl = function isHsl(color) {\n return typeof color.hue === 'number' && typeof color.saturation === 'number' && typeof color.lightness === 'number' && (typeof color.alpha !== 'number' || typeof color.alpha === 'undefined');\n};\n\nvar isHsla = function isHsla(color) {\n return typeof color.hue === 'number' && typeof color.saturation === 'number' && typeof color.lightness === 'number' && typeof color.alpha === 'number';\n};\n/**\n * Converts a RgbColor, RgbaColor, HslColor or HslaColor object to a color string.\n * This util is useful in case you only know on runtime which color object is\n * used. Otherwise we recommend to rely on `rgb`, `rgba`, `hsl` or `hsla`.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: toColorString({ red: 255, green: 205, blue: 100 }),\n * background: toColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 }),\n * background: toColorString({ hue: 240, saturation: 1, lightness: 0.5 }),\n * background: toColorString({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0.72 }),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${toColorString({ red: 255, green: 205, blue: 100 })};\n * background: ${toColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 })};\n * background: ${toColorString({ hue: 240, saturation: 1, lightness: 0.5 })};\n * background: ${toColorString({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0.72 })};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#ffcd64\";\n * background: \"rgba(255,205,100,0.72)\";\n * background: \"#00f\";\n * background: \"rgba(179,25,25,0.72)\";\n * }\n */\n\n\nfunction toColorString(color) {\n if (typeof color !== 'object') throw new PolishedError(8);\n if (isRgba(color)) return rgba(color);\n if (isRgb(color)) return rgb(color);\n if (isHsla(color)) return hsla(color);\n if (isHsl(color)) return hsl(color);\n throw new PolishedError(8);\n}\n\n// Type definitions taken from https://github.com/gcanti/flow-static-land/blob/master/src/Fun.js\n// eslint-disable-next-line no-unused-vars\n// eslint-disable-next-line no-unused-vars\n// eslint-disable-next-line no-redeclare\nfunction curried(f, length, acc) {\n return function fn() {\n // eslint-disable-next-line prefer-rest-params\n var combined = acc.concat(Array.prototype.slice.call(arguments));\n return combined.length >= length ? f.apply(this, combined) : curried(f, length, combined);\n };\n} // eslint-disable-next-line no-redeclare\n\n\nfunction curry(f) {\n // eslint-disable-line no-redeclare\n return curried(f, f.length, []);\n}\n\n/**\n * Changes the hue of the color. Hue is a number between 0 to 360. The first\n * argument for adjustHue is the amount of degrees the color is rotated around\n * the color wheel, always producing a positive hue value.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: adjustHue(180, '#448'),\n * background: adjustHue('180', 'rgba(101,100,205,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${adjustHue(180, '#448')};\n * background: ${adjustHue('180', 'rgba(101,100,205,0.7)')};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#888844\";\n * background: \"rgba(136,136,68,0.7)\";\n * }\n */\n\nfunction adjustHue(degree, color) {\n if (color === 'transparent') return color;\n var hslColor = parseToHsl(color);\n return toColorString(_extends({}, hslColor, {\n hue: hslColor.hue + parseFloat(degree)\n }));\n} // prettier-ignore\n\n\nvar curriedAdjustHue = /*#__PURE__*/curry\n/* :: */\n(adjustHue);\n\n/**\n * Returns the complement of the provided color. This is identical to adjustHue(180, ).\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: complement('#448'),\n * background: complement('rgba(204,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${complement('#448')};\n * background: ${complement('rgba(204,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#884\";\n * background: \"rgba(153,153,153,0.7)\";\n * }\n */\n\nfunction complement(color) {\n if (color === 'transparent') return color;\n var hslColor = parseToHsl(color);\n return toColorString(_extends({}, hslColor, {\n hue: (hslColor.hue + 180) % 360\n }));\n}\n\nfunction guard(lowerBoundary, upperBoundary, value) {\n return Math.max(lowerBoundary, Math.min(upperBoundary, value));\n}\n\n/**\n * Returns a string value for the darkened color.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: darken(0.2, '#FFCD64'),\n * background: darken('0.2', 'rgba(255,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${darken(0.2, '#FFCD64')};\n * background: ${darken('0.2', 'rgba(255,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#ffbd31\";\n * background: \"rgba(255,189,49,0.7)\";\n * }\n */\n\nfunction darken(amount, color) {\n if (color === 'transparent') return color;\n var hslColor = parseToHsl(color);\n return toColorString(_extends({}, hslColor, {\n lightness: guard(0, 1, hslColor.lightness - parseFloat(amount))\n }));\n} // prettier-ignore\n\n\nvar curriedDarken = /*#__PURE__*/curry\n/* :: */\n(darken);\n\n/**\n * Decreases the intensity of a color. Its range is between 0 to 1. The first\n * argument of the desaturate function is the amount by how much the color\n * intensity should be decreased.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: desaturate(0.2, '#CCCD64'),\n * background: desaturate('0.2', 'rgba(204,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${desaturate(0.2, '#CCCD64')};\n * background: ${desaturate('0.2', 'rgba(204,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#b8b979\";\n * background: \"rgba(184,185,121,0.7)\";\n * }\n */\n\nfunction desaturate(amount, color) {\n if (color === 'transparent') return color;\n var hslColor = parseToHsl(color);\n return toColorString(_extends({}, hslColor, {\n saturation: guard(0, 1, hslColor.saturation - parseFloat(amount))\n }));\n} // prettier-ignore\n\n\nvar curriedDesaturate = /*#__PURE__*/curry\n/* :: */\n(desaturate);\n\n/**\n * Returns a number (float) representing the luminance of a color.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: getLuminance('#CCCD64') >= getLuminance('#0000ff') ? '#CCCD64' : '#0000ff',\n * background: getLuminance('rgba(58, 133, 255, 1)') >= getLuminance('rgba(255, 57, 149, 1)') ?\n * 'rgba(58, 133, 255, 1)' :\n * 'rgba(255, 57, 149, 1)',\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${getLuminance('#CCCD64') >= getLuminance('#0000ff') ? '#CCCD64' : '#0000ff'};\n * background: ${getLuminance('rgba(58, 133, 255, 1)') >= getLuminance('rgba(255, 57, 149, 1)') ?\n * 'rgba(58, 133, 255, 1)' :\n * 'rgba(255, 57, 149, 1)'};\n *\n * // CSS in JS Output\n *\n * div {\n * background: \"#CCCD64\";\n * background: \"rgba(58, 133, 255, 1)\";\n * }\n */\n\nfunction getLuminance(color) {\n if (color === 'transparent') return 0;\n var rgbColor = parseToRgb(color);\n\n var _Object$keys$map = Object.keys(rgbColor).map(function (key) {\n var channel = rgbColor[key] / 255;\n return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);\n }),\n r = _Object$keys$map[0],\n g = _Object$keys$map[1],\n b = _Object$keys$map[2];\n\n return parseFloat((0.2126 * r + 0.7152 * g + 0.0722 * b).toFixed(3));\n}\n\n/**\n * Returns the contrast ratio between two colors based on\n * [W3's recommended equation for calculating contrast](http://www.w3.org/TR/WCAG20/#contrast-ratiodef).\n *\n * @example\n * const contrastRatio = getContrast('#444', '#fff');\n */\n\nfunction getContrast(color1, color2) {\n var luminance1 = getLuminance(color1);\n var luminance2 = getLuminance(color2);\n return parseFloat((luminance1 > luminance2 ? (luminance1 + 0.05) / (luminance2 + 0.05) : (luminance2 + 0.05) / (luminance1 + 0.05)).toFixed(2));\n}\n\n/**\n * Converts the color to a grayscale, by reducing its saturation to 0.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: grayscale('#CCCD64'),\n * background: grayscale('rgba(204,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${grayscale('#CCCD64')};\n * background: ${grayscale('rgba(204,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#999\";\n * background: \"rgba(153,153,153,0.7)\";\n * }\n */\n\nfunction grayscale(color) {\n if (color === 'transparent') return color;\n return toColorString(_extends({}, parseToHsl(color), {\n saturation: 0\n }));\n}\n\n/**\n * Converts a HslColor or HslaColor object to a color string.\n * This util is useful in case you only know on runtime which color object is\n * used. Otherwise we recommend to rely on `hsl` or `hsla`.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: hslToColorString({ hue: 240, saturation: 1, lightness: 0.5 }),\n * background: hslToColorString({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0.72 }),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${hslToColorString({ hue: 240, saturation: 1, lightness: 0.5 })};\n * background: ${hslToColorString({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0.72 })};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#00f\";\n * background: \"rgba(179,25,25,0.72)\";\n * }\n */\nfunction hslToColorString(color) {\n if (typeof color === 'object' && typeof color.hue === 'number' && typeof color.saturation === 'number' && typeof color.lightness === 'number') {\n if (color.alpha && typeof color.alpha === 'number') {\n return hsla({\n hue: color.hue,\n saturation: color.saturation,\n lightness: color.lightness,\n alpha: color.alpha\n });\n }\n\n return hsl({\n hue: color.hue,\n saturation: color.saturation,\n lightness: color.lightness\n });\n }\n\n throw new PolishedError(45);\n}\n\n/**\n * Inverts the red, green and blue values of a color.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: invert('#CCCD64'),\n * background: invert('rgba(101,100,205,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${invert('#CCCD64')};\n * background: ${invert('rgba(101,100,205,0.7)')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#33329b\";\n * background: \"rgba(154,155,50,0.7)\";\n * }\n */\n\nfunction invert(color) {\n if (color === 'transparent') return color; // parse color string to rgb\n\n var value = parseToRgb(color);\n return toColorString(_extends({}, value, {\n red: 255 - value.red,\n green: 255 - value.green,\n blue: 255 - value.blue\n }));\n}\n\n/**\n * Returns a string value for the lightened color.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: lighten(0.2, '#CCCD64'),\n * background: lighten('0.2', 'rgba(204,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${lighten(0.2, '#FFCD64')};\n * background: ${lighten('0.2', 'rgba(204,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#e5e6b1\";\n * background: \"rgba(229,230,177,0.7)\";\n * }\n */\n\nfunction lighten(amount, color) {\n if (color === 'transparent') return color;\n var hslColor = parseToHsl(color);\n return toColorString(_extends({}, hslColor, {\n lightness: guard(0, 1, hslColor.lightness + parseFloat(amount))\n }));\n} // prettier-ignore\n\n\nvar curriedLighten = /*#__PURE__*/curry\n/* :: */\n(lighten);\n\n/**\n * Determines which contrast guidelines have been met for two colors.\n * Based on the [contrast calculations recommended by W3](https://www.w3.org/WAI/WCAG21/Understanding/contrast-enhanced.html).\n *\n * @example\n * const scores = meetsContrastGuidelines('#444', '#fff');\n */\nfunction meetsContrastGuidelines(color1, color2) {\n var contrastRatio = getContrast(color1, color2);\n return {\n AA: contrastRatio >= 4.5,\n AALarge: contrastRatio >= 3,\n AAA: contrastRatio >= 7,\n AAALarge: contrastRatio >= 4.5\n };\n}\n\n/**\n * Mixes the two provided colors together by calculating the average of each of the RGB components weighted to the first color by the provided weight.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: mix(0.5, '#f00', '#00f')\n * background: mix(0.25, '#f00', '#00f')\n * background: mix('0.5', 'rgba(255, 0, 0, 0.5)', '#00f')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${mix(0.5, '#f00', '#00f')};\n * background: ${mix(0.25, '#f00', '#00f')};\n * background: ${mix('0.5', 'rgba(255, 0, 0, 0.5)', '#00f')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#7f007f\";\n * background: \"#3f00bf\";\n * background: \"rgba(63, 0, 191, 0.75)\";\n * }\n */\n\nfunction mix(weight, color, otherColor) {\n if (color === 'transparent') return otherColor;\n if (otherColor === 'transparent') return color;\n if (weight === 0) return otherColor;\n var parsedColor1 = parseToRgb(color);\n\n var color1 = _extends({}, parsedColor1, {\n alpha: typeof parsedColor1.alpha === 'number' ? parsedColor1.alpha : 1\n });\n\n var parsedColor2 = parseToRgb(otherColor);\n\n var color2 = _extends({}, parsedColor2, {\n alpha: typeof parsedColor2.alpha === 'number' ? parsedColor2.alpha : 1\n }); // The formula is copied from the original Sass implementation:\n // http://sass-lang.com/documentation/Sass/Script/Functions.html#mix-instance_method\n\n\n var alphaDelta = color1.alpha - color2.alpha;\n var x = parseFloat(weight) * 2 - 1;\n var y = x * alphaDelta === -1 ? x : x + alphaDelta;\n var z = 1 + x * alphaDelta;\n var weight1 = (y / z + 1) / 2.0;\n var weight2 = 1 - weight1;\n var mixedColor = {\n red: Math.floor(color1.red * weight1 + color2.red * weight2),\n green: Math.floor(color1.green * weight1 + color2.green * weight2),\n blue: Math.floor(color1.blue * weight1 + color2.blue * weight2),\n alpha: color1.alpha * (parseFloat(weight) / 1.0) + color2.alpha * (1 - parseFloat(weight) / 1.0)\n };\n return rgba(mixedColor);\n} // prettier-ignore\n\n\nvar curriedMix = /*#__PURE__*/curry\n/* :: */\n(mix);\n\n/**\n * Increases the opacity of a color. Its range for the amount is between 0 to 1.\n *\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: opacify(0.1, 'rgba(255, 255, 255, 0.9)');\n * background: opacify(0.2, 'hsla(0, 0%, 100%, 0.5)'),\n * background: opacify('0.5', 'rgba(255, 0, 0, 0.2)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${opacify(0.1, 'rgba(255, 255, 255, 0.9)')};\n * background: ${opacify(0.2, 'hsla(0, 0%, 100%, 0.5)')},\n * background: ${opacify('0.5', 'rgba(255, 0, 0, 0.2)')},\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#fff\";\n * background: \"rgba(255,255,255,0.7)\";\n * background: \"rgba(255,0,0,0.7)\";\n * }\n */\n\nfunction opacify(amount, color) {\n if (color === 'transparent') return color;\n var parsedColor = parseToRgb(color);\n var alpha = typeof parsedColor.alpha === 'number' ? parsedColor.alpha : 1;\n\n var colorWithAlpha = _extends({}, parsedColor, {\n alpha: guard(0, 1, (alpha * 100 + parseFloat(amount) * 100) / 100)\n });\n\n return rgba(colorWithAlpha);\n} // prettier-ignore\n\n\nvar curriedOpacify = /*#__PURE__*/curry\n/* :: */\n(opacify);\n\nvar defaultReturnIfLightColor = '#000';\nvar defaultReturnIfDarkColor = '#fff';\n/**\n * Returns black or white (or optional passed colors) for best\n * contrast depending on the luminosity of the given color.\n * When passing custom return colors, strict mode ensures that the\n * return color always meets or exceeds WCAG level AA or greater. If this test\n * fails, the default return color (black or white) is returned in place of the\n * custom return color. You can optionally turn off strict mode.\n *\n * Follows [W3C specs for readability](https://www.w3.org/TR/WCAG20-TECHS/G18.html).\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * color: readableColor('#000'),\n * color: readableColor('black', '#001', '#ff8'),\n * color: readableColor('white', '#001', '#ff8'),\n * color: readableColor('red', '#333', '#ddd', true)\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * color: ${readableColor('#000')};\n * color: ${readableColor('black', '#001', '#ff8')};\n * color: ${readableColor('white', '#001', '#ff8')};\n * color: ${readableColor('red', '#333', '#ddd', true)};\n * `\n *\n * // CSS in JS Output\n * element {\n * color: \"#fff\";\n * color: \"#ff8\";\n * color: \"#001\";\n * color: \"#000\";\n * }\n */\n\nfunction readableColor(color, returnIfLightColor, returnIfDarkColor, strict) {\n if (returnIfLightColor === void 0) {\n returnIfLightColor = defaultReturnIfLightColor;\n }\n\n if (returnIfDarkColor === void 0) {\n returnIfDarkColor = defaultReturnIfDarkColor;\n }\n\n if (strict === void 0) {\n strict = true;\n }\n\n var isColorLight = getLuminance(color) > 0.179;\n var preferredReturnColor = isColorLight ? returnIfLightColor : returnIfDarkColor;\n\n if (!strict || getContrast(color, preferredReturnColor) >= 4.5) {\n return preferredReturnColor;\n }\n\n return isColorLight ? defaultReturnIfLightColor : defaultReturnIfDarkColor;\n}\n\n/**\n * Converts a RgbColor or RgbaColor object to a color string.\n * This util is useful in case you only know on runtime which color object is\n * used. Otherwise we recommend to rely on `rgb` or `rgba`.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: rgbToColorString({ red: 255, green: 205, blue: 100 }),\n * background: rgbToColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 }),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${rgbToColorString({ red: 255, green: 205, blue: 100 })};\n * background: ${rgbToColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 })};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#ffcd64\";\n * background: \"rgba(255,205,100,0.72)\";\n * }\n */\nfunction rgbToColorString(color) {\n if (typeof color === 'object' && typeof color.red === 'number' && typeof color.green === 'number' && typeof color.blue === 'number') {\n if (typeof color.alpha === 'number') {\n return rgba({\n red: color.red,\n green: color.green,\n blue: color.blue,\n alpha: color.alpha\n });\n }\n\n return rgb({\n red: color.red,\n green: color.green,\n blue: color.blue\n });\n }\n\n throw new PolishedError(46);\n}\n\n/**\n * Increases the intensity of a color. Its range is between 0 to 1. The first\n * argument of the saturate function is the amount by how much the color\n * intensity should be increased.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: saturate(0.2, '#CCCD64'),\n * background: saturate('0.2', 'rgba(204,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${saturate(0.2, '#FFCD64')};\n * background: ${saturate('0.2', 'rgba(204,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#e0e250\";\n * background: \"rgba(224,226,80,0.7)\";\n * }\n */\n\nfunction saturate(amount, color) {\n if (color === 'transparent') return color;\n var hslColor = parseToHsl(color);\n return toColorString(_extends({}, hslColor, {\n saturation: guard(0, 1, hslColor.saturation + parseFloat(amount))\n }));\n} // prettier-ignore\n\n\nvar curriedSaturate = /*#__PURE__*/curry\n/* :: */\n(saturate);\n\n/**\n * Sets the hue of a color to the provided value. The hue range can be\n * from 0 and 359.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: setHue(42, '#CCCD64'),\n * background: setHue('244', 'rgba(204,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${setHue(42, '#CCCD64')};\n * background: ${setHue('244', 'rgba(204,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#cdae64\";\n * background: \"rgba(107,100,205,0.7)\";\n * }\n */\n\nfunction setHue(hue, color) {\n if (color === 'transparent') return color;\n return toColorString(_extends({}, parseToHsl(color), {\n hue: parseFloat(hue)\n }));\n} // prettier-ignore\n\n\nvar curriedSetHue = /*#__PURE__*/curry\n/* :: */\n(setHue);\n\n/**\n * Sets the lightness of a color to the provided value. The lightness range can be\n * from 0 and 1.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: setLightness(0.2, '#CCCD64'),\n * background: setLightness('0.75', 'rgba(204,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${setLightness(0.2, '#CCCD64')};\n * background: ${setLightness('0.75', 'rgba(204,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#4d4d19\";\n * background: \"rgba(223,224,159,0.7)\";\n * }\n */\n\nfunction setLightness(lightness, color) {\n if (color === 'transparent') return color;\n return toColorString(_extends({}, parseToHsl(color), {\n lightness: parseFloat(lightness)\n }));\n} // prettier-ignore\n\n\nvar curriedSetLightness = /*#__PURE__*/curry\n/* :: */\n(setLightness);\n\n/**\n * Sets the saturation of a color to the provided value. The saturation range can be\n * from 0 and 1.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: setSaturation(0.2, '#CCCD64'),\n * background: setSaturation('0.75', 'rgba(204,205,100,0.7)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${setSaturation(0.2, '#CCCD64')};\n * background: ${setSaturation('0.75', 'rgba(204,205,100,0.7)')};\n * `\n *\n * // CSS in JS Output\n * element {\n * background: \"#adad84\";\n * background: \"rgba(228,229,76,0.7)\";\n * }\n */\n\nfunction setSaturation(saturation, color) {\n if (color === 'transparent') return color;\n return toColorString(_extends({}, parseToHsl(color), {\n saturation: parseFloat(saturation)\n }));\n} // prettier-ignore\n\n\nvar curriedSetSaturation = /*#__PURE__*/curry\n/* :: */\n(setSaturation);\n\n/**\n * Shades a color by mixing it with black. `shade` can produce\n * hue shifts, where as `darken` manipulates the luminance channel and therefore\n * doesn't produce hue shifts.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: shade(0.25, '#00f')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${shade(0.25, '#00f')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#00003f\";\n * }\n */\n\nfunction shade(percentage, color) {\n if (color === 'transparent') return color;\n return curriedMix(parseFloat(percentage), 'rgb(0, 0, 0)', color);\n} // prettier-ignore\n\n\nvar curriedShade = /*#__PURE__*/curry\n/* :: */\n(shade);\n\n/**\n * Tints a color by mixing it with white. `tint` can produce\n * hue shifts, where as `lighten` manipulates the luminance channel and therefore\n * doesn't produce hue shifts.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: tint(0.25, '#00f')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${tint(0.25, '#00f')};\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"#bfbfff\";\n * }\n */\n\nfunction tint(percentage, color) {\n if (color === 'transparent') return color;\n return curriedMix(parseFloat(percentage), 'rgb(255, 255, 255)', color);\n} // prettier-ignore\n\n\nvar curriedTint = /*#__PURE__*/curry\n/* :: */\n(tint);\n\n/**\n * Decreases the opacity of a color. Its range for the amount is between 0 to 1.\n *\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * background: transparentize(0.1, '#fff');\n * background: transparentize(0.2, 'hsl(0, 0%, 100%)'),\n * background: transparentize('0.5', 'rgba(255, 0, 0, 0.8)'),\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * background: ${transparentize(0.1, '#fff')};\n * background: ${transparentize(0.2, 'hsl(0, 0%, 100%)')},\n * background: ${transparentize('0.5', 'rgba(255, 0, 0, 0.8)')},\n * `\n *\n * // CSS in JS Output\n *\n * element {\n * background: \"rgba(255,255,255,0.9)\";\n * background: \"rgba(255,255,255,0.8)\";\n * background: \"rgba(255,0,0,0.3)\";\n * }\n */\n\nfunction transparentize(amount, color) {\n if (color === 'transparent') return color;\n var parsedColor = parseToRgb(color);\n var alpha = typeof parsedColor.alpha === 'number' ? parsedColor.alpha : 1;\n\n var colorWithAlpha = _extends({}, parsedColor, {\n alpha: guard(0, 1, +(alpha * 100 - parseFloat(amount) * 100).toFixed(2) / 100)\n });\n\n return rgba(colorWithAlpha);\n} // prettier-ignore\n\n\nvar curriedTransparentize = /*#__PURE__*/curry\n/* :: */\n(transparentize);\n\n/**\n * Shorthand for easily setting the animation property. Allows either multiple arrays with animations\n * or a single animation spread over the arguments.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...animation(['rotate', '1s', 'ease-in-out'], ['colorchange', '2s'])\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${animation(['rotate', '1s', 'ease-in-out'], ['colorchange', '2s'])}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'animation': 'rotate 1s ease-in-out, colorchange 2s'\n * }\n * @example\n * // Styles as object usage\n * const styles = {\n * ...animation('rotate', '1s', 'ease-in-out')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${animation('rotate', '1s', 'ease-in-out')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'animation': 'rotate 1s ease-in-out'\n * }\n */\nfunction animation() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // Allow single or multiple animations passed\n var multiMode = Array.isArray(args[0]);\n\n if (!multiMode && args.length > 8) {\n throw new PolishedError(64);\n }\n\n var code = args.map(function (arg) {\n if (multiMode && !Array.isArray(arg) || !multiMode && Array.isArray(arg)) {\n throw new PolishedError(65);\n }\n\n if (Array.isArray(arg) && arg.length > 8) {\n throw new PolishedError(66);\n }\n\n return Array.isArray(arg) ? arg.join(' ') : arg;\n }).join(', ');\n return {\n animation: code\n };\n}\n\n/**\n * Shorthand that accepts any number of backgroundImage values as parameters for creating a single background statement.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...backgroundImages('url(\"/image/background.jpg\")', 'linear-gradient(red, green)')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${backgroundImages('url(\"/image/background.jpg\")', 'linear-gradient(red, green)')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'backgroundImage': 'url(\"/image/background.jpg\"), linear-gradient(red, green)'\n * }\n */\nfunction backgroundImages() {\n for (var _len = arguments.length, properties = new Array(_len), _key = 0; _key < _len; _key++) {\n properties[_key] = arguments[_key];\n }\n\n return {\n backgroundImage: properties.join(', ')\n };\n}\n\n/**\n * Shorthand that accepts any number of background values as parameters for creating a single background statement.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...backgrounds('url(\"/image/background.jpg\")', 'linear-gradient(red, green)', 'center no-repeat')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${backgrounds('url(\"/image/background.jpg\")', 'linear-gradient(red, green)', 'center no-repeat')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'background': 'url(\"/image/background.jpg\"), linear-gradient(red, green), center no-repeat'\n * }\n */\nfunction backgrounds() {\n for (var _len = arguments.length, properties = new Array(_len), _key = 0; _key < _len; _key++) {\n properties[_key] = arguments[_key];\n }\n\n return {\n background: properties.join(', ')\n };\n}\n\nvar sideMap = ['top', 'right', 'bottom', 'left'];\n/**\n * Shorthand for the border property that splits out individual properties for use with tools like Fela and Styletron. A side keyword can optionally be passed to target only one side's border properties.\n *\n * @example\n * // Styles as object usage\n * const styles = {\n * ...border('1px', 'solid', 'red')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${border('1px', 'solid', 'red')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'borderColor': 'red',\n * 'borderStyle': 'solid',\n * 'borderWidth': `1px`,\n * }\n *\n * // Styles as object usage\n * const styles = {\n * ...border('top', '1px', 'solid', 'red')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${border('top', '1px', 'solid', 'red')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'borderTopColor': 'red',\n * 'borderTopStyle': 'solid',\n * 'borderTopWidth': `1px`,\n * }\n */\n\nfunction border(sideKeyword) {\n for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n values[_key - 1] = arguments[_key];\n }\n\n if (typeof sideKeyword === 'string' && sideMap.indexOf(sideKeyword) >= 0) {\n var _ref;\n\n return _ref = {}, _ref[\"border\" + capitalizeString(sideKeyword) + \"Width\"] = values[0], _ref[\"border\" + capitalizeString(sideKeyword) + \"Style\"] = values[1], _ref[\"border\" + capitalizeString(sideKeyword) + \"Color\"] = values[2], _ref;\n } else {\n values.unshift(sideKeyword);\n return {\n borderWidth: values[0],\n borderStyle: values[1],\n borderColor: values[2]\n };\n }\n}\n\n/**\n * Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...borderColor('red', 'green', 'blue', 'yellow')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${borderColor('red', 'green', 'blue', 'yellow')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'borderTopColor': 'red',\n * 'borderRightColor': 'green',\n * 'borderBottomColor': 'blue',\n * 'borderLeftColor': 'yellow'\n * }\n */\nfunction borderColor() {\n for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {\n values[_key] = arguments[_key];\n }\n\n return directionalProperty.apply(void 0, ['borderColor'].concat(values));\n}\n\n/**\n * Shorthand that accepts a value for side and a value for radius and applies the radius value to both corners of the side.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...borderRadius('top', '5px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${borderRadius('top', '5px')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'borderTopRightRadius': '5px',\n * 'borderTopLeftRadius': '5px',\n * }\n */\nfunction borderRadius(side, radius) {\n var uppercaseSide = capitalizeString(side);\n\n if (!radius && radius !== 0) {\n throw new PolishedError(62);\n }\n\n if (uppercaseSide === 'Top' || uppercaseSide === 'Bottom') {\n var _ref;\n\n return _ref = {}, _ref[\"border\" + uppercaseSide + \"RightRadius\"] = radius, _ref[\"border\" + uppercaseSide + \"LeftRadius\"] = radius, _ref;\n }\n\n if (uppercaseSide === 'Left' || uppercaseSide === 'Right') {\n var _ref2;\n\n return _ref2 = {}, _ref2[\"borderTop\" + uppercaseSide + \"Radius\"] = radius, _ref2[\"borderBottom\" + uppercaseSide + \"Radius\"] = radius, _ref2;\n }\n\n throw new PolishedError(63);\n}\n\n/**\n * Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...borderStyle('solid', 'dashed', 'dotted', 'double')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${borderStyle('solid', 'dashed', 'dotted', 'double')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'borderTopStyle': 'solid',\n * 'borderRightStyle': 'dashed',\n * 'borderBottomStyle': 'dotted',\n * 'borderLeftStyle': 'double'\n * }\n */\nfunction borderStyle() {\n for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {\n values[_key] = arguments[_key];\n }\n\n return directionalProperty.apply(void 0, ['borderStyle'].concat(values));\n}\n\n/**\n * Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...borderWidth('12px', '24px', '36px', '48px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${borderWidth('12px', '24px', '36px', '48px')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'borderTopWidth': '12px',\n * 'borderRightWidth': '24px',\n * 'borderBottomWidth': '36px',\n * 'borderLeftWidth': '48px'\n * }\n */\nfunction borderWidth() {\n for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {\n values[_key] = arguments[_key];\n }\n\n return directionalProperty.apply(void 0, ['borderWidth'].concat(values));\n}\n\nfunction generateSelectors(template, state) {\n var stateSuffix = state ? \":\" + state : '';\n return template(stateSuffix);\n}\n/**\n * Function helper that adds an array of states to a template of selectors. Used in textInputs and buttons.\n * @private\n */\n\n\nfunction statefulSelectors(states, template, stateMap) {\n if (!template) throw new PolishedError(67);\n if (states.length === 0) return generateSelectors(template, null);\n var selectors = [];\n\n for (var i = 0; i < states.length; i += 1) {\n if (stateMap && stateMap.indexOf(states[i]) < 0) {\n throw new PolishedError(68);\n }\n\n selectors.push(generateSelectors(template, states[i]));\n }\n\n selectors = selectors.join(',');\n return selectors;\n}\n\nvar stateMap = [undefined, null, 'active', 'focus', 'hover'];\n\nfunction template(state) {\n return \"button\" + state + \",\\n input[type=\\\"button\\\"]\" + state + \",\\n input[type=\\\"reset\\\"]\" + state + \",\\n input[type=\\\"submit\\\"]\" + state;\n}\n/**\n * Populates selectors that target all buttons. You can pass optional states to append to the selectors.\n * @example\n * // Styles as object usage\n * const styles = {\n * [buttons('active')]: {\n * 'border': 'none'\n * }\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * > ${buttons('active')} {\n * border: none;\n * }\n * `\n *\n * // CSS in JS Output\n *\n * 'button:active,\n * 'input[type=\"button\"]:active,\n * 'input[type=\\\"reset\\\"]:active,\n * 'input[type=\\\"submit\\\"]:active: {\n * 'border': 'none'\n * }\n */\n\n\nfunction buttons() {\n for (var _len = arguments.length, states = new Array(_len), _key = 0; _key < _len; _key++) {\n states[_key] = arguments[_key];\n }\n\n return statefulSelectors(states, template, stateMap);\n}\n\n/**\n * Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...margin('12px', '24px', '36px', '48px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${margin('12px', '24px', '36px', '48px')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'marginTop': '12px',\n * 'marginRight': '24px',\n * 'marginBottom': '36px',\n * 'marginLeft': '48px'\n * }\n */\nfunction margin() {\n for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {\n values[_key] = arguments[_key];\n }\n\n return directionalProperty.apply(void 0, ['margin'].concat(values));\n}\n\n/**\n * Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...padding('12px', '24px', '36px', '48px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${padding('12px', '24px', '36px', '48px')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'paddingTop': '12px',\n * 'paddingRight': '24px',\n * 'paddingBottom': '36px',\n * 'paddingLeft': '48px'\n * }\n */\nfunction padding() {\n for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {\n values[_key] = arguments[_key];\n }\n\n return directionalProperty.apply(void 0, ['padding'].concat(values));\n}\n\nvar positionMap$1 = ['absolute', 'fixed', 'relative', 'static', 'sticky'];\n/**\n * Shorthand accepts up to five values, including null to skip a value, and maps them to their respective directions. The first value can optionally be a position keyword.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...position('12px', '24px', '36px', '48px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${position('12px', '24px', '36px', '48px')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'top': '12px',\n * 'right': '24px',\n * 'bottom': '36px',\n * 'left': '48px'\n * }\n *\n * // Styles as object usage\n * const styles = {\n * ...position('absolute', '12px', '24px', '36px', '48px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${position('absolute', '12px', '24px', '36px', '48px')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'position': 'absolute',\n * 'top': '12px',\n * 'right': '24px',\n * 'bottom': '36px',\n * 'left': '48px'\n * }\n */\n\nfunction position(firstValue) {\n for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n values[_key - 1] = arguments[_key];\n }\n\n if (positionMap$1.indexOf(firstValue) >= 0 && firstValue) {\n return _extends({}, directionalProperty.apply(void 0, [''].concat(values)), {\n position: firstValue\n });\n } else {\n return directionalProperty.apply(void 0, ['', firstValue].concat(values));\n }\n}\n\n/**\n * Shorthand to set the height and width properties in a single statement.\n * @example\n * // Styles as object usage\n * const styles = {\n * ...size('300px', '250px')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${size('300px', '250px')}\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'height': '300px',\n * 'width': '250px',\n * }\n */\nfunction size(height, width) {\n if (width === void 0) {\n width = height;\n }\n\n return {\n height: height,\n width: width\n };\n}\n\nvar stateMap$1 = [undefined, null, 'active', 'focus', 'hover'];\n\nfunction template$1(state) {\n return \"input[type=\\\"color\\\"]\" + state + \",\\n input[type=\\\"date\\\"]\" + state + \",\\n input[type=\\\"datetime\\\"]\" + state + \",\\n input[type=\\\"datetime-local\\\"]\" + state + \",\\n input[type=\\\"email\\\"]\" + state + \",\\n input[type=\\\"month\\\"]\" + state + \",\\n input[type=\\\"number\\\"]\" + state + \",\\n input[type=\\\"password\\\"]\" + state + \",\\n input[type=\\\"search\\\"]\" + state + \",\\n input[type=\\\"tel\\\"]\" + state + \",\\n input[type=\\\"text\\\"]\" + state + \",\\n input[type=\\\"time\\\"]\" + state + \",\\n input[type=\\\"url\\\"]\" + state + \",\\n input[type=\\\"week\\\"]\" + state + \",\\n input:not([type])\" + state + \",\\n textarea\" + state;\n}\n/**\n * Populates selectors that target all text inputs. You can pass optional states to append to the selectors.\n * @example\n * // Styles as object usage\n * const styles = {\n * [textInputs('active')]: {\n * 'border': 'none'\n * }\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * > ${textInputs('active')} {\n * border: none;\n * }\n * `\n *\n * // CSS in JS Output\n *\n * 'input[type=\"color\"]:active,\n * input[type=\"date\"]:active,\n * input[type=\"datetime\"]:active,\n * input[type=\"datetime-local\"]:active,\n * input[type=\"email\"]:active,\n * input[type=\"month\"]:active,\n * input[type=\"number\"]:active,\n * input[type=\"password\"]:active,\n * input[type=\"search\"]:active,\n * input[type=\"tel\"]:active,\n * input[type=\"text\"]:active,\n * input[type=\"time\"]:active,\n * input[type=\"url\"]:active,\n * input[type=\"week\"]:active,\n * input:not([type]):active,\n * textarea:active': {\n * 'border': 'none'\n * }\n */\n\n\nfunction textInputs() {\n for (var _len = arguments.length, states = new Array(_len), _key = 0; _key < _len; _key++) {\n states[_key] = arguments[_key];\n }\n\n return statefulSelectors(states, template$1, stateMap$1);\n}\n\n/**\n * Accepts any number of transition values as parameters for creating a single transition statement. You may also pass an array of properties as the first parameter that you would like to apply the same transition values to (second parameter).\n * @example\n * // Styles as object usage\n * const styles = {\n * ...transitions('opacity 1.0s ease-in 0s', 'width 2.0s ease-in 2s'),\n * ...transitions(['color', 'background-color'], '2.0s ease-in 2s')\n * }\n *\n * // styled-components usage\n * const div = styled.div`\n * ${transitions('opacity 1.0s ease-in 0s', 'width 2.0s ease-in 2s')};\n * ${transitions(['color', 'background-color'], '2.0s ease-in 2s'),};\n * `\n *\n * // CSS as JS Output\n *\n * div {\n * 'transition': 'opacity 1.0s ease-in 0s, width 2.0s ease-in 2s'\n * 'transition': 'color 2.0s ease-in 2s, background-color 2.0s ease-in 2s',\n * }\n */\n\nfunction transitions() {\n for (var _len = arguments.length, properties = new Array(_len), _key = 0; _key < _len; _key++) {\n properties[_key] = arguments[_key];\n }\n\n if (Array.isArray(properties[0]) && properties.length === 2) {\n var value = properties[1];\n\n if (typeof value !== 'string') {\n throw new PolishedError(61);\n }\n\n var transitionsString = properties[0].map(function (property) {\n return property + \" \" + value;\n }).join(', ');\n return {\n transition: transitionsString\n };\n } else {\n return {\n transition: properties.join(', ')\n };\n }\n}\n\nexport { curriedAdjustHue as adjustHue, animation, backgroundImages, backgrounds, between, border, borderColor, borderRadius, borderStyle, borderWidth, buttons, clearFix, complement, cover, cssVar, curriedDarken as darken, curriedDesaturate as desaturate, directionalProperty, ellipsis, em, fluidRange, fontFace, getContrast, getLuminance, getValueAndUnit, grayscale, hiDPI, hideText, hideVisually, hsl, hslToColorString, hsla, invert, curriedLighten as lighten, linearGradient, margin, math, meetsContrastGuidelines, curriedMix as mix, modularScale, normalize, curriedOpacify as opacify, padding, parseToHsl, parseToRgb, position, radialGradient, readableColor, rem, retinaImage, rgb, rgbToColorString, rgba, curriedSaturate as saturate, curriedSetHue as setHue, curriedSetLightness as setLightness, curriedSetSaturation as setSaturation, curriedShade as shade, size, stripUnit, textInputs, timingFunctions, curriedTint as tint, toColorString, transitions, curriedTransparentize as transparentize, triangle, wordWrap };\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {FocusableElement} from '@react-types/shared';\nimport {focusWithoutScrolling, runAfterTransition} from '@react-aria/utils';\nimport {getInteractionModality} from '@react-aria/interactions';\n\n/**\n * A utility function that focuses an element while avoiding undesired side effects such\n * as page scrolling and screen reader issues with CSS transitions.\n */\nexport function focusSafely(element: FocusableElement) {\n // If the user is interacting with a virtual cursor, e.g. screen reader, then\n // wait until after any animated transitions that are currently occurring on\n // the page before shifting focus. This avoids issues with VoiceOver on iOS\n // causing the page to scroll when moving focus if the element is transitioning\n // from off the screen.\n if (getInteractionModality() === 'virtual') {\n let lastFocusedElement = document.activeElement;\n runAfterTransition(() => {\n // If focus did not move and the element is still in the document, focus it.\n if (document.activeElement === lastFocusedElement && document.contains(element)) {\n focusWithoutScrolling(element);\n }\n });\n } else {\n focusWithoutScrolling(element);\n }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {FocusableElement} from '@react-types/shared';\nimport {focusSafely} from './focusSafely';\nimport {isElementVisible} from './isElementVisible';\nimport React, {ReactNode, RefObject, useContext, useEffect, useRef} from 'react';\nimport {useLayoutEffect} from '@react-aria/utils';\n\n\nexport interface FocusScopeProps {\n /** The contents of the focus scope. */\n children: ReactNode,\n\n /**\n * Whether to contain focus inside the scope, so users cannot\n * move focus outside, for example in a modal dialog.\n */\n contain?: boolean,\n\n /**\n * Whether to restore focus back to the element that was focused\n * when the focus scope mounted, after the focus scope unmounts.\n */\n restoreFocus?: boolean,\n\n /** Whether to auto focus the first focusable element in the focus scope on mount. */\n autoFocus?: boolean\n}\n\nexport interface FocusManagerOptions {\n /** The element to start searching from. The currently focused element by default. */\n from?: Element,\n /** Whether to only include tabbable elements, or all focusable elements. */\n tabbable?: boolean,\n /** Whether focus should wrap around when it reaches the end of the scope. */\n wrap?: boolean,\n /** A callback that determines whether the given element is focused. */\n accept?: (node: Element) => boolean\n}\n\nexport interface FocusManager {\n /** Moves focus to the next focusable or tabbable element in the focus scope. */\n focusNext(opts?: FocusManagerOptions): FocusableElement,\n /** Moves focus to the previous focusable or tabbable element in the focus scope. */\n focusPrevious(opts?: FocusManagerOptions): FocusableElement,\n /** Moves focus to the first focusable or tabbable element in the focus scope. */\n focusFirst(opts?: FocusManagerOptions): FocusableElement,\n /** Moves focus to the last focusable or tabbable element in the focus scope. */\n focusLast(opts?: FocusManagerOptions): FocusableElement\n}\n\ntype ScopeRef = RefObject;\ninterface IFocusContext {\n scopeRef: ScopeRef,\n focusManager: FocusManager\n}\n\nconst FocusContext = React.createContext(null);\n\nlet activeScope: ScopeRef = null;\n\n// This is a hacky DOM-based implementation of a FocusScope until this RFC lands in React:\n// https://github.com/reactjs/rfcs/pull/109\n\n/**\n * A FocusScope manages focus for its descendants. It supports containing focus inside\n * the scope, restoring focus to the previously focused element on unmount, and auto\n * focusing children on mount. It also acts as a container for a programmatic focus\n * management interface that can be used to move focus forward and back in response\n * to user events.\n */\nexport function FocusScope(props: FocusScopeProps) {\n let {children, contain, restoreFocus, autoFocus} = props;\n let startRef = useRef();\n let endRef = useRef();\n let scopeRef = useRef([]);\n let ctx = useContext(FocusContext);\n // if there is no scopeRef on the context, then the parent is the focusScopeTree's root, represented by null\n let parentScope = ctx?.scopeRef ?? null;\n\n useLayoutEffect(() => {\n // Find all rendered nodes between the sentinels and add them to the scope.\n let node = startRef.current.nextSibling;\n let nodes = [];\n while (node && node !== endRef.current) {\n nodes.push(node);\n node = node.nextSibling;\n }\n\n scopeRef.current = nodes;\n }, [children, parentScope]);\n\n // add to the focus scope tree in render order because useEffects/useLayoutEffects run children first whereas render runs parent first\n // which matters when constructing a tree\n if (focusScopeTree.getTreeNode(parentScope) && !focusScopeTree.getTreeNode(scopeRef)) {\n focusScopeTree.addTreeNode(scopeRef, parentScope);\n }\n\n let node = focusScopeTree.getTreeNode(scopeRef);\n node.contain = contain;\n\n useFocusContainment(scopeRef, contain);\n useRestoreFocus(scopeRef, restoreFocus, contain);\n useAutoFocus(scopeRef, autoFocus);\n\n // this layout effect needs to run last so that focusScopeTree cleanup happens at the last moment possible\n useLayoutEffect(() => {\n if (scopeRef && (parentScope || parentScope == null)) {\n return () => {\n // Restore the active scope on unmount if this scope or a descendant scope is active.\n // Parent effect cleanups run before children, so we need to check if the\n // parent scope actually still exists before restoring the active scope to it.\n if (\n (scopeRef === activeScope || isAncestorScope(scopeRef, activeScope)) &&\n (!parentScope || focusScopeTree.getTreeNode(parentScope))\n ) {\n activeScope = parentScope;\n }\n focusScopeTree.removeTreeNode(scopeRef);\n };\n }\n }, [scopeRef, parentScope]);\n\n let focusManager = createFocusManagerForScope(scopeRef);\n\n return (\n \n \n );\n}\n\n/**\n * Returns a FocusManager interface for the parent FocusScope.\n * A FocusManager can be used to programmatically move focus within\n * a FocusScope, e.g. in response to user events like keyboard navigation.\n */\nexport function useFocusManager(): FocusManager {\n return useContext(FocusContext)?.focusManager;\n}\n\nfunction createFocusManagerForScope(scopeRef: React.RefObject): FocusManager {\n return {\n focusNext(opts: FocusManagerOptions = {}) {\n let scope = scopeRef.current;\n let {from, tabbable, wrap, accept} = opts;\n let node = from || document.activeElement;\n let sentinel = scope[0].previousElementSibling;\n let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable, accept}, scope);\n walker.currentNode = isElementInScope(node, scope) ? node : sentinel;\n let nextNode = walker.nextNode() as FocusableElement;\n if (!nextNode && wrap) {\n walker.currentNode = sentinel;\n nextNode = walker.nextNode() as FocusableElement;\n }\n if (nextNode) {\n focusElement(nextNode, true);\n }\n return nextNode;\n },\n focusPrevious(opts: FocusManagerOptions = {}) {\n let scope = scopeRef.current;\n let {from, tabbable, wrap, accept} = opts;\n let node = from || document.activeElement;\n let sentinel = scope[scope.length - 1].nextElementSibling;\n let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable, accept}, scope);\n walker.currentNode = isElementInScope(node, scope) ? node : sentinel;\n let previousNode = walker.previousNode() as FocusableElement;\n if (!previousNode && wrap) {\n walker.currentNode = sentinel;\n previousNode = walker.previousNode() as FocusableElement;\n }\n if (previousNode) {\n focusElement(previousNode, true);\n }\n return previousNode;\n },\n focusFirst(opts = {}) {\n let scope = scopeRef.current;\n let {tabbable, accept} = opts;\n let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable, accept}, scope);\n walker.currentNode = scope[0].previousElementSibling;\n let nextNode = walker.nextNode() as FocusableElement;\n if (nextNode) {\n focusElement(nextNode, true);\n }\n return nextNode;\n },\n focusLast(opts = {}) {\n let scope = scopeRef.current;\n let {tabbable, accept} = opts;\n let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable, accept}, scope);\n walker.currentNode = scope[scope.length - 1].nextElementSibling;\n let previousNode = walker.previousNode() as FocusableElement;\n if (previousNode) {\n focusElement(previousNode, true);\n }\n return previousNode;\n }\n };\n}\n\nconst focusableElements = [\n 'input:not([disabled]):not([type=hidden])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n 'button:not([disabled])',\n 'a[href]',\n 'area[href]',\n 'summary',\n 'iframe',\n 'object',\n 'embed',\n 'audio[controls]',\n 'video[controls]',\n '[contenteditable]'\n];\n\nconst FOCUSABLE_ELEMENT_SELECTOR = focusableElements.join(':not([hidden]),') + ',[tabindex]:not([disabled]):not([hidden])';\n\nfocusableElements.push('[tabindex]:not([tabindex=\"-1\"]):not([disabled])');\nconst TABBABLE_ELEMENT_SELECTOR = focusableElements.join(':not([hidden]):not([tabindex=\"-1\"]),');\n\nfunction getScopeRoot(scope: Element[]) {\n return scope[0].parentElement;\n}\n\nfunction shouldContainFocus(scopeRef: ScopeRef) {\n let scope = focusScopeTree.getTreeNode(activeScope);\n while (scope && scope.scopeRef !== scopeRef) {\n if (scope.contain) {\n return false;\n }\n\n scope = scope.parent;\n }\n\n return true;\n}\n\nfunction useFocusContainment(scopeRef: RefObject, contain: boolean) {\n let focusedNode = useRef();\n\n let raf = useRef(null);\n useLayoutEffect(() => {\n let scope = scopeRef.current;\n if (!contain) {\n // if contain was changed, then we should cancel any ongoing waits to pull focus back into containment\n if (raf.current) {\n cancelAnimationFrame(raf.current);\n raf.current = null;\n }\n return;\n }\n\n // Handle the Tab key to contain focus within the scope\n let onKeyDown = (e) => {\n if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey || !shouldContainFocus(scopeRef)) {\n return;\n }\n\n let focusedElement = document.activeElement;\n let scope = scopeRef.current;\n if (!isElementInScope(focusedElement, scope)) {\n return;\n }\n\n let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable: true}, scope);\n walker.currentNode = focusedElement;\n let nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;\n if (!nextElement) {\n walker.currentNode = e.shiftKey ? scope[scope.length - 1].nextElementSibling : scope[0].previousElementSibling;\n nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;\n }\n\n e.preventDefault();\n if (nextElement) {\n focusElement(nextElement, true);\n }\n };\n\n let onFocus = (e) => {\n // If focusing an element in a child scope of the currently active scope, the child becomes active.\n // Moving out of the active scope to an ancestor is not allowed.\n if (!activeScope || isAncestorScope(activeScope, scopeRef)) {\n activeScope = scopeRef;\n focusedNode.current = e.target;\n } else if (shouldContainFocus(scopeRef) && !isElementInChildScope(e.target, scopeRef)) {\n // If a focus event occurs outside the active scope (e.g. user tabs from browser location bar),\n // restore focus to the previously focused node or the first tabbable element in the active scope.\n if (focusedNode.current) {\n focusedNode.current.focus();\n } else if (activeScope) {\n focusFirstInScope(activeScope.current);\n }\n } else if (shouldContainFocus(scopeRef)) {\n focusedNode.current = e.target;\n }\n };\n\n let onBlur = (e) => {\n // Firefox doesn't shift focus back to the Dialog properly without this\n raf.current = requestAnimationFrame(() => {\n // Use document.activeElement instead of e.relatedTarget so we can tell if user clicked into iframe\n if (shouldContainFocus(scopeRef) && !isElementInChildScope(document.activeElement, scopeRef)) {\n activeScope = scopeRef;\n if (document.body.contains(e.target)) {\n focusedNode.current = e.target;\n focusedNode.current.focus();\n } else if (activeScope) {\n focusFirstInScope(activeScope.current);\n }\n }\n });\n };\n\n document.addEventListener('keydown', onKeyDown, false);\n document.addEventListener('focusin', onFocus, false);\n scope.forEach(element => element.addEventListener('focusin', onFocus, false));\n scope.forEach(element => element.addEventListener('focusout', onBlur, false));\n return () => {\n document.removeEventListener('keydown', onKeyDown, false);\n document.removeEventListener('focusin', onFocus, false);\n scope.forEach(element => element.removeEventListener('focusin', onFocus, false));\n scope.forEach(element => element.removeEventListener('focusout', onBlur, false));\n };\n }, [scopeRef, contain]);\n\n // eslint-disable-next-line arrow-body-style\n useEffect(() => {\n return () => {\n if (raf.current) {\n cancelAnimationFrame(raf.current);\n }\n };\n }, [raf]);\n}\n\nfunction isElementInAnyScope(element: Element) {\n return isElementInChildScope(element);\n}\n\nfunction isElementInScope(element: Element, scope: Element[]) {\n return scope.some(node => node.contains(element));\n}\n\nfunction isElementInChildScope(element: Element, scope: ScopeRef = null) {\n // node.contains in isElementInScope covers child scopes that are also DOM children,\n // but does not cover child scopes in portals.\n for (let {scopeRef: s} of focusScopeTree.traverse(focusScopeTree.getTreeNode(scope))) {\n if (isElementInScope(element, s.current)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction isAncestorScope(ancestor: ScopeRef, scope: ScopeRef) {\n let parent = focusScopeTree.getTreeNode(scope)?.parent;\n while (parent) {\n if (parent.scopeRef === ancestor) {\n return true;\n }\n parent = parent.parent;\n }\n return false;\n}\n\nfunction focusElement(element: FocusableElement | null, scroll = false) {\n if (element != null && !scroll) {\n try {\n focusSafely(element);\n } catch (err) {\n // ignore\n }\n } else if (element != null) {\n try {\n element.focus();\n } catch (err) {\n // ignore\n }\n }\n}\n\nfunction focusFirstInScope(scope: Element[], tabbable:boolean = true) {\n let sentinel = scope[0].previousElementSibling;\n let walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable}, scope);\n walker.currentNode = sentinel;\n let nextNode = walker.nextNode();\n\n // If the scope does not contain a tabbable element, use the first focusable element.\n if (tabbable && !nextNode) {\n walker = getFocusableTreeWalker(getScopeRoot(scope), {tabbable: false}, scope);\n walker.currentNode = sentinel;\n nextNode = walker.nextNode();\n }\n\n focusElement(nextNode as FocusableElement);\n}\n\nfunction useAutoFocus(scopeRef: RefObject, autoFocus: boolean) {\n const autoFocusRef = React.useRef(autoFocus);\n useEffect(() => {\n if (autoFocusRef.current) {\n activeScope = scopeRef;\n if (!isElementInScope(document.activeElement, activeScope.current)) {\n focusFirstInScope(scopeRef.current);\n }\n }\n autoFocusRef.current = false;\n }, [scopeRef]);\n}\n\nfunction useRestoreFocus(scopeRef: RefObject, restoreFocus: boolean, contain: boolean) {\n // create a ref during render instead of useLayoutEffect so the active element is saved before a child with autoFocus=true mounts.\n const nodeToRestoreRef = useRef(typeof document !== 'undefined' ? document.activeElement as FocusableElement : null);\n\n // restoring scopes should all track if they are active regardless of contain, but contain already tracks it plus logic to contain the focus\n // restoring-non-containing scopes should only care if they become active so they can perform the restore\n useLayoutEffect(() => {\n let scope = scopeRef.current;\n if (!restoreFocus || contain) {\n return;\n }\n\n let onFocus = () => {\n // If focusing an element in a child scope of the currently active scope, the child becomes active.\n // Moving out of the active scope to an ancestor is not allowed.\n if (!activeScope || isAncestorScope(activeScope, scopeRef)) {\n activeScope = scopeRef;\n }\n };\n\n document.addEventListener('focusin', onFocus, false);\n scope.forEach(element => element.addEventListener('focusin', onFocus, false));\n return () => {\n document.removeEventListener('focusin', onFocus, false);\n scope.forEach(element => element.removeEventListener('focusin', onFocus, false));\n };\n }, [scopeRef, contain]);\n\n // useLayoutEffect instead of useEffect so the active element is saved synchronously instead of asynchronously.\n useLayoutEffect(() => {\n focusScopeTree.getTreeNode(scopeRef).nodeToRestore = nodeToRestoreRef.current;\n if (!restoreFocus) {\n return;\n }\n\n // Handle the Tab key so that tabbing out of the scope goes to the next element\n // after the node that had focus when the scope mounted. This is important when\n // using portals for overlays, so that focus goes to the expected element when\n // tabbing out of the overlay.\n let onKeyDown = (e: KeyboardEvent) => {\n if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey) {\n return;\n }\n\n let focusedElement = document.activeElement as FocusableElement;\n if (!isElementInScope(focusedElement, scopeRef.current)) {\n return;\n }\n let nodeToRestore = focusScopeTree.getTreeNode(scopeRef).nodeToRestore;\n\n // Create a DOM tree walker that matches all tabbable elements\n let walker = getFocusableTreeWalker(document.body, {tabbable: true});\n\n // Find the next tabbable element after the currently focused element\n walker.currentNode = focusedElement;\n let nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;\n\n if (!document.body.contains(nodeToRestore) || nodeToRestore === document.body) {\n nodeToRestore = null;\n focusScopeTree.getTreeNode(scopeRef).nodeToRestore = null;\n }\n\n // If there is no next element, or it is outside the current scope, move focus to the\n // next element after the node to restore to instead.\n if ((!nextElement || !isElementInScope(nextElement, scopeRef.current)) && nodeToRestore) {\n walker.currentNode = nodeToRestore;\n\n // Skip over elements within the scope, in case the scope immediately follows the node to restore.\n do {\n nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;\n } while (isElementInScope(nextElement, scopeRef.current));\n\n e.preventDefault();\n e.stopPropagation();\n if (nextElement) {\n focusElement(nextElement, true);\n } else {\n // If there is no next element and the nodeToRestore isn't within a FocusScope (i.e. we are leaving the top level focus scope)\n // then move focus to the body.\n // Otherwise restore focus to the nodeToRestore (e.g menu within a popover -> tabbing to close the menu should move focus to menu trigger)\n if (!isElementInAnyScope(nodeToRestore)) {\n focusedElement.blur();\n } else {\n focusElement(nodeToRestore, true);\n }\n }\n }\n };\n\n if (!contain) {\n document.addEventListener('keydown', onKeyDown, true);\n }\n\n return () => {\n if (!contain) {\n document.removeEventListener('keydown', onKeyDown, true);\n }\n let nodeToRestore = focusScopeTree.getTreeNode(scopeRef).nodeToRestore;\n\n // if we already lost focus to the body and this was the active scope, then we should attempt to restore\n if (\n restoreFocus\n && nodeToRestore\n && (\n isElementInScope(document.activeElement, scopeRef.current)\n || (document.activeElement === document.body && activeScope === scopeRef)\n )\n ) {\n // freeze the focusScopeTree so it persists after the raf, otherwise during unmount nodes are removed from it\n let clonedTree = focusScopeTree.clone();\n requestAnimationFrame(() => {\n // Only restore focus if we've lost focus to the body, the alternative is that focus has been purposefully moved elsewhere\n if (document.activeElement === document.body) {\n // look up the tree starting with our scope to find a nodeToRestore still in the DOM\n let treeNode = clonedTree.getTreeNode(scopeRef);\n while (treeNode) {\n if (treeNode.nodeToRestore && document.body.contains(treeNode.nodeToRestore)) {\n focusElement(treeNode.nodeToRestore);\n return;\n }\n treeNode = treeNode.parent;\n }\n }\n });\n }\n };\n }, [scopeRef, restoreFocus, contain]);\n}\n\n/**\n * Create a [TreeWalker]{@link https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker}\n * that matches all focusable/tabbable elements.\n */\nexport function getFocusableTreeWalker(root: Element, opts?: FocusManagerOptions, scope?: Element[]) {\n let selector = opts?.tabbable ? TABBABLE_ELEMENT_SELECTOR : FOCUSABLE_ELEMENT_SELECTOR;\n let walker = document.createTreeWalker(\n root,\n NodeFilter.SHOW_ELEMENT,\n {\n acceptNode(node) {\n // Skip nodes inside the starting node.\n if (opts?.from?.contains(node)) {\n return NodeFilter.FILTER_REJECT;\n }\n\n if ((node as Element).matches(selector)\n && isElementVisible(node as Element)\n && (!scope || isElementInScope(node as Element, scope))\n && (!opts?.accept || opts.accept(node as Element))\n ) {\n return NodeFilter.FILTER_ACCEPT;\n }\n\n return NodeFilter.FILTER_SKIP;\n }\n }\n );\n\n if (opts?.from) {\n walker.currentNode = opts.from;\n }\n\n return walker;\n}\n\n/**\n * Creates a FocusManager object that can be used to move focus within an element.\n */\nexport function createFocusManager(ref: RefObject, defaultOptions: FocusManagerOptions = {}): FocusManager {\n return {\n focusNext(opts: FocusManagerOptions = {}) {\n let root = ref.current;\n if (!root) {\n return;\n }\n let {from, tabbable = defaultOptions.tabbable, wrap = defaultOptions.wrap, accept = defaultOptions.accept} = opts;\n let node = from || document.activeElement;\n let walker = getFocusableTreeWalker(root, {tabbable, accept});\n if (root.contains(node)) {\n walker.currentNode = node;\n }\n let nextNode = walker.nextNode() as FocusableElement;\n if (!nextNode && wrap) {\n walker.currentNode = root;\n nextNode = walker.nextNode() as FocusableElement;\n }\n if (nextNode) {\n focusElement(nextNode, true);\n }\n return nextNode;\n },\n focusPrevious(opts: FocusManagerOptions = defaultOptions) {\n let root = ref.current;\n if (!root) {\n return;\n }\n let {from, tabbable = defaultOptions.tabbable, wrap = defaultOptions.wrap, accept = defaultOptions.accept} = opts;\n let node = from || document.activeElement;\n let walker = getFocusableTreeWalker(root, {tabbable, accept});\n if (root.contains(node)) {\n walker.currentNode = node;\n } else {\n let next = last(walker);\n if (next) {\n focusElement(next, true);\n }\n return next;\n }\n let previousNode = walker.previousNode() as FocusableElement;\n if (!previousNode && wrap) {\n walker.currentNode = root;\n previousNode = last(walker);\n }\n if (previousNode) {\n focusElement(previousNode, true);\n }\n return previousNode;\n },\n focusFirst(opts = defaultOptions) {\n let root = ref.current;\n if (!root) {\n return;\n }\n let {tabbable = defaultOptions.tabbable, accept = defaultOptions.accept} = opts;\n let walker = getFocusableTreeWalker(root, {tabbable, accept});\n let nextNode = walker.nextNode() as FocusableElement;\n if (nextNode) {\n focusElement(nextNode, true);\n }\n return nextNode;\n },\n focusLast(opts = defaultOptions) {\n let root = ref.current;\n if (!root) {\n return;\n }\n let {tabbable = defaultOptions.tabbable, accept = defaultOptions.accept} = opts;\n let walker = getFocusableTreeWalker(root, {tabbable, accept});\n let next = last(walker);\n if (next) {\n focusElement(next, true);\n }\n return next;\n }\n };\n}\n\nfunction last(walker: TreeWalker) {\n let next: FocusableElement;\n let last: FocusableElement;\n do {\n last = walker.lastChild() as FocusableElement;\n if (last) {\n next = last;\n }\n } while (last);\n return next;\n}\n\n\nclass Tree {\n private root: TreeNode;\n private fastMap = new Map();\n\n constructor() {\n this.root = new TreeNode({scopeRef: null});\n this.fastMap.set(null, this.root);\n }\n\n get size() {\n return this.fastMap.size;\n }\n\n getTreeNode(data: ScopeRef) {\n return this.fastMap.get(data);\n }\n\n addTreeNode(scopeRef: ScopeRef, parent: ScopeRef, nodeToRestore?: FocusableElement) {\n let parentNode = this.fastMap.get(parent ?? null);\n let node = new TreeNode({scopeRef});\n parentNode.addChild(node);\n node.parent = parentNode;\n this.fastMap.set(scopeRef, node);\n if (nodeToRestore) {\n node.nodeToRestore = nodeToRestore;\n }\n }\n\n removeTreeNode(scopeRef: ScopeRef) {\n // never remove the root\n if (scopeRef === null) {\n return;\n }\n let node = this.fastMap.get(scopeRef);\n let parentNode = node.parent;\n // when we remove a scope, check if any sibling scopes are trying to restore focus to something inside the scope we're removing\n // if we are, then replace the siblings restore with the restore from the scope we're removing\n for (let current of this.traverse()) {\n if (\n current !== node &&\n node.nodeToRestore &&\n current.nodeToRestore &&\n node.scopeRef.current &&\n isElementInScope(current.nodeToRestore, node.scopeRef.current)\n ) {\n current.nodeToRestore = node.nodeToRestore;\n }\n }\n let children = node.children;\n parentNode.removeChild(node);\n if (children.length > 0) {\n children.forEach(child => parentNode.addChild(child));\n }\n this.fastMap.delete(node.scopeRef);\n }\n\n // Pre Order Depth First\n *traverse(node: TreeNode = this.root): Generator {\n if (node.scopeRef != null) {\n yield node;\n }\n if (node.children.length > 0) {\n for (let child of node.children) {\n yield* this.traverse(child);\n }\n }\n }\n\n clone(): Tree {\n let newTree = new Tree();\n for (let node of this.traverse()) {\n newTree.addTreeNode(node.scopeRef, node.parent.scopeRef, node.nodeToRestore);\n }\n return newTree;\n }\n}\n\nclass TreeNode {\n public scopeRef: ScopeRef;\n public nodeToRestore: FocusableElement;\n public parent: TreeNode;\n public children: TreeNode[] = [];\n public contain = false;\n\n constructor(props: {scopeRef: ScopeRef}) {\n this.scopeRef = props.scopeRef;\n }\n addChild(node: TreeNode) {\n this.children.push(node);\n node.parent = this;\n }\n removeChild(node: TreeNode) {\n this.children.splice(this.children.indexOf(node), 1);\n node.parent = undefined;\n }\n}\n\nexport let focusScopeTree = new Tree();\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {DOMAttributes, FocusableDOMProps, FocusableElement, FocusableProps} from '@react-types/shared';\nimport {focusSafely} from './';\nimport {mergeProps, useSyncRef} from '@react-aria/utils';\nimport React, {MutableRefObject, ReactNode, RefObject, useContext, useEffect, useRef} from 'react';\nimport {useFocus, useKeyboard} from '@react-aria/interactions';\n\nexport interface FocusableOptions extends FocusableProps, FocusableDOMProps {\n /** Whether focus should be disabled. */\n isDisabled?: boolean\n}\n\nexport interface FocusableProviderProps extends DOMAttributes {\n /** The child element to provide DOM props to. */\n children?: ReactNode\n}\n\ninterface FocusableContextValue extends FocusableProviderProps {\n ref?: MutableRefObject\n}\n\nlet FocusableContext = React.createContext(null);\n\nfunction useFocusableContext(ref: RefObject): FocusableContextValue {\n let context = useContext(FocusableContext) || {};\n useSyncRef(context, ref);\n\n // eslint-disable-next-line\n let {ref: _, ...otherProps} = context;\n return otherProps;\n}\n\n/**\n * Provides DOM props to the nearest focusable child.\n */\nfunction FocusableProvider(props: FocusableProviderProps, ref: RefObject) {\n let {children, ...otherProps} = props;\n let context = {\n ...otherProps,\n ref\n };\n\n return (\n \n {children}\n \n );\n}\n\nlet _FocusableProvider = React.forwardRef(FocusableProvider);\nexport {_FocusableProvider as FocusableProvider};\n\nexport interface FocusableAria {\n /** Props for the focusable element. */\n focusableProps: DOMAttributes\n}\n\n/**\n * Used to make an element focusable and capable of auto focus.\n */\nexport function useFocusable(props: FocusableOptions, domRef: RefObject): FocusableAria {\n let {focusProps} = useFocus(props);\n let {keyboardProps} = useKeyboard(props);\n let interactions = mergeProps(focusProps, keyboardProps);\n let domProps = useFocusableContext(domRef);\n let interactionProps = props.isDisabled ? {} : domProps;\n let autoFocusRef = useRef(props.autoFocus);\n\n useEffect(() => {\n if (autoFocusRef.current && domRef.current) {\n focusSafely(domRef.current);\n }\n autoFocusRef.current = false;\n }, [domRef]);\n\n return {\n focusableProps: mergeProps(\n {\n ...interactions,\n tabIndex: props.excludeFromTabOrder && !props.isDisabled ? -1 : undefined\n },\n interactionProps\n )\n };\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from react.\n// Original licensing for the following can be found in the\n// NOTICE file in the root directory of this source tree.\n// See https://github.com/facebook/react/tree/cc7c1aece46a6b69b41958d731e0fd27c94bfc6c/packages/react-interactions\n\nimport {DOMAttributes, FocusEvents} from '@react-types/shared';\nimport {FocusEvent, useCallback} from 'react';\nimport {useSyntheticBlurEvent} from './utils';\n\nexport interface FocusProps extends FocusEvents {\n /** Whether the focus events should be disabled. */\n isDisabled?: boolean\n}\n\nexport interface FocusResult {\n /** Props to spread onto the target element. */\n focusProps: DOMAttributes\n}\n\n/**\n * Handles focus events for the immediate target.\n * Focus events on child elements will be ignored.\n */\nexport function useFocus(props: FocusProps): FocusResult {\n let {\n isDisabled,\n onFocus: onFocusProp,\n onBlur: onBlurProp,\n onFocusChange\n } = props;\n\n const onBlur: FocusProps['onBlur'] = useCallback((e: FocusEvent) => {\n if (e.target === e.currentTarget) {\n if (onBlurProp) {\n onBlurProp(e);\n }\n\n if (onFocusChange) {\n onFocusChange(false);\n }\n\n return true;\n }\n }, [onBlurProp, onFocusChange]);\n\n\n const onSyntheticFocus = useSyntheticBlurEvent(onBlur);\n\n const onFocus: FocusProps['onFocus'] = useCallback((e: FocusEvent) => {\n if (e.target === e.currentTarget) {\n if (onFocusProp) {\n onFocusProp(e);\n }\n\n if (onFocusChange) {\n onFocusChange(true);\n }\n\n onSyntheticFocus(e);\n }\n }, [onFocusChange, onFocusProp, onSyntheticFocus]);\n\n return {\n focusProps: {\n onFocus: (!isDisabled && (onFocusProp || onFocusChange || onBlurProp)) ? onFocus : undefined,\n onBlur: (!isDisabled && (onBlurProp || onFocusChange)) ? onBlur : null\n }\n };\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {createEventHandler} from './createEventHandler';\nimport {DOMAttributes, KeyboardEvents} from '@react-types/shared';\n\nexport interface KeyboardProps extends KeyboardEvents {\n /** Whether the keyboard events should be disabled. */\n isDisabled?: boolean\n}\n\nexport interface KeyboardResult {\n /** Props to spread onto the target element. */\n keyboardProps: DOMAttributes\n}\n\n/**\n * Handles keyboard interactions for a focusable element.\n */\nexport function useKeyboard(props: KeyboardProps): KeyboardResult {\n return {\n keyboardProps: props.isDisabled ? {} : {\n onKeyDown: createEventHandler(props.onKeyDown),\n onKeyUp: createEventHandler(props.onKeyUp)\n }\n };\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {\n AnchorHTMLAttributes,\n ButtonHTMLAttributes,\n ElementType,\n HTMLAttributes,\n InputHTMLAttributes,\n RefObject\n} from 'react';\nimport {AriaButtonProps} from '@react-types/button';\nimport {DOMAttributes} from '@react-types/shared';\nimport {filterDOMProps} from '@react-aria/utils';\nimport {mergeProps} from '@react-aria/utils';\nimport {useFocusable} from '@react-aria/focus';\nimport {usePress} from '@react-aria/interactions';\n\n\nexport interface ButtonAria {\n /** Props for the button element. */\n buttonProps: T,\n /** Whether the button is currently pressed. */\n isPressed: boolean\n}\n\n// Order with overrides is important: 'button' should be default\nexport function useButton(props: AriaButtonProps<'button'>, ref: RefObject): ButtonAria>;\nexport function useButton(props: AriaButtonProps<'a'>, ref: RefObject): ButtonAria>;\nexport function useButton(props: AriaButtonProps<'div'>, ref: RefObject): ButtonAria>;\nexport function useButton(props: AriaButtonProps<'input'>, ref: RefObject): ButtonAria>;\nexport function useButton(props: AriaButtonProps<'span'>, ref: RefObject): ButtonAria>;\nexport function useButton(props: AriaButtonProps, ref: RefObject): ButtonAria;\n/**\n * Provides the behavior and accessibility implementation for a button component. Handles mouse, keyboard, and touch interactions,\n * focus behavior, and ARIA props for both native button elements and custom element types.\n * @param props - Props to be applied to the button.\n * @param ref - A ref to a DOM element for the button.\n */\nexport function useButton(props: AriaButtonProps, ref: RefObject): ButtonAria> {\n let {\n elementType = 'button',\n isDisabled,\n onPress,\n onPressStart,\n onPressEnd,\n onPressChange,\n // @ts-ignore - undocumented\n preventFocusOnPress,\n // @ts-ignore - undocumented\n allowFocusWhenDisabled,\n // @ts-ignore\n onClick: deprecatedOnClick,\n href,\n target,\n rel,\n type = 'button'\n } = props;\n let additionalProps;\n if (elementType === 'button') {\n additionalProps = {\n type,\n disabled: isDisabled\n };\n } else {\n additionalProps = {\n role: 'button',\n tabIndex: isDisabled ? undefined : 0,\n href: elementType === 'a' && isDisabled ? undefined : href,\n target: elementType === 'a' ? target : undefined,\n type: elementType === 'input' ? type : undefined,\n disabled: elementType === 'input' ? isDisabled : undefined,\n 'aria-disabled': !isDisabled || elementType === 'input' ? undefined : isDisabled,\n rel: elementType === 'a' ? rel : undefined\n };\n }\n\n let {pressProps, isPressed} = usePress({\n onPressStart,\n onPressEnd,\n onPressChange,\n onPress,\n isDisabled,\n preventFocusOnPress,\n ref\n });\n\n let {focusableProps} = useFocusable(props, ref);\n if (allowFocusWhenDisabled) {\n focusableProps.tabIndex = isDisabled ? -1 : focusableProps.tabIndex;\n }\n let buttonProps = mergeProps(focusableProps, pressProps, filterDOMProps(props, {labelable: true}));\n\n return {\n isPressed, // Used to indicate press state for visual\n buttonProps: mergeProps(additionalProps, buttonProps, {\n 'aria-haspopup': props['aria-haspopup'],\n 'aria-expanded': props['aria-expanded'],\n 'aria-controls': props['aria-controls'],\n 'aria-pressed': props['aria-pressed'],\n onClick: (e) => {\n if (deprecatedOnClick) {\n deprecatedOnClick(e);\n console.warn('onClick is deprecated, please use onPress');\n }\n }\n })\n };\n}\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose';\nimport { useLayoutEffect, forwardRef, useRef, createElement } from 'react';\nimport useLatest from 'use-latest';\nimport useComposedRef from 'use-composed-ref';\n\nvar HIDDEN_TEXTAREA_STYLE = {\n 'min-height': '0',\n 'max-height': 'none',\n height: '0',\n visibility: 'hidden',\n overflow: 'hidden',\n position: 'absolute',\n 'z-index': '-1000',\n top: '0',\n right: '0'\n};\n\nvar forceHiddenStyles = function forceHiddenStyles(node) {\n Object.keys(HIDDEN_TEXTAREA_STYLE).forEach(function (key) {\n node.style.setProperty(key, HIDDEN_TEXTAREA_STYLE[key], 'important');\n });\n};\n\n// export type CalculatedNodeHeights = [height: number, rowHeight: number];\n// https://github.com/microsoft/TypeScript/issues/28259\n\nvar hiddenTextarea = null;\n\nvar getHeight = function getHeight(node, sizingData) {\n var height = node.scrollHeight;\n\n if (sizingData.sizingStyle.boxSizing === 'border-box') {\n // border-box: add border, since height = content + padding + border\n return height + sizingData.borderSize;\n } // remove padding, since height = content\n\n\n return height - sizingData.paddingSize;\n};\n\nfunction calculateNodeHeight(sizingData, value, minRows, maxRows) {\n if (minRows === void 0) {\n minRows = 1;\n }\n\n if (maxRows === void 0) {\n maxRows = Infinity;\n }\n\n if (!hiddenTextarea) {\n hiddenTextarea = document.createElement('textarea');\n hiddenTextarea.setAttribute('tabindex', '-1');\n hiddenTextarea.setAttribute('aria-hidden', 'true');\n forceHiddenStyles(hiddenTextarea);\n }\n\n if (hiddenTextarea.parentNode === null) {\n document.body.appendChild(hiddenTextarea);\n }\n\n var paddingSize = sizingData.paddingSize,\n borderSize = sizingData.borderSize,\n sizingStyle = sizingData.sizingStyle;\n var boxSizing = sizingStyle.boxSizing;\n Object.keys(sizingStyle).forEach(function (_key) {\n var key = _key;\n hiddenTextarea.style[key] = sizingStyle[key];\n });\n forceHiddenStyles(hiddenTextarea);\n hiddenTextarea.value = value;\n var height = getHeight(hiddenTextarea, sizingData); // measure height of a textarea with a single row\n\n hiddenTextarea.value = 'x';\n var rowHeight = hiddenTextarea.scrollHeight - paddingSize;\n var minHeight = rowHeight * minRows;\n\n if (boxSizing === 'border-box') {\n minHeight = minHeight + paddingSize + borderSize;\n }\n\n height = Math.max(minHeight, height);\n var maxHeight = rowHeight * maxRows;\n\n if (boxSizing === 'border-box') {\n maxHeight = maxHeight + paddingSize + borderSize;\n }\n\n height = Math.min(maxHeight, height);\n return [height, rowHeight];\n}\n\nvar noop = function noop() {};\nvar pick = function pick(props, obj) {\n return props.reduce(function (acc, prop) {\n acc[prop] = obj[prop];\n return acc;\n }, {});\n};\n\nvar SIZING_STYLE = ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth', 'boxSizing', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight', 'letterSpacing', 'lineHeight', 'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop', // non-standard\n'tabSize', 'textIndent', // non-standard\n'textRendering', 'textTransform', 'width', 'wordBreak'];\nvar isIE = !!document.documentElement.currentStyle ;\n\nvar getSizingData = function getSizingData(node) {\n var style = window.getComputedStyle(node);\n\n if (style === null) {\n return null;\n }\n\n var sizingStyle = pick(SIZING_STYLE, style);\n var boxSizing = sizingStyle.boxSizing; // probably node is detached from DOM, can't read computed dimensions\n\n if (boxSizing === '') {\n return null;\n } // IE (Edge has already correct behaviour) returns content width as computed width\n // so we need to add manually padding and border widths\n\n\n if (isIE && boxSizing === 'border-box') {\n sizingStyle.width = parseFloat(sizingStyle.width) + parseFloat(sizingStyle.borderRightWidth) + parseFloat(sizingStyle.borderLeftWidth) + parseFloat(sizingStyle.paddingRight) + parseFloat(sizingStyle.paddingLeft) + 'px';\n }\n\n var paddingSize = parseFloat(sizingStyle.paddingBottom) + parseFloat(sizingStyle.paddingTop);\n var borderSize = parseFloat(sizingStyle.borderBottomWidth) + parseFloat(sizingStyle.borderTopWidth);\n return {\n sizingStyle: sizingStyle,\n paddingSize: paddingSize,\n borderSize: borderSize\n };\n};\n\nvar useWindowResizeListener = function useWindowResizeListener(listener) {\n var latestListener = useLatest(listener);\n useLayoutEffect(function () {\n var handler = function handler(event) {\n latestListener.current(event);\n };\n\n window.addEventListener('resize', handler);\n return function () {\n window.removeEventListener('resize', handler);\n };\n }, []);\n};\n\nvar TextareaAutosize = function TextareaAutosize(_ref, userRef) {\n var cacheMeasurements = _ref.cacheMeasurements,\n maxRows = _ref.maxRows,\n minRows = _ref.minRows,\n _ref$onChange = _ref.onChange,\n onChange = _ref$onChange === void 0 ? noop : _ref$onChange,\n _ref$onHeightChange = _ref.onHeightChange,\n onHeightChange = _ref$onHeightChange === void 0 ? noop : _ref$onHeightChange,\n props = _objectWithoutPropertiesLoose(_ref, [\"cacheMeasurements\", \"maxRows\", \"minRows\", \"onChange\", \"onHeightChange\"]);\n\n if (process.env.NODE_ENV !== 'production' && props.style) {\n if ('maxHeight' in props.style) {\n throw new Error('Using `style.maxHeight` for is not supported. Please use `maxRows`.');\n }\n\n if ('minHeight' in props.style) {\n throw new Error('Using `style.minHeight` for is not supported. Please use `minRows`.');\n }\n }\n\n var isControlled = props.value !== undefined;\n var libRef = useRef(null);\n var ref = useComposedRef(libRef, userRef);\n var heightRef = useRef(0);\n var measurementsCacheRef = useRef();\n\n var resizeTextarea = function resizeTextarea() {\n var node = libRef.current;\n var nodeSizingData = cacheMeasurements && measurementsCacheRef.current ? measurementsCacheRef.current : getSizingData(node);\n\n if (!nodeSizingData) {\n return;\n }\n\n measurementsCacheRef.current = nodeSizingData;\n\n var _calculateNodeHeight = calculateNodeHeight(nodeSizingData, node.value || node.placeholder || 'x', minRows, maxRows),\n height = _calculateNodeHeight[0],\n rowHeight = _calculateNodeHeight[1];\n\n if (heightRef.current !== height) {\n heightRef.current = height;\n node.style.setProperty('height', height + \"px\", 'important');\n onHeightChange(height, {\n rowHeight: rowHeight\n });\n }\n };\n\n var handleChange = function handleChange(event) {\n if (!isControlled) {\n resizeTextarea();\n }\n\n onChange(event);\n };\n\n {\n useLayoutEffect(resizeTextarea);\n useWindowResizeListener(resizeTextarea);\n }\n\n return /*#__PURE__*/createElement(\"textarea\", _extends({}, props, {\n onChange: handleChange,\n ref: ref\n }));\n};\n\nvar index = /* #__PURE__ */forwardRef(TextareaAutosize);\n\nexport default index;\n","/**\r\n * A collection of shims that provide minimal functionality of the ES6 collections.\r\n *\r\n * These implementations are not meant to be used outside of the ResizeObserver\r\n * modules as they cover only a limited range of use cases.\r\n */\r\n/* eslint-disable require-jsdoc, valid-jsdoc */\r\nvar MapShim = (function () {\r\n if (typeof Map !== 'undefined') {\r\n return Map;\r\n }\r\n /**\r\n * Returns index in provided array that matches the specified key.\r\n *\r\n * @param {Array} arr\r\n * @param {*} key\r\n * @returns {number}\r\n */\r\n function getIndex(arr, key) {\r\n var result = -1;\r\n arr.some(function (entry, index) {\r\n if (entry[0] === key) {\r\n result = index;\r\n return true;\r\n }\r\n return false;\r\n });\r\n return result;\r\n }\r\n return /** @class */ (function () {\r\n function class_1() {\r\n this.__entries__ = [];\r\n }\r\n Object.defineProperty(class_1.prototype, \"size\", {\r\n /**\r\n * @returns {boolean}\r\n */\r\n get: function () {\r\n return this.__entries__.length;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * @param {*} key\r\n * @returns {*}\r\n */\r\n class_1.prototype.get = function (key) {\r\n var index = getIndex(this.__entries__, key);\r\n var entry = this.__entries__[index];\r\n return entry && entry[1];\r\n };\r\n /**\r\n * @param {*} key\r\n * @param {*} value\r\n * @returns {void}\r\n */\r\n class_1.prototype.set = function (key, value) {\r\n var index = getIndex(this.__entries__, key);\r\n if (~index) {\r\n this.__entries__[index][1] = value;\r\n }\r\n else {\r\n this.__entries__.push([key, value]);\r\n }\r\n };\r\n /**\r\n * @param {*} key\r\n * @returns {void}\r\n */\r\n class_1.prototype.delete = function (key) {\r\n var entries = this.__entries__;\r\n var index = getIndex(entries, key);\r\n if (~index) {\r\n entries.splice(index, 1);\r\n }\r\n };\r\n /**\r\n * @param {*} key\r\n * @returns {void}\r\n */\r\n class_1.prototype.has = function (key) {\r\n return !!~getIndex(this.__entries__, key);\r\n };\r\n /**\r\n * @returns {void}\r\n */\r\n class_1.prototype.clear = function () {\r\n this.__entries__.splice(0);\r\n };\r\n /**\r\n * @param {Function} callback\r\n * @param {*} [ctx=null]\r\n * @returns {void}\r\n */\r\n class_1.prototype.forEach = function (callback, ctx) {\r\n if (ctx === void 0) { ctx = null; }\r\n for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {\r\n var entry = _a[_i];\r\n callback.call(ctx, entry[1], entry[0]);\r\n }\r\n };\r\n return class_1;\r\n }());\r\n})();\n\n/**\r\n * Detects whether window and document objects are available in current environment.\r\n */\r\nvar isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;\n\n// Returns global object of a current environment.\r\nvar global$1 = (function () {\r\n if (typeof global !== 'undefined' && global.Math === Math) {\r\n return global;\r\n }\r\n if (typeof self !== 'undefined' && self.Math === Math) {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined' && window.Math === Math) {\r\n return window;\r\n }\r\n // eslint-disable-next-line no-new-func\r\n return Function('return this')();\r\n})();\n\n/**\r\n * A shim for the requestAnimationFrame which falls back to the setTimeout if\r\n * first one is not supported.\r\n *\r\n * @returns {number} Requests' identifier.\r\n */\r\nvar requestAnimationFrame$1 = (function () {\r\n if (typeof requestAnimationFrame === 'function') {\r\n // It's required to use a bounded function because IE sometimes throws\r\n // an \"Invalid calling object\" error if rAF is invoked without the global\r\n // object on the left hand side.\r\n return requestAnimationFrame.bind(global$1);\r\n }\r\n return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };\r\n})();\n\n// Defines minimum timeout before adding a trailing call.\r\nvar trailingTimeout = 2;\r\n/**\r\n * Creates a wrapper function which ensures that provided callback will be\r\n * invoked only once during the specified delay period.\r\n *\r\n * @param {Function} callback - Function to be invoked after the delay period.\r\n * @param {number} delay - Delay after which to invoke callback.\r\n * @returns {Function}\r\n */\r\nfunction throttle (callback, delay) {\r\n var leadingCall = false, trailingCall = false, lastCallTime = 0;\r\n /**\r\n * Invokes the original callback function and schedules new invocation if\r\n * the \"proxy\" was called during current request.\r\n *\r\n * @returns {void}\r\n */\r\n function resolvePending() {\r\n if (leadingCall) {\r\n leadingCall = false;\r\n callback();\r\n }\r\n if (trailingCall) {\r\n proxy();\r\n }\r\n }\r\n /**\r\n * Callback invoked after the specified delay. It will further postpone\r\n * invocation of the original function delegating it to the\r\n * requestAnimationFrame.\r\n *\r\n * @returns {void}\r\n */\r\n function timeoutCallback() {\r\n requestAnimationFrame$1(resolvePending);\r\n }\r\n /**\r\n * Schedules invocation of the original function.\r\n *\r\n * @returns {void}\r\n */\r\n function proxy() {\r\n var timeStamp = Date.now();\r\n if (leadingCall) {\r\n // Reject immediately following calls.\r\n if (timeStamp - lastCallTime < trailingTimeout) {\r\n return;\r\n }\r\n // Schedule new call to be in invoked when the pending one is resolved.\r\n // This is important for \"transitions\" which never actually start\r\n // immediately so there is a chance that we might miss one if change\r\n // happens amids the pending invocation.\r\n trailingCall = true;\r\n }\r\n else {\r\n leadingCall = true;\r\n trailingCall = false;\r\n setTimeout(timeoutCallback, delay);\r\n }\r\n lastCallTime = timeStamp;\r\n }\r\n return proxy;\r\n}\n\n// Minimum delay before invoking the update of observers.\r\nvar REFRESH_DELAY = 20;\r\n// A list of substrings of CSS properties used to find transition events that\r\n// might affect dimensions of observed elements.\r\nvar transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];\r\n// Check if MutationObserver is available.\r\nvar mutationObserverSupported = typeof MutationObserver !== 'undefined';\r\n/**\r\n * Singleton controller class which handles updates of ResizeObserver instances.\r\n */\r\nvar ResizeObserverController = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserverController.\r\n *\r\n * @private\r\n */\r\n function ResizeObserverController() {\r\n /**\r\n * Indicates whether DOM listeners have been added.\r\n *\r\n * @private {boolean}\r\n */\r\n this.connected_ = false;\r\n /**\r\n * Tells that controller has subscribed for Mutation Events.\r\n *\r\n * @private {boolean}\r\n */\r\n this.mutationEventsAdded_ = false;\r\n /**\r\n * Keeps reference to the instance of MutationObserver.\r\n *\r\n * @private {MutationObserver}\r\n */\r\n this.mutationsObserver_ = null;\r\n /**\r\n * A list of connected observers.\r\n *\r\n * @private {Array}\r\n */\r\n this.observers_ = [];\r\n this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);\r\n this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);\r\n }\r\n /**\r\n * Adds observer to observers list.\r\n *\r\n * @param {ResizeObserverSPI} observer - Observer to be added.\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.addObserver = function (observer) {\r\n if (!~this.observers_.indexOf(observer)) {\r\n this.observers_.push(observer);\r\n }\r\n // Add listeners if they haven't been added yet.\r\n if (!this.connected_) {\r\n this.connect_();\r\n }\r\n };\r\n /**\r\n * Removes observer from observers list.\r\n *\r\n * @param {ResizeObserverSPI} observer - Observer to be removed.\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.removeObserver = function (observer) {\r\n var observers = this.observers_;\r\n var index = observers.indexOf(observer);\r\n // Remove observer if it's present in registry.\r\n if (~index) {\r\n observers.splice(index, 1);\r\n }\r\n // Remove listeners if controller has no connected observers.\r\n if (!observers.length && this.connected_) {\r\n this.disconnect_();\r\n }\r\n };\r\n /**\r\n * Invokes the update of observers. It will continue running updates insofar\r\n * it detects changes.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.refresh = function () {\r\n var changesDetected = this.updateObservers_();\r\n // Continue running updates if changes have been detected as there might\r\n // be future ones caused by CSS transitions.\r\n if (changesDetected) {\r\n this.refresh();\r\n }\r\n };\r\n /**\r\n * Updates every observer from observers list and notifies them of queued\r\n * entries.\r\n *\r\n * @private\r\n * @returns {boolean} Returns \"true\" if any observer has detected changes in\r\n * dimensions of it's elements.\r\n */\r\n ResizeObserverController.prototype.updateObservers_ = function () {\r\n // Collect observers that have active observations.\r\n var activeObservers = this.observers_.filter(function (observer) {\r\n return observer.gatherActive(), observer.hasActive();\r\n });\r\n // Deliver notifications in a separate cycle in order to avoid any\r\n // collisions between observers, e.g. when multiple instances of\r\n // ResizeObserver are tracking the same element and the callback of one\r\n // of them changes content dimensions of the observed target. Sometimes\r\n // this may result in notifications being blocked for the rest of observers.\r\n activeObservers.forEach(function (observer) { return observer.broadcastActive(); });\r\n return activeObservers.length > 0;\r\n };\r\n /**\r\n * Initializes DOM listeners.\r\n *\r\n * @private\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.connect_ = function () {\r\n // Do nothing if running in a non-browser environment or if listeners\r\n // have been already added.\r\n if (!isBrowser || this.connected_) {\r\n return;\r\n }\r\n // Subscription to the \"Transitionend\" event is used as a workaround for\r\n // delayed transitions. This way it's possible to capture at least the\r\n // final state of an element.\r\n document.addEventListener('transitionend', this.onTransitionEnd_);\r\n window.addEventListener('resize', this.refresh);\r\n if (mutationObserverSupported) {\r\n this.mutationsObserver_ = new MutationObserver(this.refresh);\r\n this.mutationsObserver_.observe(document, {\r\n attributes: true,\r\n childList: true,\r\n characterData: true,\r\n subtree: true\r\n });\r\n }\r\n else {\r\n document.addEventListener('DOMSubtreeModified', this.refresh);\r\n this.mutationEventsAdded_ = true;\r\n }\r\n this.connected_ = true;\r\n };\r\n /**\r\n * Removes DOM listeners.\r\n *\r\n * @private\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.disconnect_ = function () {\r\n // Do nothing if running in a non-browser environment or if listeners\r\n // have been already removed.\r\n if (!isBrowser || !this.connected_) {\r\n return;\r\n }\r\n document.removeEventListener('transitionend', this.onTransitionEnd_);\r\n window.removeEventListener('resize', this.refresh);\r\n if (this.mutationsObserver_) {\r\n this.mutationsObserver_.disconnect();\r\n }\r\n if (this.mutationEventsAdded_) {\r\n document.removeEventListener('DOMSubtreeModified', this.refresh);\r\n }\r\n this.mutationsObserver_ = null;\r\n this.mutationEventsAdded_ = false;\r\n this.connected_ = false;\r\n };\r\n /**\r\n * \"Transitionend\" event handler.\r\n *\r\n * @private\r\n * @param {TransitionEvent} event\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {\r\n var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;\r\n // Detect whether transition may affect dimensions of an element.\r\n var isReflowProperty = transitionKeys.some(function (key) {\r\n return !!~propertyName.indexOf(key);\r\n });\r\n if (isReflowProperty) {\r\n this.refresh();\r\n }\r\n };\r\n /**\r\n * Returns instance of the ResizeObserverController.\r\n *\r\n * @returns {ResizeObserverController}\r\n */\r\n ResizeObserverController.getInstance = function () {\r\n if (!this.instance_) {\r\n this.instance_ = new ResizeObserverController();\r\n }\r\n return this.instance_;\r\n };\r\n /**\r\n * Holds reference to the controller's instance.\r\n *\r\n * @private {ResizeObserverController}\r\n */\r\n ResizeObserverController.instance_ = null;\r\n return ResizeObserverController;\r\n}());\n\n/**\r\n * Defines non-writable/enumerable properties of the provided target object.\r\n *\r\n * @param {Object} target - Object for which to define properties.\r\n * @param {Object} props - Properties to be defined.\r\n * @returns {Object} Target object.\r\n */\r\nvar defineConfigurable = (function (target, props) {\r\n for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {\r\n var key = _a[_i];\r\n Object.defineProperty(target, key, {\r\n value: props[key],\r\n enumerable: false,\r\n writable: false,\r\n configurable: true\r\n });\r\n }\r\n return target;\r\n});\n\n/**\r\n * Returns the global object associated with provided element.\r\n *\r\n * @param {Object} target\r\n * @returns {Object}\r\n */\r\nvar getWindowOf = (function (target) {\r\n // Assume that the element is an instance of Node, which means that it\r\n // has the \"ownerDocument\" property from which we can retrieve a\r\n // corresponding global object.\r\n var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;\r\n // Return the local global object if it's not possible extract one from\r\n // provided element.\r\n return ownerGlobal || global$1;\r\n});\n\n// Placeholder of an empty content rectangle.\r\nvar emptyRect = createRectInit(0, 0, 0, 0);\r\n/**\r\n * Converts provided string to a number.\r\n *\r\n * @param {number|string} value\r\n * @returns {number}\r\n */\r\nfunction toFloat(value) {\r\n return parseFloat(value) || 0;\r\n}\r\n/**\r\n * Extracts borders size from provided styles.\r\n *\r\n * @param {CSSStyleDeclaration} styles\r\n * @param {...string} positions - Borders positions (top, right, ...)\r\n * @returns {number}\r\n */\r\nfunction getBordersSize(styles) {\r\n var positions = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n positions[_i - 1] = arguments[_i];\r\n }\r\n return positions.reduce(function (size, position) {\r\n var value = styles['border-' + position + '-width'];\r\n return size + toFloat(value);\r\n }, 0);\r\n}\r\n/**\r\n * Extracts paddings sizes from provided styles.\r\n *\r\n * @param {CSSStyleDeclaration} styles\r\n * @returns {Object} Paddings box.\r\n */\r\nfunction getPaddings(styles) {\r\n var positions = ['top', 'right', 'bottom', 'left'];\r\n var paddings = {};\r\n for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {\r\n var position = positions_1[_i];\r\n var value = styles['padding-' + position];\r\n paddings[position] = toFloat(value);\r\n }\r\n return paddings;\r\n}\r\n/**\r\n * Calculates content rectangle of provided SVG element.\r\n *\r\n * @param {SVGGraphicsElement} target - Element content rectangle of which needs\r\n * to be calculated.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getSVGContentRect(target) {\r\n var bbox = target.getBBox();\r\n return createRectInit(0, 0, bbox.width, bbox.height);\r\n}\r\n/**\r\n * Calculates content rectangle of provided HTMLElement.\r\n *\r\n * @param {HTMLElement} target - Element for which to calculate the content rectangle.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getHTMLElementContentRect(target) {\r\n // Client width & height properties can't be\r\n // used exclusively as they provide rounded values.\r\n var clientWidth = target.clientWidth, clientHeight = target.clientHeight;\r\n // By this condition we can catch all non-replaced inline, hidden and\r\n // detached elements. Though elements with width & height properties less\r\n // than 0.5 will be discarded as well.\r\n //\r\n // Without it we would need to implement separate methods for each of\r\n // those cases and it's not possible to perform a precise and performance\r\n // effective test for hidden elements. E.g. even jQuery's ':visible' filter\r\n // gives wrong results for elements with width & height less than 0.5.\r\n if (!clientWidth && !clientHeight) {\r\n return emptyRect;\r\n }\r\n var styles = getWindowOf(target).getComputedStyle(target);\r\n var paddings = getPaddings(styles);\r\n var horizPad = paddings.left + paddings.right;\r\n var vertPad = paddings.top + paddings.bottom;\r\n // Computed styles of width & height are being used because they are the\r\n // only dimensions available to JS that contain non-rounded values. It could\r\n // be possible to utilize the getBoundingClientRect if only it's data wasn't\r\n // affected by CSS transformations let alone paddings, borders and scroll bars.\r\n var width = toFloat(styles.width), height = toFloat(styles.height);\r\n // Width & height include paddings and borders when the 'border-box' box\r\n // model is applied (except for IE).\r\n if (styles.boxSizing === 'border-box') {\r\n // Following conditions are required to handle Internet Explorer which\r\n // doesn't include paddings and borders to computed CSS dimensions.\r\n //\r\n // We can say that if CSS dimensions + paddings are equal to the \"client\"\r\n // properties then it's either IE, and thus we don't need to subtract\r\n // anything, or an element merely doesn't have paddings/borders styles.\r\n if (Math.round(width + horizPad) !== clientWidth) {\r\n width -= getBordersSize(styles, 'left', 'right') + horizPad;\r\n }\r\n if (Math.round(height + vertPad) !== clientHeight) {\r\n height -= getBordersSize(styles, 'top', 'bottom') + vertPad;\r\n }\r\n }\r\n // Following steps can't be applied to the document's root element as its\r\n // client[Width/Height] properties represent viewport area of the window.\r\n // Besides, it's as well not necessary as the itself neither has\r\n // rendered scroll bars nor it can be clipped.\r\n if (!isDocumentElement(target)) {\r\n // In some browsers (only in Firefox, actually) CSS width & height\r\n // include scroll bars size which can be removed at this step as scroll\r\n // bars are the only difference between rounded dimensions + paddings\r\n // and \"client\" properties, though that is not always true in Chrome.\r\n var vertScrollbar = Math.round(width + horizPad) - clientWidth;\r\n var horizScrollbar = Math.round(height + vertPad) - clientHeight;\r\n // Chrome has a rather weird rounding of \"client\" properties.\r\n // E.g. for an element with content width of 314.2px it sometimes gives\r\n // the client width of 315px and for the width of 314.7px it may give\r\n // 314px. And it doesn't happen all the time. So just ignore this delta\r\n // as a non-relevant.\r\n if (Math.abs(vertScrollbar) !== 1) {\r\n width -= vertScrollbar;\r\n }\r\n if (Math.abs(horizScrollbar) !== 1) {\r\n height -= horizScrollbar;\r\n }\r\n }\r\n return createRectInit(paddings.left, paddings.top, width, height);\r\n}\r\n/**\r\n * Checks whether provided element is an instance of the SVGGraphicsElement.\r\n *\r\n * @param {Element} target - Element to be checked.\r\n * @returns {boolean}\r\n */\r\nvar isSVGGraphicsElement = (function () {\r\n // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement\r\n // interface.\r\n if (typeof SVGGraphicsElement !== 'undefined') {\r\n return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };\r\n }\r\n // If it's so, then check that element is at least an instance of the\r\n // SVGElement and that it has the \"getBBox\" method.\r\n // eslint-disable-next-line no-extra-parens\r\n return function (target) { return (target instanceof getWindowOf(target).SVGElement &&\r\n typeof target.getBBox === 'function'); };\r\n})();\r\n/**\r\n * Checks whether provided element is a document element ().\r\n *\r\n * @param {Element} target - Element to be checked.\r\n * @returns {boolean}\r\n */\r\nfunction isDocumentElement(target) {\r\n return target === getWindowOf(target).document.documentElement;\r\n}\r\n/**\r\n * Calculates an appropriate content rectangle for provided html or svg element.\r\n *\r\n * @param {Element} target - Element content rectangle of which needs to be calculated.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getContentRect(target) {\r\n if (!isBrowser) {\r\n return emptyRect;\r\n }\r\n if (isSVGGraphicsElement(target)) {\r\n return getSVGContentRect(target);\r\n }\r\n return getHTMLElementContentRect(target);\r\n}\r\n/**\r\n * Creates rectangle with an interface of the DOMRectReadOnly.\r\n * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly\r\n *\r\n * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.\r\n * @returns {DOMRectReadOnly}\r\n */\r\nfunction createReadOnlyRect(_a) {\r\n var x = _a.x, y = _a.y, width = _a.width, height = _a.height;\r\n // If DOMRectReadOnly is available use it as a prototype for the rectangle.\r\n var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;\r\n var rect = Object.create(Constr.prototype);\r\n // Rectangle's properties are not writable and non-enumerable.\r\n defineConfigurable(rect, {\r\n x: x, y: y, width: width, height: height,\r\n top: y,\r\n right: x + width,\r\n bottom: height + y,\r\n left: x\r\n });\r\n return rect;\r\n}\r\n/**\r\n * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.\r\n * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit\r\n *\r\n * @param {number} x - X coordinate.\r\n * @param {number} y - Y coordinate.\r\n * @param {number} width - Rectangle's width.\r\n * @param {number} height - Rectangle's height.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction createRectInit(x, y, width, height) {\r\n return { x: x, y: y, width: width, height: height };\r\n}\n\n/**\r\n * Class that is responsible for computations of the content rectangle of\r\n * provided DOM element and for keeping track of it's changes.\r\n */\r\nvar ResizeObservation = /** @class */ (function () {\r\n /**\r\n * Creates an instance of ResizeObservation.\r\n *\r\n * @param {Element} target - Element to be observed.\r\n */\r\n function ResizeObservation(target) {\r\n /**\r\n * Broadcasted width of content rectangle.\r\n *\r\n * @type {number}\r\n */\r\n this.broadcastWidth = 0;\r\n /**\r\n * Broadcasted height of content rectangle.\r\n *\r\n * @type {number}\r\n */\r\n this.broadcastHeight = 0;\r\n /**\r\n * Reference to the last observed content rectangle.\r\n *\r\n * @private {DOMRectInit}\r\n */\r\n this.contentRect_ = createRectInit(0, 0, 0, 0);\r\n this.target = target;\r\n }\r\n /**\r\n * Updates content rectangle and tells whether it's width or height properties\r\n * have changed since the last broadcast.\r\n *\r\n * @returns {boolean}\r\n */\r\n ResizeObservation.prototype.isActive = function () {\r\n var rect = getContentRect(this.target);\r\n this.contentRect_ = rect;\r\n return (rect.width !== this.broadcastWidth ||\r\n rect.height !== this.broadcastHeight);\r\n };\r\n /**\r\n * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data\r\n * from the corresponding properties of the last observed content rectangle.\r\n *\r\n * @returns {DOMRectInit} Last observed content rectangle.\r\n */\r\n ResizeObservation.prototype.broadcastRect = function () {\r\n var rect = this.contentRect_;\r\n this.broadcastWidth = rect.width;\r\n this.broadcastHeight = rect.height;\r\n return rect;\r\n };\r\n return ResizeObservation;\r\n}());\n\nvar ResizeObserverEntry = /** @class */ (function () {\r\n /**\r\n * Creates an instance of ResizeObserverEntry.\r\n *\r\n * @param {Element} target - Element that is being observed.\r\n * @param {DOMRectInit} rectInit - Data of the element's content rectangle.\r\n */\r\n function ResizeObserverEntry(target, rectInit) {\r\n var contentRect = createReadOnlyRect(rectInit);\r\n // According to the specification following properties are not writable\r\n // and are also not enumerable in the native implementation.\r\n //\r\n // Property accessors are not being used as they'd require to define a\r\n // private WeakMap storage which may cause memory leaks in browsers that\r\n // don't support this type of collections.\r\n defineConfigurable(this, { target: target, contentRect: contentRect });\r\n }\r\n return ResizeObserverEntry;\r\n}());\n\nvar ResizeObserverSPI = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserver.\r\n *\r\n * @param {ResizeObserverCallback} callback - Callback function that is invoked\r\n * when one of the observed elements changes it's content dimensions.\r\n * @param {ResizeObserverController} controller - Controller instance which\r\n * is responsible for the updates of observer.\r\n * @param {ResizeObserver} callbackCtx - Reference to the public\r\n * ResizeObserver instance which will be passed to callback function.\r\n */\r\n function ResizeObserverSPI(callback, controller, callbackCtx) {\r\n /**\r\n * Collection of resize observations that have detected changes in dimensions\r\n * of elements.\r\n *\r\n * @private {Array}\r\n */\r\n this.activeObservations_ = [];\r\n /**\r\n * Registry of the ResizeObservation instances.\r\n *\r\n * @private {Map}\r\n */\r\n this.observations_ = new MapShim();\r\n if (typeof callback !== 'function') {\r\n throw new TypeError('The callback provided as parameter 1 is not a function.');\r\n }\r\n this.callback_ = callback;\r\n this.controller_ = controller;\r\n this.callbackCtx_ = callbackCtx;\r\n }\r\n /**\r\n * Starts observing provided element.\r\n *\r\n * @param {Element} target - Element to be observed.\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.observe = function (target) {\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n // Do nothing if current environment doesn't have the Element interface.\r\n if (typeof Element === 'undefined' || !(Element instanceof Object)) {\r\n return;\r\n }\r\n if (!(target instanceof getWindowOf(target).Element)) {\r\n throw new TypeError('parameter 1 is not of type \"Element\".');\r\n }\r\n var observations = this.observations_;\r\n // Do nothing if element is already being observed.\r\n if (observations.has(target)) {\r\n return;\r\n }\r\n observations.set(target, new ResizeObservation(target));\r\n this.controller_.addObserver(this);\r\n // Force the update of observations.\r\n this.controller_.refresh();\r\n };\r\n /**\r\n * Stops observing provided element.\r\n *\r\n * @param {Element} target - Element to stop observing.\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.unobserve = function (target) {\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n // Do nothing if current environment doesn't have the Element interface.\r\n if (typeof Element === 'undefined' || !(Element instanceof Object)) {\r\n return;\r\n }\r\n if (!(target instanceof getWindowOf(target).Element)) {\r\n throw new TypeError('parameter 1 is not of type \"Element\".');\r\n }\r\n var observations = this.observations_;\r\n // Do nothing if element is not being observed.\r\n if (!observations.has(target)) {\r\n return;\r\n }\r\n observations.delete(target);\r\n if (!observations.size) {\r\n this.controller_.removeObserver(this);\r\n }\r\n };\r\n /**\r\n * Stops observing all elements.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.disconnect = function () {\r\n this.clearActive();\r\n this.observations_.clear();\r\n this.controller_.removeObserver(this);\r\n };\r\n /**\r\n * Collects observation instances the associated element of which has changed\r\n * it's content rectangle.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.gatherActive = function () {\r\n var _this = this;\r\n this.clearActive();\r\n this.observations_.forEach(function (observation) {\r\n if (observation.isActive()) {\r\n _this.activeObservations_.push(observation);\r\n }\r\n });\r\n };\r\n /**\r\n * Invokes initial callback function with a list of ResizeObserverEntry\r\n * instances collected from active resize observations.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.broadcastActive = function () {\r\n // Do nothing if observer doesn't have active observations.\r\n if (!this.hasActive()) {\r\n return;\r\n }\r\n var ctx = this.callbackCtx_;\r\n // Create ResizeObserverEntry instance for every active observation.\r\n var entries = this.activeObservations_.map(function (observation) {\r\n return new ResizeObserverEntry(observation.target, observation.broadcastRect());\r\n });\r\n this.callback_.call(ctx, entries, ctx);\r\n this.clearActive();\r\n };\r\n /**\r\n * Clears the collection of active observations.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.clearActive = function () {\r\n this.activeObservations_.splice(0);\r\n };\r\n /**\r\n * Tells whether observer has active observations.\r\n *\r\n * @returns {boolean}\r\n */\r\n ResizeObserverSPI.prototype.hasActive = function () {\r\n return this.activeObservations_.length > 0;\r\n };\r\n return ResizeObserverSPI;\r\n}());\n\n// Registry of internal observers. If WeakMap is not available use current shim\r\n// for the Map collection as it has all required methods and because WeakMap\r\n// can't be fully polyfilled anyway.\r\nvar observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();\r\n/**\r\n * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation\r\n * exposing only those methods and properties that are defined in the spec.\r\n */\r\nvar ResizeObserver = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserver.\r\n *\r\n * @param {ResizeObserverCallback} callback - Callback that is invoked when\r\n * dimensions of the observed elements change.\r\n */\r\n function ResizeObserver(callback) {\r\n if (!(this instanceof ResizeObserver)) {\r\n throw new TypeError('Cannot call a class as a function.');\r\n }\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n var controller = ResizeObserverController.getInstance();\r\n var observer = new ResizeObserverSPI(callback, controller, this);\r\n observers.set(this, observer);\r\n }\r\n return ResizeObserver;\r\n}());\r\n// Expose public methods of ResizeObserver.\r\n[\r\n 'observe',\r\n 'unobserve',\r\n 'disconnect'\r\n].forEach(function (method) {\r\n ResizeObserver.prototype[method] = function () {\r\n var _a;\r\n return (_a = observers.get(this))[method].apply(_a, arguments);\r\n };\r\n});\n\nvar index = (function () {\r\n // Export existing implementation if available.\r\n if (typeof global$1.ResizeObserver !== 'undefined') {\r\n return global$1.ResizeObserver;\r\n }\r\n return ResizeObserver;\r\n})();\n\nexport default index;\n","import { memo, useEffect, useRef } from \"react\";\nimport {\n Message as LiveMessage,\n MessageText,\n MessageList,\n} from \"@livechat/ui-kit\";\nimport { Message } from \"./Message\";\n\ninterface Props {\n messages: Message[];\n}\n\nmemo(ChatList);\n\nexport default function ChatList(props: Props) {\n const renderedMessages = props.messages.map((message) => (\n \n {message.payloadAsUtf8}\n \n ));\n\n return (\n \n {renderedMessages}\n \n \n );\n}\n\nfunction formatDisplayDate(message: Message): string {\n return message.timestamp.toLocaleString([], {\n month: \"short\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n hour12: false,\n });\n}\n\nconst AlwaysScrollToBottom = (props: { messages: Message[] }) => {\n const elementRef = useRef();\n\n useEffect(() => {\n // @ts-ignore\n elementRef.current.scrollIntoView();\n }, [props.messages]);\n\n // @ts-ignore\n return
    ;\n};\n","import { createContext, useContext } from \"react\";\nimport { Waku } from \"js-waku\";\n\nexport type WakuContextType = {\n waku?: Waku;\n};\n\nexport const WakuContext = createContext({ waku: undefined });\nexport const useWaku = () => useContext(WakuContext);\n","import { ChangeEvent, KeyboardEvent, useEffect, useState } from \"react\";\nimport { useWaku } from \"./WakuContext\";\nimport {\n TextInput,\n TextComposer,\n Row,\n Fill,\n Fit,\n SendButton,\n} from \"@livechat/ui-kit\";\n\ninterface Props {\n sendMessage: ((msg: string) => Promise) | undefined;\n}\n\nexport default function MessageInput(props: Props) {\n const [inputText, setInputText] = useState(\"\");\n const [activeButton, setActiveButton] = useState(false);\n const { waku } = useWaku();\n\n const sendMessage = async () => {\n if (props.sendMessage) {\n await props.sendMessage(inputText);\n setInputText(\"\");\n }\n };\n\n const messageHandler = (event: ChangeEvent) => {\n setInputText(event.target.value);\n };\n\n const keyPressHandler = async (event: KeyboardEvent) => {\n if (\n event.key === \"Enter\" &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n await sendMessage();\n }\n };\n\n // Enable the button if there are peers available or the user is sending a command\n useEffect(() => {\n if (inputText.startsWith(\"/\")) {\n setActiveButton(true);\n } else if (waku) {\n (async () => {\n const peers = await waku.lightPush.peers();\n if (!!peers) {\n setActiveButton(true);\n } else {\n setActiveButton(false);\n }\n })();\n }\n }, [activeButton, inputText, waku]);\n\n return (\n \n \n \n \n \n \n \n \n \n \n );\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from \"protons-runtime\";\nimport type { Uint8ArrayList } from \"uint8arraylist\";\nimport type { Codec } from \"protons-runtime\";\n\nexport interface ChatMessage {\n timestamp: bigint;\n nick: string;\n payload: Uint8Array;\n}\n\nexport namespace ChatMessage {\n let _codec: Codec;\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message(\n (obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork();\n }\n\n if (obj.timestamp != null) {\n writer.uint32(8);\n writer.uint64(obj.timestamp);\n } else {\n throw new Error(\n 'Protocol error: required field \"timestamp\" was not found in object'\n );\n }\n\n if (obj.nick != null) {\n writer.uint32(18);\n writer.string(obj.nick);\n } else {\n throw new Error(\n 'Protocol error: required field \"nick\" was not found in object'\n );\n }\n\n if (obj.payload != null) {\n writer.uint32(26);\n writer.bytes(obj.payload);\n } else {\n throw new Error(\n 'Protocol error: required field \"payload\" was not found in object'\n );\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim();\n }\n },\n (reader, length) => {\n const obj: any = {\n timestamp: 0n,\n nick: \"\",\n payload: new Uint8Array(0),\n };\n\n const end = length == null ? reader.len : reader.pos + length;\n\n while (reader.pos < end) {\n const tag = reader.uint32();\n\n switch (tag >>> 3) {\n case 1:\n obj.timestamp = reader.uint64();\n break;\n case 2:\n obj.nick = reader.string();\n break;\n case 3:\n obj.payload = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n\n if (obj.timestamp == null) {\n throw new Error(\n 'Protocol error: value for required field \"timestamp\" was not found in protobuf'\n );\n }\n\n if (obj.nick == null) {\n throw new Error(\n 'Protocol error: value for required field \"nick\" was not found in protobuf'\n );\n }\n\n if (obj.payload == null) {\n throw new Error(\n 'Protocol error: value for required field \"payload\" was not found in protobuf'\n );\n }\n\n return obj;\n }\n );\n }\n\n return _codec;\n };\n\n export const encode = (obj: ChatMessage): Uint8Array => {\n return encodeMessage(obj, ChatMessage.codec());\n };\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): ChatMessage => {\n return decodeMessage(buf, ChatMessage.codec());\n };\n}\n","import { utils } from \"js-waku\";\nimport * as proto from \"./proto/chat_message\";\n\n/**\n * ChatMessage is used by the various show case waku apps that demonstrates\n * waku used as the network layer for chat group applications.\n *\n * This is included to help building PoC and MVPs. Apps that aim to be\n * production ready should use a more appropriate data structure.\n */\nexport class ChatMessage {\n public constructor(public proto: proto.ChatMessage) {}\n\n /**\n * Create Chat Message with a utf-8 string as payload.\n */\n static fromUtf8String(\n timestamp: Date,\n nick: string,\n text: string\n ): ChatMessage {\n const timestampNumber = BigInt(Math.floor(timestamp.valueOf() / 1000));\n const payload = utils.utf8ToBytes(text);\n\n return new ChatMessage({\n timestamp: timestampNumber,\n nick,\n payload,\n });\n }\n\n /**\n * Decode a protobuf payload to a ChatMessage.\n * @param bytes The payload to decode.\n */\n static decode(bytes: Uint8Array): ChatMessage {\n const protoMsg = proto.ChatMessage.decode(bytes);\n return new ChatMessage(protoMsg);\n }\n\n /**\n * Encode this ChatMessage to a byte array, to be used as a protobuf payload.\n * @returns The encoded payload.\n */\n encode(): Uint8Array {\n return proto.ChatMessage.encode(this.proto);\n }\n\n get timestamp(): Date {\n return new Date(Number(this.proto.timestamp * BigInt(1000)));\n }\n\n get nick(): string {\n return this.proto.nick;\n }\n\n get payloadAsUtf8(): string {\n if (!this.proto.payload) {\n return \"\";\n }\n\n return utils.bytesToUtf8(this.proto.payload);\n }\n}\n","import { PushResponse, WakuMessage } from \"js-waku\";\nimport { ChatContentTopic } from \"./App\";\nimport ChatList from \"./ChatList\";\nimport MessageInput from \"./MessageInput\";\nimport { useWaku } from \"./WakuContext\";\nimport { TitleBar } from \"@livechat/ui-kit\";\nimport { Message } from \"./Message\";\nimport { ChatMessage } from \"./chat_message\";\nimport { useEffect, useState } from \"react\";\n\ninterface Props {\n messages: Message[];\n commandHandler: (cmd: string) => void;\n nick: string;\n}\n\nexport default function Room(props: Props) {\n const { waku } = useWaku();\n\n const [storePeers, setStorePeers] = useState(0);\n const [filterPeers, setFilterPeers] = useState(0);\n const [lightPushPeers, setLightPushPeers] = useState(0);\n\n useEffect(() => {\n if (!waku) return;\n\n // Update store peer when new peer connected & identified\n waku.libp2p.peerStore.addEventListener(\"change:protocols\", async () => {\n const storePeers = await waku.store.peers();\n setStorePeers(storePeers.length);\n\n const filterPeers = await waku.filter.peers();\n setFilterPeers(filterPeers.length);\n\n const lightPushPeers = await waku.lightPush.peers();\n setLightPushPeers(lightPushPeers.length);\n });\n }, [waku]);\n\n return (\n \n \n \n {\n return handleMessage(\n messageToSend,\n props.nick,\n props.commandHandler,\n waku.lightPush.push.bind(waku.lightPush)\n );\n }\n : undefined\n }\n />\n
    \n );\n}\n\nasync function handleMessage(\n message: string,\n nick: string,\n commandHandler: (cmd: string) => void,\n messageSender: (msg: WakuMessage) => Promise\n) {\n if (message.startsWith(\"/\")) {\n commandHandler(message);\n } else {\n const timestamp = new Date();\n const chatMessage = ChatMessage.fromUtf8String(timestamp, nick, message);\n const wakuMsg = await WakuMessage.fromBytes(\n chatMessage.encode(),\n ChatContentTopic,\n { timestamp }\n );\n await messageSender(wakuMsg);\n }\n}\n","import { WakuMessage } from \"js-waku\";\nimport { ChatMessage } from \"./chat_message\";\n\nexport class Message {\n public chatMessage: ChatMessage;\n // WakuMessage timestamp\n public sentTimestamp: Date | undefined;\n\n constructor(chatMessage: ChatMessage, sentTimestamp: Date | undefined) {\n this.chatMessage = chatMessage;\n this.sentTimestamp = sentTimestamp;\n }\n\n static fromWakuMessage(wakuMsg: WakuMessage): Message | undefined {\n if (wakuMsg.payload) {\n try {\n const chatMsg = ChatMessage.decode(wakuMsg.payload);\n if (chatMsg) {\n return new Message(chatMsg, wakuMsg.timestamp);\n }\n } catch (e) {\n console.error(\"Failed to decode chat message\", e);\n }\n }\n return;\n }\n\n static fromUtf8String(nick: string, text: string): Message {\n const now = new Date();\n return new Message(ChatMessage.fromUtf8String(now, nick, text), now);\n }\n\n get nick() {\n return this.chatMessage.nick;\n }\n\n get timestamp() {\n return this.chatMessage.timestamp;\n }\n\n get payloadAsUtf8() {\n return this.chatMessage.payloadAsUtf8;\n }\n}\n","/**\n * Return pseudo random subset of the input.\n */\nexport function getPseudoRandomSubset(\n values: T[],\n wantedNumber: number\n): T[] {\n if (values.length <= wantedNumber || values.length <= 1) {\n return values;\n }\n\n return shuffle(values).slice(0, wantedNumber);\n}\n\nfunction shuffle(arr: T[]): T[] {\n if (arr.length <= 1) {\n return arr;\n }\n const randInt = (): number => {\n return Math.floor(Math.random() * Math.floor(arr.length));\n };\n\n for (let i = 0; i < arr.length; i++) {\n const j = randInt();\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n return arr;\n}\n","import { Multiaddr } from \"@multiformats/multiaddr\";\n\nimport { getPseudoRandomSubset } from \"./random_subset\";\n\nexport const DefaultWantedNumber = 1;\n\nexport enum Fleet {\n Prod = \"prod\",\n Test = \"test\",\n}\n\n/**\n * Return list of pre-defined (hardcoded) bootstrap nodes.\n *\n * Default behavior is to return nodes of the nwaku Status Prod fleet.\n *\n * @param fleet The fleet to be returned. Defaults to production fleet.\n * @param wantedNumber The number of connections desired. Defaults to [[DefaultWantedNumber]].\n *\n * @returns An array of multiaddresses.\n */\nexport function getPredefinedBootstrapNodes(\n fleet: Fleet = Fleet.Prod,\n wantedNumber: number = DefaultWantedNumber\n): Multiaddr[] {\n if (wantedNumber <= 0) {\n return [];\n }\n\n let nodes;\n switch (fleet) {\n case Fleet.Prod:\n nodes = fleets.fleets[\"wakuv2.prod\"][\"waku-websocket\"];\n break;\n case Fleet.Test:\n nodes = fleets.fleets[\"wakuv2.test\"][\"waku-websocket\"];\n break;\n default:\n nodes = fleets.fleets[\"wakuv2.prod\"][\"waku-websocket\"];\n }\n\n nodes = Object.values(nodes) as string[];\n\n nodes = nodes.map((node: string) => new Multiaddr(node));\n return getPseudoRandomSubset(nodes, wantedNumber);\n}\n\nexport const fleets = {\n fleets: {\n \"wakuv2.prod\": {\n \"waku-websocket\": {\n \"node-01.ac-cn-hongkong-c.wakuv2.prod\":\n \"/dns4/node-01.ac-cn-hongkong-c.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAm4v86W3bmT1BiH6oSPzcsSr24iDQpSN5Qa992BCjjwgrD\",\n \"node-01.do-ams3.wakuv2.prod\":\n \"/dns4/node-01.do-ams3.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAmL5okWopX7NqZWBUKVqW8iUxCEmd5GMHLVPwCgzYzQv3e\",\n \"node-01.gc-us-central1-a.wakuv2.prod\":\n \"/dns4/node-01.gc-us-central1-a.wakuv2.prod.statusim.net/tcp/443/wss/p2p/16Uiu2HAmVkKntsECaYfefR1V2yCR79CegLATuTPE6B9TxgxBiiiA\",\n },\n },\n \"wakuv2.test\": {\n \"waku-websocket\": {\n \"node-01.ac-cn-hongkong-c.wakuv2.test\":\n \"/dns4/node-01.ac-cn-hongkong-c.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAkvWiyFsgRhuJEb9JfjYxEkoHLgnUQmr1N5mKWnYjxYRVm\",\n \"node-01.do-ams3.wakuv2.test\":\n \"/dns4/node-01.do-ams3.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAmPLe7Mzm8TsYUubgCAW1aJoeFScxrLj8ppHFivPo97bUZ\",\n \"node-01.gc-us-central1-a.wakuv2.test\":\n \"/dns4/node-01.gc-us-central1-a.wakuv2.test.statusim.net/tcp/443/wss/p2p/16Uiu2HAmJb2e28qLXxT5kZxVUUoJt72EMzNGXB47Rxx5hw3q4YjS\",\n },\n },\n },\n};\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined ?\n\tnew AbortError(errorMessage) :\n\tnew DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined ?\n\t\tgetDOMException('This operation was aborted.') :\n\t\tsignal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, milliseconds, fallback, options) {\n\tlet timer;\n\n\tconst cancelablePromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\toptions = {\n\t\t\tcustomTimers: {setTimeout, clearTimeout},\n\t\t\t...options\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\ttimer = options.customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (typeof fallback === 'function') {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t} finally {\n\t\t\t\toptions.customTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tclearTimeout(timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.on || emitter.addListener || emitter.addEventListener;\n\tconst removeListener = emitter.off || emitter.removeListener || emitter.removeEventListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\t\tif (options.filter && !options.filter(value)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = error => {\n\t\t\tcancel();\n\t\t\treject(error);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, options.timeout);\n\t\ttimeout.cancel = cancel;\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t// eslint-disable-next-line unicorn/no-array-callback-reference\n\t\tif (options.filter && !options.filter(value)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n","import type { GossipSub } from \"@chainsafe/libp2p-gossipsub\";\nimport { Peer, PeerProtocolsChangeData } from \"@libp2p/interface-peer-store\";\nimport debug from \"debug\";\nimport type { Libp2p } from \"libp2p\";\nimport { pEvent } from \"p-event\";\n\nimport { StoreCodecs } from \"./constants\";\nimport { Protocols, Waku } from \"./waku\";\nimport { FilterCodec } from \"./waku_filter\";\nimport { LightPushCodec } from \"./waku_light_push\";\n\nconst log = debug(\"waku:wait-for-remote-peer\");\n\ninterface WakuProtocol {\n libp2p: Libp2p;\n peers: () => Promise;\n}\n\ninterface WakuGossipSubProtocol extends GossipSub {\n getMeshPeers: () => string[];\n}\n\n/**\n * Wait for a remote peer to be ready given the passed protocols.\n * Must be used after attempting to connect to nodes, using {@link index.waku.Waku.dial} or\n * a bootstrap method with {@link index.waku.Waku.constructor}.\n *\n * If the passed protocols is a GossipSub protocol, then it resolves only once\n * a peer is in a mesh, to help ensure that other peers will send and receive\n * message to us.\n *\n * @param waku The Waku Node\n * @param protocols The protocols that need to be enabled by remote peers.\n * @param timeoutMs A timeout value in milliseconds..\n *\n * @returns A promise that **resolves** if all desired protocols are fulfilled by\n * remote nodes, **rejects** if the timeoutMs is reached.\n *\n * @default Remote peer must have Waku Relay enabled and no time out is applied.\n */\nexport async function waitForRemotePeer(\n waku: Waku,\n protocols?: Protocols[],\n timeoutMs?: number\n): Promise {\n protocols = protocols ?? [Protocols.Relay];\n\n if (!waku.isStarted()) return Promise.reject(\"Waku node is not started\");\n\n const promises = [];\n\n if (protocols.includes(Protocols.Relay)) {\n promises.push(waitForGossipSubPeerInMesh(waku.relay));\n }\n\n if (protocols.includes(Protocols.Store)) {\n promises.push(waitForConnectedPeer(waku.store, Object.values(StoreCodecs)));\n }\n\n if (protocols.includes(Protocols.LightPush)) {\n promises.push(waitForConnectedPeer(waku.lightPush, [LightPushCodec]));\n }\n\n if (protocols.includes(Protocols.Filter)) {\n promises.push(waitForConnectedPeer(waku.filter, [FilterCodec]));\n }\n\n if (timeoutMs) {\n await rejectOnTimeout(\n Promise.all(promises),\n timeoutMs,\n \"Timed out waiting for a remote peer.\"\n );\n } else {\n await Promise.all(promises);\n }\n}\n\n/**\n * Wait for a peer with the given protocol to be connected.\n */\nasync function waitForConnectedPeer(\n waku: WakuProtocol,\n codecs: string[]\n): Promise {\n const peers = await waku.peers();\n\n if (peers.length) {\n log(`${codecs} peer found: `, peers[0].id.toString());\n return;\n }\n\n await new Promise((resolve) => {\n const cb = (evt: CustomEvent): void => {\n for (const codec of codecs) {\n if (evt.detail.protocols.includes(codec)) {\n log(\"Resolving for\", codec, evt.detail.protocols);\n waku.libp2p.peerStore.removeEventListener(\"change:protocols\", cb);\n resolve();\n break;\n }\n }\n };\n waku.libp2p.peerStore.addEventListener(\"change:protocols\", cb);\n });\n}\n\n/**\n * Wait for a peer with the given protocol to be connected and in the gossipsub\n * mesh.\n */\nasync function waitForGossipSubPeerInMesh(\n waku: WakuGossipSubProtocol\n): Promise {\n let peers = waku.getMeshPeers();\n\n while (peers.length == 0) {\n await pEvent(waku, \"gossipsub:heartbeat\");\n peers = waku.getMeshPeers();\n }\n}\n\nconst awaitTimeout = (ms: number, rejectReason: string): Promise =>\n new Promise((_resolve, reject) => setTimeout(() => reject(rejectReason), ms));\n\nasync function rejectOnTimeout(\n promise: Promise,\n timeoutMs: number,\n rejectReason: string\n): Promise {\n await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);\n}\n","import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\n\nexport const symbol = Symbol.for('@libp2p/peer-discovery')\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent\n}\n\nexport interface PeerDiscovery extends EventEmitter {\n /**\n * Used to identify the peer discovery mechanism\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isPeerDiscovery function\n */\n [symbol]: true\n}\n\nexport function isPeerDiscovery (other: any): other is PeerDiscovery {\n return other != null && Boolean(other[symbol])\n}\n","import type {\n PeerDiscovery,\n PeerDiscoveryEvents,\n} from \"@libp2p/interface-peer-discovery\";\nimport { symbol } from \"@libp2p/interface-peer-discovery\";\nimport type { PeerInfo } from \"@libp2p/interface-peer-info\";\nimport { CustomEvent, EventEmitter } from \"@libp2p/interfaces/events\";\nimport { Multiaddr } from \"@multiformats/multiaddr\";\nimport debug from \"debug\";\n\nimport { multiaddrsToPeerInfo } from \"./multiaddr_to_peer_info\";\nimport { getPseudoRandomSubset } from \"./random_subset\";\n\nconst log = debug(\"waku:peer-discovery-static-list\");\n\nexport interface Options {\n /**\n * The maximum of peers to connect to as part of the bootstrap process.\n *\n * @default The length of the passed `peers` array.\n */\n maxPeers?: number;\n /**\n * The interval between emitting addresses in milliseconds.\n *\n * @default {@link PeerDiscoveryEvents.DefaultInterval}\n */\n interval?: number;\n}\n\n/**\n * Parse options and expose function to return bootstrap peer addresses.\n *\n * @throws if an invalid combination of options is passed, see [[BootstrapOptions]] for details.\n */\nexport class PeerDiscoveryStaticPeers\n extends EventEmitter\n implements PeerDiscovery\n{\n static DefaultInterval = 200;\n private readonly peers: PeerInfo[];\n private timer?: ReturnType;\n private readonly interval: number;\n\n /**\n * @param peers Multiaddrs of peers to connect to.\n * @param opts\n */\n constructor(peers: string[] | Multiaddr[], opts?: Options) {\n super();\n\n this.interval = opts?.interval ?? PeerDiscoveryStaticPeers.DefaultInterval;\n const maxPeers = opts?.maxPeers ?? peers?.length;\n\n const peerMas = peers.map((peer: string | Multiaddr) => {\n if (typeof peer === \"string\") {\n return new Multiaddr(peer);\n } else {\n return peer;\n }\n });\n this.peers = multiaddrsToPeerInfo(getPseudoRandomSubset(peerMas, maxPeers));\n log(\n \"Use provided list of peers (reduced to maxPeers)\",\n this.peers.map((ma) => ma.toString())\n );\n }\n\n /**\n * Start emitting static peers.\n */\n start(): void {\n this._startTimer();\n }\n\n private _startTimer(): void {\n if (this.peers) {\n log(\"Starting to emit static peers.\");\n if (this.timer != null) {\n return;\n }\n\n this.timer = setInterval(() => this._returnPeers(), this.interval);\n\n this._returnPeers();\n }\n }\n\n _returnPeers(): void {\n if (this.timer == null) {\n return;\n }\n\n this.peers.forEach((peerData) => {\n this.dispatchEvent(\n new CustomEvent(\"peer\", { detail: peerData })\n );\n });\n }\n\n /**\n * Stop emitting peers.\n */\n stop(): void {\n if (this.timer != null) {\n clearInterval(this.timer);\n }\n\n this.timer = undefined;\n }\n\n get [symbol](): true {\n return true;\n }\n\n get [Symbol.toStringTag](): string {\n return \"@waku/peer-discovery-static-list\";\n }\n}\n","import { PeerInfo } from \"@libp2p/interface-peer-info\";\nimport { peerIdFromString } from \"@libp2p/peer-id\";\nimport { Multiaddr } from \"@multiformats/multiaddr\";\n\nexport function multiaddrsToPeerInfo(mas: Multiaddr[]): PeerInfo[] {\n return mas\n .map((ma) => {\n const peerIdStr = ma.getPeerId();\n const protocols: string[] = [];\n return {\n id: peerIdStr ? peerIdFromString(peerIdStr) : null,\n multiaddrs: [ma.decapsulateCode(421)],\n protocols,\n };\n })\n .filter((peerInfo): peerInfo is PeerInfo => peerInfo.id !== null);\n}\n","import { HKDF } from '@stablelib/hkdf'\nimport * as x25519 from '@stablelib/x25519'\nimport { SHA256, hash } from '@stablelib/sha256'\nimport { ChaCha20Poly1305 } from '@stablelib/chacha20poly1305'\nimport type { bytes32, bytes } from '../@types/basic.js'\nimport type { Hkdf } from '../@types/handshake.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport type { ICryptoInterface } from '../crypto.js'\n\nexport const stablelib: ICryptoInterface = {\n hashSHA256 (data: Uint8Array): Uint8Array {\n return hash(data)\n },\n\n getHKDF (ck: bytes32, ikm: Uint8Array): Hkdf {\n const hkdf = new HKDF(SHA256, ikm, ck)\n const okmU8Array = hkdf.expand(96)\n const okm = okmU8Array\n\n const k1 = okm.subarray(0, 32)\n const k2 = okm.subarray(32, 64)\n const k3 = okm.subarray(64, 96)\n\n return [k1, k2, k3]\n },\n\n generateX25519KeyPair (): KeyPair {\n const keypair = x25519.generateKeyPair()\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair {\n const keypair = x25519.generateKeyPairFromSeed(seed)\n\n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey\n }\n },\n\n generateX25519SharedKey (privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array {\n return x25519.sharedKey(privateKey, publicKey)\n },\n\n chaCha20Poly1305Encrypt (plaintext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.seal(nonce, plaintext, ad)\n },\n\n chaCha20Poly1305Decrypt (ciphertext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes | null {\n const ctx = new ChaCha20Poly1305(k)\n\n return ctx.open(nonce, ciphertext, ad)\n }\n}\n","export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n","import { Reader, reader } from 'it-reader'\nimport { pushable } from 'it-pushable'\nimport defer from 'p-defer'\nimport type { Duplex, Source } from 'it-stream-types'\nimport type { Pushable } from 'it-pushable'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Handshake {\n reader: Reader\n writer: Pushable\n stream: Duplex\n rest: () => Source\n write: (data: TSink) => void\n read: () => Promise\n}\n\n// Convert a duplex stream into a reader and writer and rest stream\nexport function handshake (stream: Duplex): Handshake {\n const writer = pushable() // Write bytes on demand to the sink\n const source = reader(stream.source) // Read bytes on demand from the source\n\n // Waits for a source to be passed to the rest stream's sink\n const sourcePromise = defer>()\n let sinkErr: Error\n\n const sinkPromise = stream.sink((async function * () {\n yield * writer\n const source = await sourcePromise.promise\n yield * source\n })())\n\n sinkPromise.catch(err => {\n sinkErr = err\n })\n\n const rest: Duplex = {\n sink: async source => {\n if (sinkErr != null) {\n return await Promise.reject(sinkErr)\n }\n\n sourcePromise.resolve(source)\n return await sinkPromise\n },\n source\n }\n\n return {\n reader: source,\n writer,\n stream: rest,\n rest: () => writer.end(),\n write: writer.push,\n read: async () => {\n const res = await source.next()\n\n if (res.value != null) {\n return res.value\n }\n }\n }\n}\n","import { Uint8ArrayList } from 'uint8arraylist'\nimport type { Source } from 'it-stream-types'\n\nexport interface Reader extends AsyncGenerator {\n next: (...args: [] | [number | undefined]) => Promise>\n}\n\nexport function reader (source: Source) {\n const reader: Reader = (async function * (): AsyncGenerator {\n // @ts-expect-error first yield in stream is ignored\n let bytes: number | undefined = yield // Allows us to receive 8 when reader.next(8) is called\n let bl = new Uint8ArrayList()\n\n for await (const chunk of source) {\n if (bytes == null) {\n bl.append(chunk)\n bytes = yield bl\n bl = new Uint8ArrayList()\n continue\n }\n\n bl.append(chunk)\n\n while (bl.length >= bytes) {\n const data = bl.sublist(0, bytes)\n bl.consume(bytes)\n bytes = yield data\n\n // If we no longer want a specific byte length, we yield the rest now\n if (bytes == null) {\n if (bl.length > 0) {\n bytes = yield bl\n bl = new Uint8ArrayList()\n }\n break // bytes is null and/or no more buffer to yield\n }\n }\n }\n\n // Consumer wants more bytes but the source has ended and our buffer\n // is not big enough to satisfy.\n if (bytes != null) {\n throw Object.assign(\n new Error(`stream ended before ${bytes} bytes became available`),\n { code: 'ERR_UNDER_READ', buffer: bl }\n )\n }\n })()\n\n void reader.next()\n return reader\n}\n","import { handshake } from 'it-handshake'\nimport * as lp from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\ninterface Decoder {\n (data: Uint8Array | Uint8ArrayList): T\n}\n\ninterface Encoder {\n (data: T): Uint8Array\n}\n\nexport interface ProtobufStream {\n read: (bytes?: number) => Promise\n readLP: () => Promise\n readPB: (proto: { decode: Decoder }) => Promise\n write: (input: Uint8Array | Uint8ArrayList) => void\n writeLP: (input: Uint8Array | Uint8ArrayList) => void\n writePB: (data: Uint8Array | Uint8ArrayList, proto: {encode: Encoder}) => void\n pb: (proto: {encode: Encoder, decode: Decoder }) => {read: () => Promise, write: (d: Uint8Array | Uint8ArrayList) => void}\n\n // return vanilla duplex\n unwrap: () => Duplex\n}\n\nexport interface Opts {\n // encoding opts\n poolSize: number\n minPoolSize: number\n lengthEncoder: lp.LengthEncoderFunction\n\n // decoding opts\n lengthDecoder: lp.LengthDecoderFunction\n maxLengthLength: number\n maxDataLength: number\n}\n\nexport function pbStream (duplex: Duplex, opts = {}): ProtobufStream {\n const shake = handshake(duplex)\n const lpReader = lp.decode.fromReader(\n shake.reader,\n opts\n )\n\n const W: ProtobufStream = {\n read: async (bytes) => {\n // just read\n const { value } = await shake.reader.next(bytes)\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n return value\n },\n readLP: async () => {\n // read, decode\n // @ts-expect-error .next is part of the generator interface\n const { value } = await lpReader.next()\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n return value\n },\n readPB: async (proto) => {\n // readLP, decode\n const value = await W.readLP()\n\n if (value == null) {\n throw new Error('Value is null')\n }\n\n // Is this a buffer?\n const buf = value instanceof Uint8Array ? value : value.slice()\n\n return proto.decode(buf)\n },\n write: (data) => {\n // just write\n if (data instanceof Uint8Array) {\n shake.writer.push(data)\n } else {\n shake.writer.push(data.slice())\n }\n },\n writeLP: (data) => {\n // encode, write\n W.write(lp.encode.single(data, opts))\n },\n writePB: (data, proto) => {\n // encode, writeLP\n W.writeLP(proto.encode(data))\n },\n pb: (proto) => {\n return {\n read: async () => await W.readPB(proto),\n write: (d) => W.writePB(d, proto)\n }\n },\n unwrap: () => {\n // returns vanilla duplex again, terminates all reads/writes from this object\n shake.rest()\n return shake.stream\n }\n }\n\n return W\n}\n","import defer from 'p-defer'\nimport type { Source, Duplex } from 'it-stream-types'\n\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair (): Duplex {\n const deferred = defer>()\n let piped = false\n\n return {\n sink: async source => {\n if (piped) {\n throw new Error('already piped')\n }\n\n piped = true\n deferred.resolve(source)\n },\n source: (async function * () {\n const source = await deferred.promise\n\n yield * source\n }())\n }\n}\n","export const NOISE_MSG_MAX_LENGTH_BYTES = 65535\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16\n\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS)\n","import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { bytes } from './@types/basic.js'\nimport type { MessageBuffer } from './@types/handshake.js'\nimport type { LengthDecoderFunction, LengthEncoderFunction } from 'it-length-prefixed'\n\nconst allocUnsafe = (len: number): Uint8Array => {\n if (globalThis.Buffer) {\n return globalThis.Buffer.allocUnsafe(len)\n }\n\n return new Uint8Array(len)\n}\n\nexport const uint16BEEncode: LengthEncoderFunction = (value: number) => {\n const target = allocUnsafe(2)\n new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)\n return target\n}\nuint16BEEncode.bytes = 2\n\nexport const uint16BEDecode: LengthDecoderFunction = (data: Uint8Array | Uint8ArrayList): number => {\n if (data.length < 2) throw RangeError('Could not decode int16BE')\n\n if (data instanceof Uint8Array) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false)\n }\n\n return data.getUint16(0)\n}\nuint16BEDecode.bytes = 2\n\n// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)\n\nexport function encode0 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ciphertext], message.ne.length + message.ciphertext.length)\n}\n\nexport function encode1 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ne, message.ns, message.ciphertext], message.ne.length + message.ns.length + message.ciphertext.length)\n}\n\nexport function encode2 (message: MessageBuffer): bytes {\n return uint8ArrayConcat([message.ns, message.ciphertext], message.ns.length + message.ciphertext.length)\n}\n\nexport function decode0 (input: bytes): MessageBuffer {\n if (input.length < 32) {\n throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ciphertext: input.subarray(32, input.length),\n ns: new Uint8Array(0)\n }\n}\n\nexport function decode1 (input: bytes): MessageBuffer {\n if (input.length < 80) {\n throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')\n }\n\n return {\n ne: input.subarray(0, 32),\n ns: input.subarray(32, 80),\n ciphertext: input.subarray(80, input.length)\n }\n}\n\nexport function decode2 (input: bytes): MessageBuffer {\n if (input.length < 48) {\n throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')\n }\n\n return {\n ne: new Uint8Array(0),\n ns: input.subarray(0, 48),\n ciphertext: input.subarray(48, input.length)\n }\n}\n","\nexport class UnexpectedPeerError extends Error {\n public code: string\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.code = UnexpectedPeerError.code\n }\n\n static get code () {\n return 'ERR_UNEXPECTED_PEER'\n }\n}\n\nexport class InvalidCryptoExchangeError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.code = InvalidCryptoExchangeError.code\n }\n\n static get code () {\n return 'ERR_INVALID_CRYPTO_EXCHANGE'\n }\n}\n\nexport class InvalidCryptoTransmissionError extends Error {\n public code: string\n\n constructor (message = 'Invalid crypto transmission') {\n super(message)\n this.code = InvalidCryptoTransmissionError.code\n }\n\n static get code () {\n return 'ERR_INVALID_CRYPTO_TRANSMISSION'\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport namespace pb {\n export interface NoiseHandshakePayload {\n identityKey: Uint8Array\n identitySig: Uint8Array\n data: Uint8Array\n }\n\n export namespace NoiseHandshakePayload {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.identityKey != null) {\n writer.uint32(10)\n writer.bytes(obj.identityKey)\n } else {\n throw new Error('Protocol error: required field \"identityKey\" was not found in object')\n }\n\n if (obj.identitySig != null) {\n writer.uint32(18)\n writer.bytes(obj.identitySig)\n } else {\n throw new Error('Protocol error: required field \"identitySig\" was not found in object')\n }\n\n if (obj.data != null) {\n writer.uint32(26)\n writer.bytes(obj.data)\n } else {\n throw new Error('Protocol error: required field \"data\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n identityKey: new Uint8Array(0),\n identitySig: new Uint8Array(0),\n data: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.identityKey = reader.bytes()\n break\n case 2:\n obj.identitySig = reader.bytes()\n break\n case 3:\n obj.data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.identityKey == null) {\n throw new Error('Protocol error: value for required field \"identityKey\" was not found in protobuf')\n }\n\n if (obj.identitySig == null) {\n throw new Error('Protocol error: value for required field \"identitySig\" was not found in protobuf')\n }\n\n if (obj.data == null) {\n throw new Error('Protocol error: value for required field \"data\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: NoiseHandshakePayload): Uint8Array => {\n return encodeMessage(obj, NoiseHandshakePayload.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): NoiseHandshakePayload => {\n return decodeMessage(buf, NoiseHandshakePayload.codec())\n }\n }\n}\n","import { unmarshalPublicKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { bytes } from './@types/basic.js'\nimport { pb } from './proto/payload.js'\n\nconst NoiseHandshakePayloadProto = pb.NoiseHandshakePayload\n\nexport async function getPayload (\n localPeer: PeerId,\n staticPublicKey: bytes,\n earlyData?: bytes\n): Promise {\n const signedPayload = await signPayload(localPeer, getHandshakePayload(staticPublicKey))\n const earlyDataPayload = earlyData ?? new Uint8Array(0)\n\n if (localPeer.publicKey == null) {\n throw new Error('PublicKey was missing from local PeerId')\n }\n\n return createHandshakePayload(\n localPeer.publicKey,\n signedPayload,\n earlyDataPayload\n )\n}\n\nexport function createHandshakePayload (\n libp2pPublicKey: Uint8Array,\n signedPayload: Uint8Array,\n earlyData?: Uint8Array\n): bytes {\n return NoiseHandshakePayloadProto.encode({\n identityKey: libp2pPublicKey,\n identitySig: signedPayload,\n data: earlyData ?? new Uint8Array(0)\n }).subarray()\n}\n\nexport async function signPayload (peerId: PeerId, payload: bytes): Promise {\n if (peerId.privateKey == null) {\n throw new Error('PrivateKey was missing from PeerId')\n }\n\n const privateKey = await unmarshalPrivateKey(peerId.privateKey)\n\n return await privateKey.sign(payload)\n}\n\nexport async function getPeerIdFromPayload (payload: pb.NoiseHandshakePayload): Promise {\n return await peerIdFromKeys(payload.identityKey)\n}\n\nexport function decodePayload (payload: bytes|Uint8Array): pb.NoiseHandshakePayload {\n return NoiseHandshakePayloadProto.decode(payload)\n}\n\nexport function getHandshakePayload (publicKey: bytes): bytes {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:')\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length)\n}\n\n/**\n * Verifies signed payload, throws on any irregularities.\n *\n * @param {bytes} noiseStaticKey - owner's noise static key\n * @param {bytes} payload - decoded payload\n * @param {PeerId} remotePeer - owner's libp2p peer ID\n * @returns {Promise} - peer ID of payload owner\n */\nexport async function verifySignedPayload (\n noiseStaticKey: bytes,\n payload: pb.NoiseHandshakePayload,\n remotePeer: PeerId\n): Promise {\n // Unmarshaling from PublicKey protobuf\n const payloadPeerId = await peerIdFromKeys(payload.identityKey)\n if (!payloadPeerId.equals(remotePeer)) {\n throw new Error(\"Peer ID doesn't match libp2p public key.\")\n }\n const generatedPayload = getHandshakePayload(noiseStaticKey)\n\n if (payloadPeerId.publicKey == null) {\n throw new Error('PublicKey was missing from PeerId')\n }\n\n if (payload.identitySig == null) {\n throw new Error('Signature was missing from message')\n }\n\n const publicKey = unmarshalPublicKey(payloadPeerId.publicKey)\n\n const valid = await publicKey.verify(generatedPayload, payload.identitySig)\n\n if (!valid) {\n throw new Error(\"Static key doesn't match to peer that signed payload!\")\n }\n\n return payloadPeerId\n}\n\nexport function isValidPublicKey (pk: bytes): boolean {\n if (!(pk instanceof Uint8Array)) {\n return false\n }\n\n if (pk.length !== 32) {\n return false\n }\n\n return true\n}\n","import { Logger, logger } from '@libp2p/logger'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport { DUMP_SESSION_KEYS } from './constants.js'\n\nconst log = logger('libp2p:noise')\n\nexport { log as logger }\n\nlet keyLogger: Logger\nif (DUMP_SESSION_KEYS) {\n keyLogger = log\n} else {\n keyLogger = Object.assign(() => { /* do nothing */ }, {\n enabled: false,\n trace: () => {},\n error: () => {}\n })\n}\n\nexport function logLocalStaticKeys (s: KeyPair): void {\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`)\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`)\n}\n\nexport function logLocalEphemeralKeys (e: KeyPair|undefined): void {\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`)\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`)\n } else {\n keyLogger('Missing local ephemeral keys.')\n }\n}\n\nexport function logRemoteStaticKey (rs: Uint8Array): void {\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs, 'hex')}`)\n}\n\nexport function logRemoteEphemeralKey (re: Uint8Array): void {\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re, 'hex')}`)\n}\n\nexport function logCipherState (session: NoiseSession): void {\n if (session.cs1 && session.cs2) {\n keyLogger(`CIPHER_STATE_1 ${session.cs1.n.getUint64()} ${uint8ArrayToString(session.cs1.k, 'hex')}`)\n keyLogger(`CIPHER_STATE_2 ${session.cs2.n.getUint64()} ${uint8ArrayToString(session.cs2.k, 'hex')}`)\n } else {\n keyLogger('Missing cipher state.')\n }\n}\n","import type { bytes, uint64 } from './@types/basic'\n\nexport const MIN_NONCE = 0\n// For performance reasons, the nonce is represented as a JS `number`\n// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use\n// 4 bytes to store the data for performance reason.\n// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2\n// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.\n// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.\nexport const MAX_NONCE = 0xffffffff\n\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed'\n\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n private n: uint64\n private readonly bytes: bytes\n private readonly view: DataView\n\n constructor (n = MIN_NONCE) {\n this.n = n\n this.bytes = new Uint8Array(12)\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength)\n this.view.setUint32(4, n, true)\n }\n\n increment (): void {\n this.n++\n // Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.\n this.view.setUint32(4, this.n, true)\n }\n\n getBytes (): bytes {\n return this.bytes\n }\n\n getUint64 (): uint64 {\n return this.n\n }\n\n assertValue (): void {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE)\n }\n }\n}\n","import type { bytes32, bytes } from '../@types/basic.js'\nimport type { KeyPair } from '../@types/libp2p.js'\nimport { isValidPublicKey } from '../utils.js'\nimport type { CipherState, HandshakeState, MessageBuffer, NoiseSession } from '../@types/handshake.js'\nimport { AbstractHandshake } from './abstract-handshake.js'\n\nexport class XX extends AbstractHandshake {\n private initializeInitiator (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private initializeResponder (prologue: bytes32, s: KeyPair, rs: bytes32, psk: bytes32): HandshakeState {\n const name = 'Noise_XX_25519_ChaChaPoly_SHA256'\n const ss = this.initializeSymmetric(name)\n this.mixHash(ss, prologue)\n const re = new Uint8Array(32)\n\n return { ss, s, rs, psk, re }\n }\n\n private writeMessageA (hs: HandshakeState, payload: bytes, e?: KeyPair): MessageBuffer {\n const ns = new Uint8Array(0)\n\n if (e !== undefined) {\n hs.e = e\n } else {\n hs.e = this.crypto.generateX25519KeyPair()\n }\n\n const ne = hs.e.publicKey\n\n this.mixHash(hs.ss, ne)\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageB (hs: HandshakeState, payload: bytes): MessageBuffer {\n hs.e = this.crypto.generateX25519KeyPair()\n const ne = hs.e.publicKey\n this.mixHash(hs.ss, ne)\n\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n\n return { ne, ns, ciphertext }\n }\n\n private writeMessageC (hs: HandshakeState, payload: bytes): { messageBuffer: MessageBuffer, cs1: CipherState, cs2: CipherState, h: bytes } {\n const spk = hs.s.publicKey\n const ns = this.encryptAndHash(hs.ss, spk)\n this.mixKey(hs.ss, this.dh(hs.s.privateKey, hs.re))\n const ciphertext = this.encryptAndHash(hs.ss, payload)\n const ne = this.createEmptyKey()\n const messageBuffer: MessageBuffer = { ne, ns, ciphertext }\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, messageBuffer, cs1, cs2 }\n }\n\n private readMessageA (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n return this.decryptAndHash(hs.ss, message.ciphertext)\n }\n\n private readMessageB (hs: HandshakeState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n if (isValidPublicKey(message.ne)) {\n hs.re = message.ne\n }\n\n this.mixHash(hs.ss, hs.re)\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.re))\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n return { plaintext, valid: (valid1 && valid2) }\n }\n\n private readMessageC (hs: HandshakeState, message: MessageBuffer): {h: bytes, plaintext: bytes, valid: boolean, cs1: CipherState, cs2: CipherState} {\n const { plaintext: ns, valid: valid1 } = this.decryptAndHash(hs.ss, message.ns)\n if (valid1 && isValidPublicKey(ns)) {\n hs.rs = ns\n }\n if (!hs.e) {\n throw new Error('Handshake state `e` param is missing.')\n }\n this.mixKey(hs.ss, this.dh(hs.e.privateKey, hs.rs))\n\n const { plaintext, valid: valid2 } = this.decryptAndHash(hs.ss, message.ciphertext)\n const { cs1, cs2 } = this.split(hs.ss)\n\n return { h: hs.ss.h, plaintext, valid: (valid1 && valid2), cs1, cs2 }\n }\n\n public initSession (initiator: boolean, prologue: bytes32, s: KeyPair): NoiseSession {\n const psk = this.createEmptyKey()\n const rs = new Uint8Array(32) // no static key yet\n let hs\n\n if (initiator) {\n hs = this.initializeInitiator(prologue, s, rs, psk)\n } else {\n hs = this.initializeResponder(prologue, s, rs, psk)\n }\n\n return {\n hs,\n i: initiator,\n mc: 0\n }\n }\n\n public sendMessage (session: NoiseSession, message: bytes, ephemeral?: KeyPair): MessageBuffer {\n let messageBuffer: MessageBuffer\n if (session.mc === 0) {\n messageBuffer = this.writeMessageA(session.hs, message, ephemeral)\n } else if (session.mc === 1) {\n messageBuffer = this.writeMessageB(session.hs, message)\n } else if (session.mc === 2) {\n const { h, messageBuffer: resultingBuffer, cs1, cs2 } = this.writeMessageC(session.hs, message)\n messageBuffer = resultingBuffer\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n } else if (session.mc > 2) {\n if (session.i) {\n if (!session.cs1) {\n throw new Error('CS1 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs1, message)\n } else {\n if (!session.cs2) {\n throw new Error('CS2 (cipher state) is not defined')\n }\n\n messageBuffer = this.writeMessageRegular(session.cs2, message)\n }\n } else {\n throw new Error('Session invalid.')\n }\n\n session.mc++\n return messageBuffer\n }\n\n public recvMessage (session: NoiseSession, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n let plaintext: bytes = new Uint8Array(0)\n let valid = false\n if (session.mc === 0) {\n ({ plaintext, valid } = this.readMessageA(session.hs, message))\n } else if (session.mc === 1) {\n ({ plaintext, valid } = this.readMessageB(session.hs, message))\n } else if (session.mc === 2) {\n const { h, plaintext: resultingPlaintext, valid: resultingValid, cs1, cs2 } = this.readMessageC(session.hs, message)\n plaintext = resultingPlaintext\n valid = resultingValid\n session.h = h\n session.cs1 = cs1\n session.cs2 = cs2\n }\n session.mc++\n return { plaintext, valid }\n }\n}\n","import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays'\nimport type { bytes, bytes32 } from '../@types/basic.js'\nimport type { CipherState, MessageBuffer, SymmetricState } from '../@types/handshake.js'\nimport type { ICryptoInterface } from '../crypto.js'\nimport { logger } from '../logger.js'\nimport { Nonce } from '../nonce.js'\n\nexport abstract class AbstractHandshake {\n public crypto: ICryptoInterface\n\n constructor (crypto: ICryptoInterface) {\n this.crypto = crypto\n }\n\n public encryptWithAd (cs: CipherState, ad: Uint8Array, plaintext: Uint8Array): bytes {\n const e = this.encrypt(cs.k, cs.n, ad, plaintext)\n cs.n.increment()\n\n return e\n }\n\n public decryptWithAd (cs: CipherState, ad: Uint8Array, ciphertext: Uint8Array): {plaintext: bytes, valid: boolean} {\n const { plaintext, valid } = this.decrypt(cs.k, cs.n, ad, ciphertext)\n if (valid) cs.n.increment()\n\n return { plaintext, valid }\n }\n\n // Cipher state related\n protected hasKey (cs: CipherState): boolean {\n return !this.isEmptyKey(cs.k)\n }\n\n protected createEmptyKey (): bytes32 {\n return new Uint8Array(32)\n }\n\n protected isEmptyKey (k: bytes32): boolean {\n const emptyKey = this.createEmptyKey()\n return uint8ArrayEquals(emptyKey, k)\n }\n\n protected encrypt (k: bytes32, n: Nonce, ad: Uint8Array, plaintext: Uint8Array): bytes {\n n.assertValue()\n\n return this.crypto.chaCha20Poly1305Encrypt(plaintext, n.getBytes(), ad, k)\n }\n\n protected encryptAndHash (ss: SymmetricState, plaintext: bytes): bytes {\n let ciphertext\n if (this.hasKey(ss.cs)) {\n ciphertext = this.encryptWithAd(ss.cs, ss.h, plaintext)\n } else {\n ciphertext = plaintext\n }\n\n this.mixHash(ss, ciphertext)\n return ciphertext\n }\n\n protected decrypt (k: bytes32, n: Nonce, ad: bytes, ciphertext: bytes): {plaintext: bytes, valid: boolean} {\n n.assertValue()\n\n const encryptedMessage = this.crypto.chaCha20Poly1305Decrypt(ciphertext, n.getBytes(), ad, k)\n\n if (encryptedMessage) {\n return {\n plaintext: encryptedMessage,\n valid: true\n }\n } else {\n return {\n plaintext: new Uint8Array(0),\n valid: false\n }\n }\n }\n\n protected decryptAndHash (ss: SymmetricState, ciphertext: bytes): {plaintext: bytes, valid: boolean} {\n let plaintext: bytes; let valid = true\n if (this.hasKey(ss.cs)) {\n ({ plaintext, valid } = this.decryptWithAd(ss.cs, ss.h, ciphertext))\n } else {\n plaintext = ciphertext\n }\n\n this.mixHash(ss, ciphertext)\n return { plaintext, valid }\n }\n\n protected dh (privateKey: bytes32, publicKey: bytes32): bytes32 {\n try {\n const derivedU8 = this.crypto.generateX25519SharedKey(privateKey, publicKey)\n\n if (derivedU8.length === 32) {\n return derivedU8\n }\n\n return derivedU8.subarray(0, 32)\n } catch (e) {\n const err = e as Error\n logger(err.message)\n return new Uint8Array(32)\n }\n }\n\n protected mixHash (ss: SymmetricState, data: bytes): void {\n ss.h = this.getHash(ss.h, data)\n }\n\n protected getHash (a: Uint8Array, b: Uint8Array): bytes32 {\n const u = this.crypto.hashSHA256(uint8ArrayConcat([a, b], a.length + b.length))\n return u\n }\n\n protected mixKey (ss: SymmetricState, ikm: bytes32): void {\n const [ck, tempK] = this.crypto.getHKDF(ss.ck, ikm)\n ss.cs = this.initializeKey(tempK)\n ss.ck = ck\n }\n\n protected initializeKey (k: bytes32): CipherState {\n return { k, n: new Nonce() }\n }\n\n // Symmetric state related\n\n protected initializeSymmetric (protocolName: string): SymmetricState {\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8')\n const h = this.hashProtocolName(protocolNameBytes)\n\n const ck = h\n const key = this.createEmptyKey()\n const cs: CipherState = this.initializeKey(key)\n\n return { cs, ck, h }\n }\n\n protected hashProtocolName (protocolName: Uint8Array): bytes32 {\n if (protocolName.length <= 32) {\n const h = new Uint8Array(32)\n h.set(protocolName)\n return h\n } else {\n return this.getHash(protocolName, new Uint8Array(0))\n }\n }\n\n protected split (ss: SymmetricState): {cs1: CipherState, cs2: CipherState} {\n const [tempk1, tempk2] = this.crypto.getHKDF(ss.ck, new Uint8Array(0))\n const cs1 = this.initializeKey(tempk1)\n const cs2 = this.initializeKey(tempk2)\n\n return { cs1, cs2 }\n }\n\n protected writeMessageRegular (cs: CipherState, payload: bytes): MessageBuffer {\n const ciphertext = this.encryptWithAd(cs, new Uint8Array(0), payload)\n const ne = this.createEmptyKey()\n const ns = new Uint8Array(0)\n\n return { ne, ns, ciphertext }\n }\n\n protected readMessageRegular (cs: CipherState, message: MessageBuffer): {plaintext: bytes, valid: boolean} {\n return this.decryptWithAd(cs, new Uint8Array(0), message.ciphertext)\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { InvalidCryptoExchangeError, UnexpectedPeerError } from '@libp2p/interface-connection-encrypter/errors'\nimport type { ProtobufStream } from 'it-pb-stream'\nimport type { bytes, bytes32 } from './@types/basic.js'\nimport type { CipherState, NoiseSession } from './@types/handshake.js'\nimport type { KeyPair } from './@types/libp2p.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { decode0, decode1, decode2, encode0, encode1, encode2 } from './encoder.js'\nimport { XX } from './handshakes/xx.js'\nimport {\n logger,\n logLocalStaticKeys,\n logLocalEphemeralKeys,\n logRemoteEphemeralKey,\n logRemoteStaticKey,\n logCipherState\n} from './logger.js'\nimport {\n decodePayload,\n getPeerIdFromPayload,\n verifySignedPayload\n} from './utils.js'\n\nexport class XXHandshake implements IHandshake {\n public isInitiator: boolean\n public session: NoiseSession\n public remotePeer!: PeerId\n public remoteEarlyData: bytes\n\n protected payload: bytes\n protected connection: ProtobufStream\n protected xx: XX\n protected staticKeypair: KeyPair\n\n private readonly prologue: bytes32\n\n constructor (\n isInitiator: boolean,\n payload: bytes,\n prologue: bytes32,\n crypto: ICryptoInterface,\n staticKeypair: KeyPair,\n connection: ProtobufStream,\n remotePeer?: PeerId,\n handshake?: XX\n ) {\n this.isInitiator = isInitiator\n this.payload = payload\n this.prologue = prologue\n this.staticKeypair = staticKeypair\n this.connection = connection\n if (remotePeer) {\n this.remotePeer = remotePeer\n }\n this.xx = handshake ?? new XX(crypto)\n this.session = this.xx.initSession(this.isInitiator, this.prologue, this.staticKeypair)\n this.remoteEarlyData = new Uint8Array(0)\n }\n\n // stage 0\n public async propose (): Promise {\n logLocalStaticKeys(this.session.hs.s)\n if (this.isInitiator) {\n logger('Stage 0 - Initiator starting to send first message.')\n const messageBuffer = this.xx.sendMessage(this.session, new Uint8Array(0))\n this.connection.writeLP(encode0(messageBuffer))\n logger('Stage 0 - Initiator finished sending first message.')\n logLocalEphemeralKeys(this.session.hs.e)\n } else {\n logger('Stage 0 - Responder waiting to receive first message...')\n const receivedMessageBuffer = decode0((await this.connection.readLP()).subarray())\n const { valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 0 validation fail')\n }\n logger('Stage 0 - Responder received first message.')\n logRemoteEphemeralKey(this.session.hs.re)\n }\n }\n\n // stage 1\n public async exchange (): Promise {\n if (this.isInitiator) {\n logger('Stage 1 - Initiator waiting to receive first message from responder...')\n const receivedMessageBuffer = decode1((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 1 validation fail')\n }\n logger('Stage 1 - Initiator received the message.')\n logRemoteEphemeralKey(this.session.hs.re)\n logRemoteStaticKey(this.session.hs.rs)\n\n logger(\"Initiator going to check remote's signature...\")\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n logger('All good with the signature!')\n } else {\n logger('Stage 1 - Responder sending out first message with signed payload and static key.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode1(messageBuffer))\n logger('Stage 1 - Responder sent the second handshake message with signed payload.')\n logLocalEphemeralKeys(this.session.hs.e)\n }\n }\n\n // stage 2\n public async finish (): Promise {\n if (this.isInitiator) {\n logger('Stage 2 - Initiator sending third handshake message.')\n const messageBuffer = this.xx.sendMessage(this.session, this.payload)\n this.connection.writeLP(encode2(messageBuffer))\n logger('Stage 2 - Initiator sent message with signed payload.')\n } else {\n logger('Stage 2 - Responder waiting for third handshake message...')\n const receivedMessageBuffer = decode2((await this.connection.readLP()).subarray())\n const { plaintext, valid } = this.xx.recvMessage(this.session, receivedMessageBuffer)\n if (!valid) {\n throw new InvalidCryptoExchangeError('xx handshake stage 2 validation fail')\n }\n logger('Stage 2 - Responder received the message, finished handshake.')\n\n try {\n const decodedPayload = decodePayload(plaintext)\n this.remotePeer = this.remotePeer || await getPeerIdFromPayload(decodedPayload)\n await verifySignedPayload(this.session.hs.rs, decodedPayload, this.remotePeer)\n this.setRemoteEarlyData(decodedPayload.data)\n } catch (e) {\n const err = e as Error\n throw new UnexpectedPeerError(`Error occurred while verifying signed payload: ${err.message}`)\n }\n }\n logCipherState(this.session)\n }\n\n public encrypt (plaintext: Uint8Array, session: NoiseSession): bytes {\n const cs = this.getCS(session)\n\n return this.xx.encryptWithAd(cs, new Uint8Array(0), plaintext)\n }\n\n public decrypt (ciphertext: Uint8Array, session: NoiseSession): {plaintext: bytes, valid: boolean} {\n const cs = this.getCS(session, false)\n\n return this.xx.decryptWithAd(cs, new Uint8Array(0), ciphertext)\n }\n\n public getRemoteStaticKey (): bytes {\n return this.session.hs.rs\n }\n\n private getCS (session: NoiseSession, encryption = true): CipherState {\n if (!session.cs1 || !session.cs2) {\n throw new InvalidCryptoExchangeError('Handshake not completed properly, cipher state does not exist.')\n }\n\n if (this.isInitiator) {\n return encryption ? session.cs1 : session.cs2\n } else {\n return encryption ? session.cs2 : session.cs1\n }\n }\n\n protected setRemoteEarlyData (data: Uint8Array|null|undefined): void {\n if (data) {\n this.remoteEarlyData = data\n }\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport type { SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport { pbStream, ProtobufStream } from 'it-pb-stream'\nimport { duplexPair } from 'it-pair/duplex'\nimport { pipe } from 'it-pipe'\nimport { encode, decode } from 'it-length-prefixed'\nimport type { Duplex } from 'it-stream-types'\nimport type { bytes } from './@types/basic.js'\nimport type { IHandshake } from './@types/handshake-interface.js'\nimport type { INoiseConnection, KeyPair } from './@types/libp2p.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js'\nimport type { ICryptoInterface } from './crypto.js'\nimport { stablelib } from './crypto/stablelib.js'\nimport { decryptStream, encryptStream } from './crypto/streaming.js'\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js'\nimport { XXHandshake } from './handshake-xx.js'\nimport { getPayload } from './utils.js'\n\ninterface HandshakeParams {\n connection: ProtobufStream\n isInitiator: boolean\n localPeer: PeerId\n remotePeer?: PeerId\n}\n\nexport class Noise implements INoiseConnection {\n public protocol = '/noise'\n public crypto: ICryptoInterface\n\n private readonly prologue: Uint8Array\n private readonly staticKeys: KeyPair\n private readonly earlyData?: bytes\n\n /**\n * @param {bytes} staticNoiseKey - x25519 private key, reuse for faster handshakes\n * @param {bytes} earlyData\n */\n constructor (staticNoiseKey?: bytes, earlyData?: bytes, crypto: ICryptoInterface = stablelib, prologueBytes?: Uint8Array) {\n this.earlyData = earlyData ?? new Uint8Array(0)\n this.crypto = crypto\n\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKeys = this.crypto.generateX25519KeyPairFromSeed(staticNoiseKey)\n } else {\n this.staticKeys = this.crypto.generateX25519KeyPair()\n }\n this.prologue = prologueBytes ?? new Uint8Array(0)\n }\n\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer\n * @param {Duplex} connection - streaming iterable duplex that will be encrypted\n * @param {PeerId} remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer.\n * @returns {Promise}\n */\n public async secureOutbound (localPeer: PeerId, connection: Duplex, remotePeer: PeerId): Promise {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: true,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remoteEarlyData: handshake.remoteEarlyData,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param {PeerId} localPeer - PeerId of the receiving peer.\n * @param {Duplex} connection - streaming iterable duplex that will be encryption.\n * @param {PeerId} remotePeer - optional PeerId of the initiating peer, if known. This may only exist during transport upgrades.\n * @returns {Promise}\n */\n public async secureInbound (localPeer: PeerId, connection: Duplex, remotePeer?: PeerId): Promise {\n const wrappedConnection = pbStream(\n connection,\n {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n }\n )\n const handshake = await this.performHandshake({\n connection: wrappedConnection,\n isInitiator: false,\n localPeer,\n remotePeer\n })\n const conn = await this.createSecureConnection(wrappedConnection, handshake)\n\n return {\n conn,\n remoteEarlyData: handshake.remoteEarlyData,\n remotePeer: handshake.remotePeer\n }\n }\n\n /**\n * If Noise pipes supported, tries IK handshake first with XX as fallback if it fails.\n * If noise pipes disabled or remote peer static key is unknown, use XX.\n *\n * @param {HandshakeParams} params\n */\n private async performHandshake (params: HandshakeParams): Promise {\n const payload = await getPayload(params.localPeer, this.staticKeys.publicKey, this.earlyData)\n\n // run XX handshake\n return await this.performXXHandshake(params, payload)\n }\n\n private async performXXHandshake (\n params: HandshakeParams,\n payload: bytes\n ): Promise {\n const { isInitiator, remotePeer, connection } = params\n const handshake = new XXHandshake(\n isInitiator,\n payload,\n this.prologue,\n this.crypto,\n this.staticKeys,\n connection,\n remotePeer\n )\n\n try {\n await handshake.propose()\n await handshake.exchange()\n await handshake.finish()\n } catch (e: unknown) {\n if (e instanceof Error) {\n e.message = `Error occurred during XX handshake: ${e.message}`\n throw e\n }\n }\n\n return handshake\n }\n\n private async createSecureConnection (\n connection: ProtobufStream,\n handshake: IHandshake\n ): Promise> {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair()\n const network = connection.unwrap()\n\n await pipe(\n secure, // write to wrapper\n encryptStream(handshake), // data is encrypted\n encode({ lengthEncoder: uint16BEEncode }), // prefix with message length\n network, // send to the remote peer\n decode({ lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake), // decrypt the incoming data\n secure // pipe to the wrapper\n )\n\n return user\n }\n}\n","import { pair } from './index.js'\nimport type { Duplex } from 'it-stream-types'\n\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair (): [Duplex, Duplex] {\n const a = pair()\n const b = pair()\n return [\n {\n source: a.source,\n sink: b.sink\n },\n {\n source: b.source,\n sink: a.sink\n }\n ]\n}\n","import type { Transform } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { IHandshake } from '../@types/handshake-interface.js'\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js'\n\n// Returns generator that encrypts payload from the user\nexport function encryptStream (handshake: IHandshake): Transform {\n return async function * (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG\n if (end > chunk.length) {\n end = chunk.length\n }\n\n const data = handshake.encrypt(chunk.subarray(i, end), handshake.session)\n yield data\n }\n }\n }\n}\n\n// Decrypt received payload to the user\nexport function decryptStream (handshake: IHandshake): Transform {\n return async function * (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES\n if (end > chunk.length) {\n end = chunk.length\n }\n\n const { plaintext: decrypted, valid } = await handshake.decrypt(chunk.subarray(i, end), handshake.session)\n if (!valid) {\n throw new Error('Failed to validate decrypted chunk')\n }\n yield decrypted\n }\n }\n }\n}\n","export function allocUnsafe (size: number) {\n return new Uint8Array(size)\n}\n","import type { Uint8ArrayList } from 'uint8arraylist'\n\ntype INITIATOR_NAME = 'NEW_STREAM' | 'MESSAGE' | 'CLOSE' | 'RESET'\ntype RECEIVER_NAME = 'MESSAGE' | 'CLOSE' | 'RESET'\ntype NAME = 'NEW_STREAM' | 'MESSAGE_INITIATOR' | 'CLOSE_INITIATOR' | 'RESET_INITIATOR' | 'MESSAGE_RECEIVER' | 'CLOSE_RECEIVER' | 'RESET_RECEIVER'\ntype CODE = 0 | 1 | 2 | 3 | 4 | 5 | 6\n\nexport enum MessageTypes {\n NEW_STREAM = 0,\n MESSAGE_RECEIVER = 1,\n MESSAGE_INITIATOR = 2,\n CLOSE_RECEIVER = 3,\n CLOSE_INITIATOR = 4,\n RESET_RECEIVER = 5,\n RESET_INITIATOR = 6\n}\n\nexport const MessageTypeNames: Record = Object.freeze({\n 0: 'NEW_STREAM',\n 1: 'MESSAGE_RECEIVER',\n 2: 'MESSAGE_INITIATOR',\n 3: 'CLOSE_RECEIVER',\n 4: 'CLOSE_INITIATOR',\n 5: 'RESET_RECEIVER',\n 6: 'RESET_INITIATOR'\n})\n\nexport const InitiatorMessageTypes: Record = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n})\n\nexport const ReceiverMessageTypes: Record = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n})\n\nexport interface NewStreamMessage {\n id: number\n type: MessageTypes.NEW_STREAM\n data: Uint8ArrayList\n}\n\nexport interface MessageReceiverMessage {\n id: number\n type: MessageTypes.MESSAGE_RECEIVER\n data: Uint8ArrayList\n}\n\nexport interface MessageInitiatorMessage {\n id: number\n type: MessageTypes.MESSAGE_INITIATOR\n data: Uint8ArrayList\n}\n\nexport interface CloseReceiverMessage {\n id: number\n type: MessageTypes.CLOSE_RECEIVER\n}\n\nexport interface CloseInitiatorMessage {\n id: number\n type: MessageTypes.CLOSE_INITIATOR\n}\n\nexport interface ResetReceiverMessage {\n id: number\n type: MessageTypes.RESET_RECEIVER\n}\n\nexport interface ResetInitiatorMessage {\n id: number\n type: MessageTypes.RESET_INITIATOR\n}\n\nexport type Message = NewStreamMessage | MessageReceiverMessage | MessageInitiatorMessage | CloseReceiverMessage | CloseInitiatorMessage | ResetReceiverMessage | ResetInitiatorMessage\n","import type { Source } from 'it-stream-types'\nimport varint from 'varint'\nimport { allocUnsafe } from './alloc-unsafe.js'\nimport { Message, MessageTypes } from './message-types.js'\n\nconst POOL_SIZE = 10 * 1024\n\nclass Encoder {\n private _pool: Uint8Array\n private _poolOffset: number\n\n constructor () {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n }\n\n /**\n * Encodes the given message and returns it and its header\n */\n write (msg: Message): Uint8Array[] {\n const pool = this._pool\n let offset = this._poolOffset\n\n varint.encode(msg.id << 3 | msg.type, pool, offset)\n offset += varint.encode.bytes\n\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n varint.encode(msg.data.length, pool, offset)\n } else {\n varint.encode(0, pool, offset)\n }\n\n offset += varint.encode.bytes\n\n const header = pool.subarray(this._poolOffset, offset)\n\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE)\n this._poolOffset = 0\n } else {\n this._poolOffset = offset\n }\n\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n return [\n header,\n msg.data instanceof Uint8Array ? msg.data : msg.data.subarray()\n ]\n }\n\n return [\n header\n ]\n }\n}\n\nconst encoder = new Encoder()\n\n/**\n * Encode and yield one or more messages\n */\nexport async function * encode (source: Source) {\n for await (const msg of source) {\n if (Array.isArray(msg)) {\n for (const m of msg) {\n yield * encoder.write(m)\n }\n } else {\n yield * encoder.write(msg)\n }\n }\n}\n","import { MessageTypeNames, MessageTypes } from './message-types.js'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Source } from 'it-stream-types'\nimport type { Message } from './message-types.js'\n\ninterface MessageHeader {\n id: number\n type: keyof typeof MessageTypeNames\n offset: number\n length: number\n}\n\nclass Decoder {\n private readonly _buffer: Uint8ArrayList\n private _headerInfo: MessageHeader | null\n\n constructor () {\n this._buffer = new Uint8ArrayList()\n this._headerInfo = null\n }\n\n write (chunk: Uint8Array) {\n if (chunk == null || chunk.length === 0) {\n return []\n }\n\n this._buffer.append(chunk)\n const msgs: Message[] = []\n\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer)\n } catch (_) {\n break // We haven't received enough data yet\n }\n }\n\n const { id, type, length, offset } = this._headerInfo\n const bufferedDataLength = this._buffer.length - offset\n\n if (bufferedDataLength < length) {\n break // not enough data yet\n }\n\n const msg: any = {\n id,\n type\n }\n\n if (type === MessageTypes.NEW_STREAM || type === MessageTypes.MESSAGE_INITIATOR || type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = this._buffer.sublist(offset, offset + length)\n }\n\n msgs.push(msg)\n\n this._buffer.consume(offset + length)\n this._headerInfo = null\n }\n\n return msgs\n }\n\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader (data: Uint8ArrayList): MessageHeader {\n const {\n value: h,\n offset\n } = readVarInt(data)\n const {\n value: length,\n offset: end\n } = readVarInt(data, offset)\n\n const type = h & 7\n\n // @ts-expect-error h is a number not a CODE\n if (MessageTypeNames[type] == null) {\n throw new Error(`Invalid type received: ${type}`)\n }\n\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length }\n }\n}\n\nconst MSB = 0x80\nconst REST = 0x7F\n\nfunction readVarInt (buf: Uint8ArrayList, offset: number = 0) {\n let res = 0\n let shift = 0\n let counter = offset\n let b: number\n const l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n offset = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf.get(counter++)\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n offset = counter - offset\n\n return {\n value: res,\n offset\n }\n}\n\n/**\n * Decode a chunk and yield an _array_ of decoded messages\n */\nexport async function * decode (source: Source) {\n const decoder = new Decoder()\n\n for await (const chunk of source) {\n const msgs = decoder.write(chunk)\n\n if (msgs.length > 0) {\n yield msgs\n }\n }\n}\n","import { Message, MessageTypes } from './message-types.js'\nimport type { Source, Transform } from 'it-stream-types'\n\nexport const MAX_MSG_SIZE = 1 << 20 // 1MB\n\n/**\n * Creates an iterable transform that restricts message sizes to\n * the given maximum size.\n */\nexport function restrictSize (max?: number): Transform {\n const maxSize = max ?? MAX_MSG_SIZE\n\n const checkSize = (msg: Message) => {\n if (msg.type !== MessageTypes.NEW_STREAM && msg.type !== MessageTypes.MESSAGE_INITIATOR && msg.type !== MessageTypes.MESSAGE_RECEIVER) {\n return\n }\n\n if (msg.data.byteLength > maxSize) {\n throw Object.assign(new Error('message size too large!'), { code: 'ERR_MSG_TOO_BIG' })\n }\n }\n\n return (source: Source) => {\n return (async function * restrictSize () {\n for await (const msg of source) {\n if (Array.isArray(msg)) {\n msg.forEach(checkSize)\n yield * msg\n } else {\n checkSize(msg)\n yield msg\n }\n }\n })()\n }\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { pushable } from 'it-pushable'\nimport errCode from 'err-code'\nimport { MAX_MSG_SIZE } from './restrict-size.js'\nimport { anySignal } from 'any-signal'\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { logger } from '@libp2p/logger'\nimport type { Message } from './message-types.js'\nimport type { StreamTimeline } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { MplexStream } from './mplex.js'\n\nconst log = logger('libp2p:mplex:stream')\n\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET'\nconst ERR_STREAM_ABORT = 'ERR_STREAM_ABORT'\nconst ERR_SINK_ENDED = 'ERR_SINK_ENDED'\nconst ERR_DOUBLE_SINK = 'ERR_DOUBLE_SINK'\n\nexport interface Options {\n id: number\n send: (msg: Message) => void\n name?: string\n onEnd?: (err?: Error) => void\n type?: 'initiator' | 'receiver'\n maxMsgSize?: number\n}\n\nexport function createStream (options: Options): MplexStream {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options\n\n const abortController = new AbortController()\n const resetController = new AbortController()\n const closeController = new AbortController()\n const Types = type === 'initiator' ? InitiatorMessageTypes : ReceiverMessageTypes\n const externalId = type === 'initiator' ? (`i${id}`) : `r${id}`\n const streamName = `${name == null ? id : name}`\n\n let sourceEnded = false\n let sinkEnded = false\n let sinkSunk = false\n let endErr: Error | undefined\n\n const timeline: StreamTimeline = {\n open: Date.now()\n }\n\n const onSourceEnd = (err?: Error) => {\n if (sourceEnded) {\n return\n }\n\n sourceEnded = true\n log.trace('%s stream %s source end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sinkEnded) {\n stream.stat.timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const onSinkEnd = (err?: Error) => {\n if (sinkEnded) {\n return\n }\n\n sinkEnded = true\n log.trace('%s stream %s sink end - err: %o', type, streamName, err)\n\n if (err != null && endErr == null) {\n endErr = err\n }\n\n if (sourceEnded) {\n timeline.close = Date.now()\n\n if (onEnd != null) {\n onEnd(endErr)\n }\n }\n }\n\n const stream: MplexStream = {\n // Close for both Reading and Writing\n close: () => {\n log.trace('%s stream %s close', type, streamName)\n\n stream.closeRead()\n stream.closeWrite()\n },\n\n // Close for reading\n closeRead: () => {\n log.trace('%s stream %s closeRead', type, streamName)\n\n if (sourceEnded) {\n return\n }\n\n stream.source.end()\n },\n\n // Close for writing\n closeWrite: () => {\n log.trace('%s stream %s closeWrite', type, streamName)\n\n if (sinkEnded) {\n return\n }\n\n closeController.abort()\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n // Close for reading and writing (local error)\n abort: (err: Error) => {\n log.trace('%s stream %s abort', type, streamName, err)\n // End the source with the passed error\n stream.source.end(err)\n abortController.abort()\n onSinkEnd(err)\n },\n\n // Close immediately for reading and writing (remote error)\n reset: () => {\n const err = errCode(new Error('stream reset'), ERR_STREAM_RESET)\n resetController.abort()\n stream.source.end(err)\n onSinkEnd(err)\n },\n\n sink: async (source: Source) => {\n if (sinkSunk) {\n throw errCode(new Error('sink already called on stream'), ERR_DOUBLE_SINK)\n }\n\n sinkSunk = true\n\n if (sinkEnded) {\n throw errCode(new Error('stream closed for writing'), ERR_SINK_ENDED)\n }\n\n source = abortableSource(source, anySignal([\n abortController.signal,\n resetController.signal,\n closeController.signal\n ]))\n\n try {\n if (type === 'initiator') { // If initiator, open a new stream\n send({ id, type: InitiatorMessageTypes.NEW_STREAM, data: new Uint8ArrayList(uint8ArrayFromString(streamName)) })\n }\n\n const uint8ArrayList = new Uint8ArrayList()\n\n for await (const data of source) {\n uint8ArrayList.append(data)\n\n while (uint8ArrayList.length !== 0) {\n if (uint8ArrayList.length <= maxMsgSize) {\n send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist() })\n uint8ArrayList.consume(uint8ArrayList.length)\n break\n }\n\n const toSend = uint8ArrayList.length - maxMsgSize\n send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist(0, toSend) })\n uint8ArrayList.consume(toSend)\n }\n }\n } catch (err: any) {\n if (err.type === 'aborted' && err.message === 'The operation was aborted') {\n if (closeController.signal.aborted) {\n return\n }\n\n if (resetController.signal.aborted) {\n err.message = 'stream reset'\n err.code = ERR_STREAM_RESET\n }\n\n if (abortController.signal.aborted) {\n err.message = 'stream aborted'\n err.code = ERR_STREAM_ABORT\n }\n }\n\n // Send no more data if this stream was remotely reset\n if (err.code === ERR_STREAM_RESET) {\n log.trace('%s stream %s reset', type, name)\n } else {\n log.trace('%s stream %s error', type, name, err)\n try {\n send({ id, type: Types.RESET })\n } catch (err) {\n log.trace('%s stream %s error sending reset', type, name, err)\n }\n }\n\n stream.source.end(err)\n onSinkEnd(err)\n return\n }\n\n try {\n send({ id, type: Types.CLOSE })\n } catch (err) {\n log.trace('%s stream %s error sending close', type, name, err)\n }\n\n onSinkEnd()\n },\n\n source: pushable({\n onEnd: onSourceEnd\n }),\n\n stat: {\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n timeline\n },\n\n metadata: {},\n\n id: externalId\n }\n\n return stream\n}\n","import type { ComponentMetricsTracker } from '@libp2p/interface-metrics'\n\nexport interface TrackedMapInit {\n metrics: ComponentMetricsTracker\n system?: string\n component: string\n metric: string\n}\n\nclass TrackedMap extends Map {\n private readonly system: string\n private readonly component: string\n private readonly metric: string\n private readonly metrics: ComponentMetricsTracker\n\n constructor (init: TrackedMapInit) {\n super()\n\n const { system, component, metric, metrics } = init\n this.system = system ?? 'libp2p'\n this.component = component\n this.metric = metric\n this.metrics = metrics\n\n this.updateComponentMetric()\n }\n\n set (key: K, value: V) {\n super.set(key, value)\n this.updateComponentMetric()\n return this\n }\n\n delete (key: K) {\n const deleted = super.delete(key)\n this.updateComponentMetric()\n return deleted\n }\n\n clear () {\n super.clear()\n this.updateComponentMetric()\n }\n\n private updateComponentMetric () {\n this.metrics.updateComponentMetric({\n system: this.system,\n component: this.component,\n metric: this.metric,\n value: this.size\n })\n }\n}\n\nexport interface CreateTrackedMapOptions {\n metrics?: ComponentMetricsTracker\n system?: string\n component: string\n metric: string\n}\n\nexport function trackedMap (config: CreateTrackedMapOptions): Map {\n const { system, component, metric, metrics } = config\n let map: Map\n\n if (metrics != null) {\n map = new TrackedMap({ system, component, metric, metrics })\n } else {\n map = new Map()\n }\n\n return map\n}\n","import { pipe } from 'it-pipe'\nimport { Pushable, pushableV } from 'it-pushable'\nimport { abortableSource } from 'abortable-iterator'\nimport { encode } from './encode.js'\nimport { decode } from './decode.js'\nimport { restrictSize } from './restrict-size.js'\nimport { MessageTypes, MessageTypeNames, Message } from './message-types.js'\nimport { createStream } from './stream.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport type { Components } from '@libp2p/components'\nimport type { Sink } from 'it-stream-types'\nimport type { StreamMuxer, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { MplexInit } from './index.js'\nimport anySignal from 'any-signal'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:mplex')\n\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4 // 4MB\n\nfunction printMessage (msg: Message) {\n const output: any = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n }\n\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray())\n }\n\n if (msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16')\n }\n\n return output\n}\n\nexport interface MplexStream extends Stream {\n source: Pushable\n}\n\ninterface MplexStreamMuxerInit extends MplexInit, StreamMuxerInit {}\n\nexport class MplexStreamMuxer implements StreamMuxer {\n public protocol = '/mplex/6.7.0'\n\n public sink: Sink\n public source: AsyncIterable\n\n private _streamId: number\n private readonly _streams: { initiators: Map, receivers: Map }\n private readonly _init: MplexStreamMuxerInit\n private readonly _source: { push: (val: Message) => void, end: (err?: Error) => void }\n private readonly closeController: AbortController\n\n constructor (components: Components, init?: MplexStreamMuxerInit) {\n init = init ?? {}\n\n this._streamId = 0\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: trackedMap({ metrics: components.getMetrics(), component: 'mplex', metric: 'initiatorStreams' }),\n /**\n * Stream to ids map\n */\n receivers: trackedMap({ metrics: components.getMetrics(), component: 'mplex', metric: 'receiverStreams' })\n }\n this._init = init\n\n /**\n * An iterable sink\n */\n this.sink = this._createSink()\n\n /**\n * An iterable source\n */\n const source = this._createSource()\n this._source = source\n this.source = source\n\n /**\n * Close controller\n */\n this.closeController = new AbortController()\n }\n\n init (components: Components) {}\n\n /**\n * Returns a Map of streams and their ids\n */\n get streams () {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams: Stream[] = []\n this._streams.initiators.forEach(stream => {\n streams.push(stream)\n })\n this._streams.receivers.forEach(stream => {\n streams.push(stream)\n })\n return streams\n }\n\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream (name?: string): Stream {\n if (this.closeController.signal.aborted) {\n throw new Error('Muxer already closed')\n }\n const id = this._streamId++\n name = name == null ? id.toString() : name.toString()\n const registry = this._streams.initiators\n return this._newStream({ id, name, type: 'initiator', registry })\n }\n\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n close (err?: Error | undefined): void {\n if (this.closeController.signal.aborted) return\n\n if (err != null) {\n this.streams.forEach(s => s.abort(err))\n } else {\n this.streams.forEach(s => s.close())\n }\n this.closeController.abort()\n }\n\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream (options: { id: number, name: string }) {\n const { id, name } = options\n const registry = this._streams.receivers\n return this._newStream({ id, name, type: 'receiver', registry })\n }\n\n _newStream (options: { id: number, name: string, type: 'initiator' | 'receiver', registry: Map }) {\n const { id, name, type, registry } = options\n\n log('new %s stream %s %s', type, id, name)\n\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw errCode(new Error('Too many outbound streams open'), 'ERR_TOO_MANY_OUTBOUND_STREAMS')\n }\n\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`)\n }\n\n const send = (msg: Message) => {\n if (log.enabled) {\n log.trace('%s stream %s send', type, id, printMessage(msg))\n }\n\n this._source.push(msg)\n }\n\n const onEnd = () => {\n log('%s stream %s ended', type, id, name)\n registry.delete(id)\n\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream)\n }\n }\n\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize })\n registry.set(id, stream)\n return stream\n }\n\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink () {\n const sink: Sink = async source => {\n // see: https://github.com/jacobheun/any-signal/pull/18\n const abortSignals = [this.closeController.signal]\n if (this._init.signal != null) {\n abortSignals.push(this._init.signal)\n }\n source = abortableSource(source, anySignal(abortSignals))\n\n try {\n await pipe(\n source,\n decode,\n restrictSize(this._init.maxMsgSize),\n async source => {\n for await (const msg of source) {\n this._handleIncoming(msg)\n }\n }\n )\n\n this._source.end()\n } catch (err: any) {\n log('error in sink', err)\n this._source.end(err) // End the source with an error\n }\n }\n\n return sink\n }\n\n /**\n * Creates a source that restricts outgoing message sizes\n * and varint encodes them\n */\n _createSource () {\n const onEnd = (err?: Error) => {\n this.close(err)\n }\n const source = pushableV({\n objectMode: true,\n onEnd\n })\n\n return Object.assign(encode(source), {\n push: source.push,\n end: source.end,\n return: source.return\n })\n }\n\n _handleIncoming (message: Message) {\n const { id, type } = message\n\n if (log.enabled) {\n log.trace('incoming message', printMessage(message))\n }\n\n // Create a new stream?\n if (message.type === MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n log.error('Too many inbound streams open')\n\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n\n this._source.push({\n id,\n type: MessageTypes.RESET_RECEIVER\n })\n\n return\n }\n\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) })\n\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream)\n }\n\n return\n }\n\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers\n const stream = list.get(id)\n\n if (stream == null) {\n log('missing stream %s', id)\n\n return\n }\n\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE\n\n switch (type) {\n case MessageTypes.MESSAGE_INITIATOR:\n case MessageTypes.MESSAGE_RECEIVER:\n if (stream.source.readableLength > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === MessageTypes.MESSAGE_INITIATOR ? MessageTypes.RESET_RECEIVER : MessageTypes.RESET_INITIATOR\n })\n\n // Inform the stream consumer they are not fast enough\n const error = errCode(new Error('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers'), 'ERR_STREAM_INPUT_BUFFER_FULL')\n stream.abort(error)\n\n return\n }\n\n // We got data from the remote, push it into our local stream\n stream.source.push(message.data)\n break\n case MessageTypes.CLOSE_INITIATOR:\n case MessageTypes.CLOSE_RECEIVER:\n // We should expect no more data from the remote, stop reading\n stream.closeRead()\n break\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // Stop reading and writing to the stream immediately\n stream.reset()\n break\n default:\n log('unknown message type %s', type)\n }\n }\n}\n","import { Components, Initializable } from '@libp2p/components'\nimport type { StreamMuxer, StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface-stream-muxer'\nimport { MplexStreamMuxer } from './mplex.js'\n\nexport interface MplexInit {\n /**\n * The maximum size of message that can be sent in one go in bytes.\n * Messages larger than this will be split into multiple smaller\n * messages.\n */\n maxMsgSize?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw.\n */\n maxInboundStreams?: number\n\n /**\n * The maximum number of multiplexed streams that can be open at any\n * one time. An attempt to open more than this will throw.\n */\n maxOutboundStreams?: number\n\n /**\n * Incoming stream messages are buffered until processed by the stream\n * handler. If the buffer reaches this size in bytes the stream will\n * be reset.\n */\n maxStreamBufferSize?: number\n}\n\nexport class Mplex implements StreamMuxerFactory, Initializable {\n public protocol = '/mplex/6.7.0'\n private readonly _init: MplexInit\n private components: Components = new Components()\n\n constructor (init: MplexInit = {}) {\n this._init = init\n }\n\n init (components: Components): void {\n this.components = components\n }\n\n createStreamMuxer (init: StreamMuxerInit = {}): StreamMuxer {\n return new MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n })\n }\n}\n","/* eslint-env browser */\n\nexport default WebSocket\n","\nimport { EventIterator } from 'event-iterator'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport type { WebSocket, ErrorEvent, MessageEvent } from 'ws'\n\n// copied from github.com/feross/buffer\n// Some ArrayBuffers are not passing the instanceof check, so we need to do a bit more work :(\nfunction isArrayBuffer (obj: any): obj is ArrayBuffer {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number')\n}\n\nexport interface ConnectedSource extends AsyncIterable {\n connected: () => Promise\n}\n\nexport default (socket: WebSocket): ConnectedSource => {\n socket.binaryType = 'arraybuffer'\n\n const connected = async () => await new Promise((resolve, reject) => {\n if (isConnected) {\n return resolve()\n }\n if (connError != null) {\n return reject(connError)\n }\n\n const cleanUp = (cont: () => void) => {\n socket.removeEventListener('open', onOpen)\n socket.removeEventListener('error', onError)\n cont()\n }\n\n const onOpen = () => cleanUp(resolve)\n const onError = (event: ErrorEvent) => {\n cleanUp(() => reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)))\n }\n\n socket.addEventListener('open', onOpen)\n socket.addEventListener('error', onError)\n })\n\n const source = (async function * () {\n const messages = new EventIterator(\n ({ push, stop, fail }) => {\n const onMessage = (event: MessageEvent) => {\n let data: Uint8Array | null = null\n\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data)\n }\n\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data)\n }\n\n if (event.data instanceof Uint8Array) {\n data = event.data\n }\n\n if (data == null) {\n return\n }\n\n push(data)\n }\n const onError = (event: ErrorEvent) => fail(event.error ?? new Error('Socket error'))\n\n socket.addEventListener('message', onMessage)\n socket.addEventListener('error', onError)\n socket.addEventListener('close', stop)\n\n return () => {\n socket.removeEventListener('message', onMessage)\n socket.removeEventListener('error', onError)\n socket.removeEventListener('close', stop)\n }\n },\n { highWaterMark: Infinity }\n )\n\n await connected()\n\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk\n }\n }())\n\n let isConnected = socket.readyState === 1\n let connError: Error | null\n\n socket.addEventListener('open', () => {\n isConnected = true\n connError = null\n })\n\n socket.addEventListener('close', () => {\n isConnected = false\n connError = null\n })\n\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)\n }\n })\n\n return Object.assign(source, {\n connected\n })\n}\n","import type { ErrorEvent, WebSocket } from 'ws'\n\nexport default (socket: WebSocket) => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed')\n }\n\n // if open, return\n if (socket.readyState === 1) {\n return\n }\n\n return new Promise((resolve, reject) => {\n function cleanup () {\n socket.removeEventListener('open', handleOpen)\n socket.removeEventListener('error', handleErr)\n }\n\n function handleOpen () {\n cleanup()\n resolve()\n }\n\n function handleErr (event: ErrorEvent) {\n cleanup()\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`))\n }\n\n socket.addEventListener('open', handleOpen)\n socket.addEventListener('error', handleErr)\n })\n}\n","import ready from './ready.js'\nimport type { WebSocket } from 'ws'\nimport type { Sink } from 'it-stream-types'\n\nexport interface SinkOptions {\n closeOnEnd?: boolean\n}\n\nexport default (socket: WebSocket, options: SinkOptions) => {\n options = options ?? {}\n options.closeOnEnd = options.closeOnEnd !== false\n\n const sink: Sink> = async source => {\n for await (const data of source) {\n try {\n await ready(socket)\n } catch (err: any) {\n if (err.message === 'socket closed') break\n throw err\n }\n\n socket.send(data)\n }\n\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n return await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve()\n } else {\n const err = Object.assign(new Error('ws error'), { event })\n reject(err)\n }\n })\n\n setTimeout(() => socket.close())\n })\n }\n }\n\n return sink\n}\n","import source from './source.js'\nimport sink from './sink.js'\nimport type WebSocket from './web-socket.js'\nimport type { SinkOptions } from './sink.js'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface DuplexWebSocket extends Duplex> {\n connected: () => Promise\n localAddress?: string\n localPort?: number\n remoteAddress: string\n remotePort: number\n close: () => Promise\n destroy: () => void\n socket: WebSocket\n}\n\nexport interface DuplexWebSocketOptions extends SinkOptions {\n remoteAddress?: string\n remotePort?: number\n}\n\nexport default (socket: WebSocket, options?: DuplexWebSocketOptions): DuplexWebSocket => {\n options = options ?? {}\n\n const connectedSource = source(socket)\n let remoteAddress: string | undefined = options.remoteAddress\n let remotePort: number | undefined = options.remotePort\n\n if (socket.url != null) {\n // only client->server sockets have urls, server->client connections do not\n try {\n const url = new URL(socket.url)\n remoteAddress = url.hostname\n remotePort = parseInt(url.port, 10)\n } catch {}\n }\n\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port')\n }\n\n const duplex: DuplexWebSocket = {\n sink: sink(socket, options),\n source: connectedSource,\n connected: async () => await connectedSource.connected(),\n close: async () => {\n if (socket.readyState === socket.CONNECTING || socket.readyState === socket.OPEN) {\n await new Promise((resolve) => {\n socket.addEventListener('close', () => {\n resolve()\n })\n socket.close()\n })\n }\n },\n destroy: () => {\n if (socket.terminate != null) {\n socket.terminate()\n } else {\n socket.close()\n }\n },\n remoteAddress,\n remotePort,\n socket\n }\n\n return duplex\n}\n","import { relative } from 'iso-url'\n\nconst map = { http: 'ws', https: 'wss' }\nconst def = 'ws'\n\nexport default (url: string, location: string | Partial) => relative(url, location, map, def)\n","// load websocket library if we are not in the browser\nimport WebSocket from './web-socket.js'\nimport duplex from './duplex.js'\nimport wsurl from './ws-url.js'\nimport type { ClientOptions } from 'ws'\nimport type { DuplexWebSocket } from './duplex.js'\nimport type { SinkOptions } from './sink.js'\n\nexport interface WebSocketOptions extends SinkOptions {\n websocket?: ClientOptions\n}\n\nexport function connect (addr: string, opts?: WebSocketOptions): DuplexWebSocket {\n const location = typeof window === 'undefined' ? '' : window.location\n opts = opts ?? {}\n\n const url = wsurl(addr, location.toString())\n const socket = new WebSocket(url, opts.websocket)\n\n return duplex(socket, opts)\n}\n","import { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MultiaddrToUriOpts {\n assumeHttp?: boolean\n}\n\ninterface Reducer { (str: string, content: string, i: number, parts: Part[], opts?: MultiaddrToUriOpts): string }\n\nconst reduceValue: Reducer = (_, v) => v\nconst tcpUri = (str: string, port: string, parts: Part[], opts?: MultiaddrToUriOpts) => {\n // return tcp when explicitly requested\n if ((opts != null) && opts.assumeHttp === false) return `tcp://${str}:${port}`\n // check if tcp is the last protocol in multiaddr\n let protocol = 'tcp'\n let explicitPort = `:${port}`\n const last = parts[parts.length - 1]\n if (last.protocol === 'tcp') {\n // assume http and produce clean urls\n protocol = port === '443' ? 'https' : 'http'\n explicitPort = port === '443' || port === '80' ? '' : explicitPort\n }\n return `${protocol}://${str}${explicitPort}`\n}\n\nconst Reducers: Record = {\n ip4: reduceValue,\n ip6: (str, content, i, parts) => (\n parts.length === 1 && parts[0].protocol === 'ip6'\n ? content\n : `[${content}]`\n ),\n tcp: (str, content, i, parts, opts) => (\n parts.some(p => ['http', 'https', 'ws', 'wss'].includes(p.protocol))\n ? `${str}:${content}`\n : tcpUri(str, content, parts, opts)\n ),\n udp: (str, content) => `udp://${str}:${content}`,\n dnsaddr: reduceValue,\n dns4: reduceValue,\n dns6: reduceValue,\n ipfs: (str, content) => `${str}/ipfs/${content}`,\n p2p: (str, content) => `${str}/p2p/${content}`,\n http: str => `http://${str}`,\n https: str => `https://${str}`,\n ws: str => `ws://${str}`,\n wss: str => `wss://${str}`,\n 'p2p-websocket-star': str => `${str}/p2p-websocket-star`,\n 'p2p-webrtc-star': str => `${str}/p2p-webrtc-star`,\n 'p2p-webrtc-direct': str => `${str}/p2p-webrtc-direct`\n}\n\ninterface Part {\n protocol: string\n content: string\n}\n\nexport function multiaddrToUri (multiaddr: Multiaddr | string | Uint8Array, opts?: MultiaddrToUriOpts) {\n const ma = new Multiaddr(multiaddr)\n const parts = multiaddr.toString().split('/').slice(1)\n return ma\n .tuples()\n .map(tuple => ({\n protocol: parts.shift() ?? '',\n content: (tuple[1] != null) ? parts.shift() ?? '' : ''\n }))\n .reduce((str: string, part: Part, i: number, parts: Part[]) => {\n const reduce = Reducers[part.protocol]\n if (reduce == null) {\n throw new Error(`Unsupported protocol ${part.protocol}`)\n }\n return reduce(str, part.content, i, parts, opts)\n }, '')\n}\n","\nexport class AbortError extends Error {\n public readonly code: string\n public readonly type: string\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.code = AbortError.code\n this.type = AbortError.type\n }\n\n static get code () {\n return 'ABORT_ERR'\n }\n\n static get type () {\n return 'aborted'\n }\n}\n","import detectElectron from 'is-electron'\n\nexport const isEnvWithDom = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\nexport const isElectron = detectElectron()\n\n/**\n * Detects browser main thread **NOT** web worker or service worker\n */\nexport const isBrowser = isEnvWithDom && !isElectron\nexport const isElectronMain = isElectron && !isEnvWithDom\nexport const isElectronRenderer = isElectron && isEnvWithDom\nexport const isNode = typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !isElectron\n// @ts-ignore\n// eslint-disable-next-line no-undef\nexport const isWebWorker = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\n\n// defeat bundlers replacing process.env.NODE_ENV with \"development\" or whatever\nexport const isTest = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env['NODE' + (() => '_')() + 'ENV'] === 'test'\nexport const isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst cancelablePromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst errorMessage = typeof message === 'string' ? message : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = message instanceof Error ? message : new TimeoutError(errorMessage);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t} finally {\n\t\t\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { CLOSE_TIMEOUT } from './constants.js'\nimport pTimeout from 'p-timeout'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\n\nconst log = logger('libp2p:websockets:socket')\n\nexport interface SocketToConnOptions extends AbortOptions {\n localAddr?: Multiaddr\n}\n\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn (stream: DuplexWebSocket, remoteAddr: Multiaddr, options?: SocketToConnOptions): MultiaddrConnection {\n options = options ?? {}\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if ((options?.signal) != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await stream.sink(source)\n } catch (err: any) {\n if (err.type !== 'aborted') {\n log.error(err)\n }\n }\n },\n\n source: (options.signal != null) ? abortableSource(stream.source, options.signal) : stream.source,\n\n remoteAddr,\n\n timeline: { open: Date.now() },\n\n async close () {\n const start = Date.now()\n\n try {\n await pTimeout(stream.close(), {\n milliseconds: CLOSE_TIMEOUT\n })\n } catch (err) {\n const { host, port } = maConn.remoteAddr.toOptions()\n log('timeout closing stream to %s:%s after %dms, destroying it manually',\n host, port, Date.now() - start)\n\n stream.destroy()\n } finally {\n maConn.timeline.close = Date.now()\n }\n }\n }\n\n stream.socket.once != null && stream.socket.once('close', () => { // eslint-disable-line @typescript-eslint/prefer-optional-chain\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n })\n\n return maConn\n}\n","// p2p multi-address code\nexport const CODE_P2P = 421\nexport const CODE_CIRCUIT = 290\n\nexport const CODE_TCP = 6\nexport const CODE_WS = 477\nexport const CODE_WSS = 478\n\n// Time to wait for a connection to close gracefully before destroying it manually\nexport const CLOSE_TIMEOUT = 2000\n","import { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface MatchesFunction { (a: string | Uint8Array | Multiaddr): boolean }\nexport interface PartialMatchesFunction { (protos: string[]): boolean | string[] | null }\n\nexport interface Mafmt {\n toString: () => string\n input?: Array<(Mafmt | (() => Mafmt))>\n matches: MatchesFunction\n partialMatch: PartialMatchesFunction\n}\n\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4')\nexport const DNS6 = base('dns6')\nexport const DNSADDR = base('dnsaddr')\nexport const DNS = or(\n base('dns'),\n DNSADDR,\n DNS4,\n DNS6\n)\n\nexport const IP = or(base('ip4'), base('ip6'))\nexport const TCP = or(\n and(IP, base('tcp')),\n and(DNS, base('tcp'))\n)\nexport const UDP = and(IP, base('udp'))\nexport const UTP = and(UDP, base('utp'))\n\nexport const QUIC = and(UDP, base('quic'))\n\nexport const WebSockets = or(\n and(TCP, base('ws')),\n and(DNS, base('ws'))\n)\n\nexport const WebSocketsSecure = or(\n and(TCP, base('wss')),\n and(DNS, base('wss'))\n)\n\nexport const HTTP = or(\n and(TCP, base('http')),\n and(IP, base('http')),\n and(DNS, base('http'))\n)\n\nexport const HTTPS = or(\n and(TCP, base('https')),\n and(IP, base('https')),\n and(DNS, base('https'))\n)\n\nexport const WebRTCStar = or(\n and(WebSockets, base('p2p-webrtc-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')),\n and(WebSockets, base('p2p-webrtc-star')),\n and(WebSocketsSecure, base('p2p-webrtc-star'))\n)\n\nexport const WebSocketStar = or(\n and(WebSockets, base('p2p-websocket-star'), base('p2p')),\n and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')),\n and(WebSockets, base('p2p-websocket-star')),\n and(WebSocketsSecure, base('p2p-websocket-star'))\n)\n\nexport const WebRTCDirect = or(\n and(HTTP, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTPS, base('p2p-webrtc-direct'), base('p2p')),\n and(HTTP, base('p2p-webrtc-direct')),\n and(HTTPS, base('p2p-webrtc-direct'))\n)\n\nexport const Reliable = or(\n WebSockets,\n WebSocketsSecure,\n HTTP,\n HTTPS,\n WebRTCStar,\n WebRTCDirect,\n TCP,\n UTP,\n QUIC,\n DNS\n)\n\n// Unlike ws-star, stardust can run over any transport thus removing the requirement for websockets (but don't even think about running a stardust server over webrtc-star ;) )\nexport const Stardust = or(\n and(Reliable, base('p2p-stardust'), base('p2p')),\n and(Reliable, base('p2p-stardust'))\n)\n\nconst _P2P = or(\n and(Reliable, base('p2p')),\n WebRTCStar,\n WebRTCDirect,\n base('p2p')\n)\n\nconst _Circuit = or(\n and(_P2P, base('p2p-circuit'), _P2P),\n and(_P2P, base('p2p-circuit')),\n and(base('p2p-circuit'), _P2P),\n and(Reliable, base('p2p-circuit')),\n and(base('p2p-circuit'), Reliable),\n base('p2p-circuit')\n)\n\nconst CircuitRecursive = () => or(\n and(_Circuit, CircuitRecursive),\n _Circuit\n)\n\nexport const Circuit = CircuitRecursive()\n\nexport const P2P = or(\n and(Circuit, _P2P, Circuit),\n and(_P2P, Circuit),\n and(Circuit, _P2P),\n Circuit,\n _P2P\n)\n\nexport const IPFS = P2P\n\n/*\n * Validation funcs\n */\n\nfunction makeMatchesFunction (partialMatch: PartialMatchesFunction) {\n function matches (a: string | Uint8Array | Multiaddr): boolean {\n let ma\n\n try {\n ma = new Multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's propably not matching as well so return false\n }\n\n const out = partialMatch(ma.protoNames())\n if (out === null) {\n return false\n }\n\n if (out === true || out === false) {\n return out\n }\n\n return out.length === 0\n }\n\n return matches\n}\n\nfunction and (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n if (a.length < args.length) {\n return null\n }\n\n let out: boolean | string[] | null = a\n\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n\n if (Array.isArray(out)) {\n a = out\n }\n\n if (out === null) {\n return true\n }\n\n return false\n })\n\n return out\n }\n\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n}\n\nfunction or (...args: Array Mafmt)>): Mafmt {\n function partialMatch (a: string[]): boolean | string[] | null {\n let out = null\n args.some((arg) => {\n const res = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a)\n if (res != null) {\n out = res\n return true\n }\n return false\n })\n\n return out\n }\n\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }' },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch: partialMatch\n }\n\n return result\n}\n\nfunction base (n: string): Mafmt {\n const name = n\n\n function matches (a: string | Uint8Array | Multiaddr) {\n let ma: Multiaddr\n\n try {\n ma = new Multiaddr(a)\n } catch (err: any) { // catch error\n return false // also if it's invalid it's probably not matching as well so return false\n }\n\n const pnames = ma.protoNames()\n if (pnames.length === 1 && pnames[0] === name) {\n return true\n }\n return false\n }\n\n function partialMatch (protos: string[]): boolean | string[] | null {\n if (protos.length === 0) {\n return null\n }\n\n if (protos[0] === name) {\n return protos.slice(1)\n }\n return null\n }\n\n return {\n toString: function () { return name },\n matches: matches,\n partialMatch: partialMatch\n }\n}\n","import * as mafmt from '@multiformats/mafmt'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport {\n CODE_CIRCUIT,\n CODE_P2P,\n CODE_TCP,\n CODE_WS,\n CODE_WSS\n} from './constants.js'\n\nexport function all (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSockets.matches(testMa) ||\n mafmt.WebSocketsSecure.matches(testMa)\n })\n}\n\nexport function dnsWss (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n\nexport function dnsWsOrWss (multiaddrs: Multiaddr[]) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false\n }\n\n const testMa = ma.decapsulateCode(CODE_P2P)\n\n // WS\n if (mafmt.WebSockets.matches(testMa)) {\n return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS))\n }\n\n // WSS\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS))\n })\n}\n","import type { AbortOptions } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\n\nexport const symbol = Symbol.for('@libp2p/transport')\n\nexport interface ConnectionHandler { (connection: Connection): void }\n\nexport interface MultiaddrFilter { (multiaddrs: Multiaddr[]): Multiaddr[] }\n\nexport interface CreateListenerOptions {\n handler?: ConnectionHandler\n upgrader: Upgrader\n}\n\nexport interface DialOptions extends AbortOptions {\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport is understood as something that offers a dial and listen interface to establish connections.\n */\nexport interface Transport {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [symbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial: (ma: Multiaddr, options: DialOptions) => Promise\n\n /**\n * Create transport listeners.\n */\n createListener: (options: CreateListenerOptions) => Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid addresses for the transport\n */\n filter: MultiaddrFilter\n}\n\nexport interface ListenerEvents {\n 'connection': CustomEvent\n 'listening': CustomEvent\n 'error': CustomEvent\n 'close': CustomEvent\n}\n\nexport interface Listener extends EventEmitter {\n /**\n * Start a listener\n */\n listen: (multiaddr: Multiaddr) => Promise\n /**\n * Get listen addresses\n */\n getAddrs: () => Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise}\n */\n close: () => Promise\n}\n\nexport interface UpgraderEvents {\n 'connection': CustomEvent\n 'connectionEnd': CustomEvent\n}\n\nexport interface Upgrader extends EventEmitter {\n /**\n * Upgrades an outbound connection on `transport.dial`.\n */\n upgradeOutbound: (maConn: MultiaddrConnection) => Promise\n\n /**\n * Upgrades an inbound connection on transport listener.\n */\n upgradeInbound: (maConn: MultiaddrConnection) => Promise\n}\n\nexport interface ProtocolHandler {\n (stream: Duplex, connection: Connection): void\n}\n\nexport function isTransport (other: any): other is Transport {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface TransportManagerEvents {\n 'listener:listening': CustomEvent\n 'listener:close': CustomEvent\n}\n\nexport interface TransportManager extends EventEmitter {\n add: (transport: Transport) => void\n dial: (ma: Multiaddr, options?: any) => Promise\n getAddrs: () => Multiaddr[]\n getTransports: () => Transport[]\n transportForMultiaddr: (ma: Multiaddr) => Transport | undefined\n listen: (addrs: Multiaddr[]) => Promise\n remove: (key: string) => Promise\n removeAll: () => Promise\n}\n","import { connect, WebSocketOptions } from 'it-ws/client'\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri'\nimport { AbortError } from '@libp2p/interfaces/errors'\nimport pDefer from 'p-defer'\nimport { logger } from '@libp2p/logger'\nimport { isBrowser, isWebWorker } from 'wherearewe'\nimport { createListener } from './listener.js'\nimport { socketToMaConn } from './socket-to-conn.js'\nimport * as filters from './filters.js'\nimport { Transport, MultiaddrFilter, symbol, CreateListenerOptions, DialOptions } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { DuplexWebSocket } from 'it-ws/duplex'\nimport type { ClientOptions } from 'ws'\nimport type { Server } from 'http'\n\nconst log = logger('libp2p:websockets')\n\nexport interface WebSocketsInit extends AbortOptions, WebSocketOptions {\n filter?: MultiaddrFilter\n websocket?: ClientOptions\n server?: Server\n}\n\nexport class WebSockets implements Transport {\n private readonly init?: WebSocketsInit\n\n constructor (init?: WebSocketsInit) {\n this.init = init\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/websockets'\n }\n\n get [symbol] (): true {\n return true\n }\n\n async dial (ma: Multiaddr, options: DialOptions): Promise {\n log('dialing %s', ma)\n options = options ?? {}\n\n const socket = await this._connect(ma, options)\n const maConn = socketToMaConn(socket, ma)\n log('new outbound connection %s', maConn.remoteAddr)\n\n const conn = await options.upgrader.upgradeOutbound(maConn)\n log('outbound connection %s upgraded', maConn.remoteAddr)\n return conn\n }\n\n async _connect (ma: Multiaddr, options: AbortOptions): Promise {\n if (options?.signal?.aborted === true) {\n throw new AbortError()\n }\n const cOpts = ma.toOptions()\n log('dialing %s:%s', cOpts.host, cOpts.port)\n\n const errorPromise = pDefer()\n const errfn = (err: any) => {\n log.error('connection error:', err)\n\n errorPromise.reject(err)\n }\n\n const rawSocket = connect(toUri(ma), this.init)\n\n if (rawSocket.socket.on != null) {\n rawSocket.socket.on('error', errfn)\n } else {\n rawSocket.socket.onerror = errfn\n }\n\n if (options.signal == null) {\n await Promise.race([rawSocket.connected(), errorPromise.promise])\n\n log('connected %s', ma)\n return rawSocket\n }\n\n // Allow abort via signal during connect\n let onAbort\n const abort = new Promise((resolve, reject) => {\n onAbort = () => {\n reject(new AbortError())\n // FIXME: https://github.com/libp2p/js-libp2p-websockets/issues/121\n setTimeout(() => {\n rawSocket.close().catch(err => {\n log.error('error closing raw socket', err)\n })\n })\n }\n\n // Already aborted?\n if (options?.signal?.aborted === true) {\n return onAbort()\n }\n\n options?.signal?.addEventListener('abort', onAbort)\n })\n\n try {\n await Promise.race([abort, errorPromise.promise, rawSocket.connected()])\n } finally {\n if (onAbort != null) {\n options?.signal?.removeEventListener('abort', onAbort)\n }\n }\n\n log('connected %s', ma)\n return rawSocket\n }\n\n /**\n * Creates a Websockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener (options: CreateListenerOptions) {\n return createListener({ ...this.init, ...options })\n }\n\n /**\n * Takes a list of `Multiaddr`s and returns only valid Websockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n filter (multiaddrs: Multiaddr[]) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs)\n }\n\n // Browser\n if (isBrowser || isWebWorker) {\n return filters.dnsWss(multiaddrs)\n }\n\n return filters.all(multiaddrs)\n }\n}\n","\nexport function createListener () {\n throw new Error('WebSocket Servers can not be created in the browser!')\n}\n","\nimport all from 'it-all'\n\n/**\n * Collect all values from the iterable and sort them using\n * the passed sorter function\n *\n * @template T\n * @param {AsyncIterable | Iterable} iterable\n * @param {(a: T, b: T) => -1 | 0 | 1} sorter\n * @returns {AsyncIterable}\n */\nexport const sortAll = (iterable, sorter) => {\n return (async function * () {\n const values = await all(iterable)\n yield * values.sort(sorter)\n })()\n}\n\n/**\n * @param {string} s\n * @param {string} r\n */\nexport const replaceStartWith = (s, r) => {\n const matcher = new RegExp('^' + r)\n return s.replace(matcher, '')\n}\n","\nimport { nanoid } from 'nanoid'\nimport { SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/f98719ea086343f7b71f32ea9d9d521d')\n * ```\n */\n static random (): Key {\n return new Key(nanoid().replace(/-/g, ''))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n *\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n","import { urlAlphabet } from './url-alphabet/index.js'\nlet random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import { BaseDatastore } from './base.js'\nimport { Key } from 'interface-datastore/key'\nimport * as Errors from './errors.js'\n\n/**\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-store').Options} Options\n */\n\n/**\n * @class MemoryDatastore\n * @implements {Datastore}\n */\nexport class MemoryDatastore extends BaseDatastore {\n constructor () {\n super()\n\n /** @type {Record} */\n this.data = {}\n }\n\n open () {\n return Promise.resolve()\n }\n\n close () {\n return Promise.resolve()\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n */\n async put (key, val) { // eslint-disable-line require-await\n this.data[key.toString()] = val\n }\n\n /**\n * @param {Key} key\n */\n async get (key) {\n const exists = await this.has(key)\n if (!exists) throw Errors.notFoundError()\n return this.data[key.toString()]\n }\n\n /**\n * @param {Key} key\n */\n async has (key) { // eslint-disable-line require-await\n return this.data[key.toString()] !== undefined\n }\n\n /**\n * @param {Key} key\n */\n async delete (key) { // eslint-disable-line require-await\n delete this.data[key.toString()]\n }\n\n async * _all () {\n yield * Object.entries(this.data)\n .map(([key, value]) => ({ key: new Key(key), value }))\n }\n\n async * _allKeys () {\n yield * Object.entries(this.data)\n .map(([key]) => new Key(key))\n }\n}\n","import { sortAll } from './utils.js'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport take from 'it-take'\n\n/**\n * @typedef {import('interface-store').Options} Options\n * @typedef {import('interface-datastore').Key} Key\n * @typedef {import('interface-datastore').Pair} Pair\n * @typedef {import('interface-datastore').Datastore} Datastore\n * @typedef {import('interface-datastore').Query} Query\n * @typedef {import('interface-datastore').KeyQuery} KeyQuery\n * @typedef {import('interface-datastore').Batch} Batch\n */\n\n/**\n * @template O\n * @typedef {import('interface-store').AwaitIterable} AwaitIterable\n */\n\n/**\n * @implements {Datastore}\n */\nexport class BaseDatastore {\n /**\n * @returns {Promise}\n */\n open () {\n return Promise.reject(new Error('.open is not implemented'))\n }\n\n /**\n * @returns {Promise}\n */\n close () {\n return Promise.reject(new Error('.close is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Uint8Array} val\n * @param {Options} [options]\n * @returns {Promise}\n */\n put (key, val, options) {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n get (key, options) {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n has (key, options) {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n /**\n * @param {Key} key\n * @param {Options} [options]\n * @returns {Promise}\n */\n delete (key, options) {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * putMany (source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield { key, value }\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * getMany (source, options = {}) {\n for await (const key of source) {\n yield this.get(key, options)\n }\n }\n\n /**\n * @param {AwaitIterable} source\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n async * deleteMany (source, options = {}) {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n /**\n * @returns {Batch}\n */\n batch () {\n /** @type {Pair[]} */\n let puts = []\n /** @type {Key[]} */\n let dels = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\n\n delete (key) {\n dels.push(key)\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options))\n puts = []\n await drain(this.deleteMany(dels, options))\n dels = []\n }\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n *\n * @param {Query} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _all (q, options) {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n *\n * @param {KeyQuery} q\n * @param {Options} [options]\n * @returns {AsyncIterable}\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q, options) {\n throw new Error('._allKeys is not implemented')\n }\n\n /**\n * @param {Query} q\n * @param {Options} [options]\n */\n query (q, options) {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (e) =>\n e.key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n /**\n * @param {KeyQuery} q\n * @param {Options} [options]\n */\n queryKeys (q, options) {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n it = filter(it, (key) =>\n key.toString().startsWith(/** @type {string} */ (q.prefix))\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sortAll(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n it = filter(it, () => i++ >= /** @type {number} */ (q.offset))\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n","import errCode from 'err-code'\n\n/**\n * @param {Error} [err]\n */\nexport function dbOpenFailedError (err) {\n err = err || new Error('Cannot open database')\n return errCode(err, 'ERR_DB_OPEN_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbDeleteFailedError (err) {\n err = err || new Error('Delete failed')\n return errCode(err, 'ERR_DB_DELETE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function dbWriteFailedError (err) {\n err = err || new Error('Write failed')\n return errCode(err, 'ERR_DB_WRITE_FAILED')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function notFoundError (err) {\n err = err || new Error('Not Found')\n return errCode(err, 'ERR_NOT_FOUND')\n}\n\n/**\n * @param {Error} [err]\n */\nexport function abortedError (err) {\n err = err || new Error('Aborted')\n return errCode(err, 'ERR_ABORTED')\n}\n","export enum messages {\n NOT_STARTED_YET = 'The libp2p node is not started yet',\n DHT_DISABLED = 'DHT is not available',\n PUBSUB_DISABLED = 'PubSub is not available',\n CONN_ENCRYPTION_REQUIRED = 'At least one connection encryption module is required',\n ERR_TRANSPORTS_REQUIRED = 'At least one transport module is required',\n ERR_PROTECTOR_REQUIRED = 'Private network is enforced, but no protector was provided',\n NOT_FOUND = 'Not found'\n}\n\nexport enum codes {\n DHT_DISABLED = 'ERR_DHT_DISABLED',\n ERR_PUBSUB_DISABLED = 'ERR_PUBSUB_DISABLED',\n PUBSUB_NOT_STARTED = 'ERR_PUBSUB_NOT_STARTED',\n DHT_NOT_STARTED = 'ERR_DHT_NOT_STARTED',\n CONN_ENCRYPTION_REQUIRED = 'ERR_CONN_ENCRYPTION_REQUIRED',\n ERR_TRANSPORTS_REQUIRED = 'ERR_TRANSPORTS_REQUIRED',\n ERR_PROTECTOR_REQUIRED = 'ERR_PROTECTOR_REQUIRED',\n ERR_PEER_DIAL_INTERCEPTED = 'ERR_PEER_DIAL_INTERCEPTED',\n ERR_CONNECTION_INTERCEPTED = 'ERR_CONNECTION_INTERCEPTED',\n ERR_INVALID_PROTOCOLS_FOR_STREAM = 'ERR_INVALID_PROTOCOLS_FOR_STREAM',\n ERR_CONNECTION_ENDED = 'ERR_CONNECTION_ENDED',\n ERR_CONNECTION_FAILED = 'ERR_CONNECTION_FAILED',\n ERR_NODE_NOT_STARTED = 'ERR_NODE_NOT_STARTED',\n ERR_ALREADY_ABORTED = 'ERR_ALREADY_ABORTED',\n ERR_TOO_MANY_ADDRESSES = 'ERR_TOO_MANY_ADDRESSES',\n ERR_NO_VALID_ADDRESSES = 'ERR_NO_VALID_ADDRESSES',\n ERR_RELAYED_DIAL = 'ERR_RELAYED_DIAL',\n ERR_DIALED_SELF = 'ERR_DIALED_SELF',\n ERR_DISCOVERED_SELF = 'ERR_DISCOVERED_SELF',\n ERR_DUPLICATE_TRANSPORT = 'ERR_DUPLICATE_TRANSPORT',\n ERR_ENCRYPTION_FAILED = 'ERR_ENCRYPTION_FAILED',\n ERR_HOP_REQUEST_FAILED = 'ERR_HOP_REQUEST_FAILED',\n ERR_INVALID_KEY = 'ERR_INVALID_KEY',\n ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE',\n ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS',\n ERR_INVALID_PEER = 'ERR_INVALID_PEER',\n ERR_MUXER_UNAVAILABLE = 'ERR_MUXER_UNAVAILABLE',\n ERR_NOT_FOUND = 'ERR_NOT_FOUND',\n ERR_TIMEOUT = 'ERR_TIMEOUT',\n ERR_TRANSPORT_UNAVAILABLE = 'ERR_TRANSPORT_UNAVAILABLE',\n ERR_TRANSPORT_DIAL_FAILED = 'ERR_TRANSPORT_DIAL_FAILED',\n ERR_UNSUPPORTED_PROTOCOL = 'ERR_UNSUPPORTED_PROTOCOL',\n ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED = 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED',\n ERR_INVALID_MULTIADDR = 'ERR_INVALID_MULTIADDR',\n ERR_SIGNATURE_NOT_VALID = 'ERR_SIGNATURE_NOT_VALID',\n ERR_FIND_SELF = 'ERR_FIND_SELF',\n ERR_NO_ROUTERS_AVAILABLE = 'ERR_NO_ROUTERS_AVAILABLE',\n ERR_CONNECTION_NOT_MULTIPLEXED = 'ERR_CONNECTION_NOT_MULTIPLEXED',\n ERR_NO_DIAL_TOKENS = 'ERR_NO_DIAL_TOKENS',\n ERR_KEYCHAIN_REQUIRED = 'ERR_KEYCHAIN_REQUIRED',\n ERR_INVALID_CMS = 'ERR_INVALID_CMS',\n ERR_MISSING_KEYS = 'ERR_MISSING_KEYS',\n ERR_NO_KEY = 'ERR_NO_KEY',\n ERR_INVALID_KEY_NAME = 'ERR_INVALID_KEY_NAME',\n ERR_INVALID_KEY_TYPE = 'ERR_INVALID_KEY_TYPE',\n ERR_KEY_ALREADY_EXISTS = 'ERR_KEY_ALREADY_EXISTS',\n ERR_INVALID_KEY_SIZE = 'ERR_INVALID_KEY_SIZE',\n ERR_KEY_NOT_FOUND = 'ERR_KEY_NOT_FOUND',\n ERR_OLD_KEY_NAME_INVALID = 'ERR_OLD_KEY_NAME_INVALID',\n ERR_NEW_KEY_NAME_INVALID = 'ERR_NEW_KEY_NAME_INVALID',\n ERR_PASSWORD_REQUIRED = 'ERR_PASSWORD_REQUIRED',\n ERR_PEM_REQUIRED = 'ERR_PEM_REQUIRED',\n ERR_CANNOT_READ_KEY = 'ERR_CANNOT_READ_KEY',\n ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY',\n ERR_MISSING_PUBLIC_KEY = 'ERR_MISSING_PUBLIC_KEY',\n ERR_INVALID_OLD_PASS_TYPE = 'ERR_INVALID_OLD_PASS_TYPE',\n ERR_INVALID_NEW_PASS_TYPE = 'ERR_INVALID_NEW_PASS_TYPE',\n ERR_INVALID_PASS_LENGTH = 'ERR_INVALID_PASS_LENGTH',\n ERR_NOT_IMPLEMENTED = 'ERR_NOT_IMPLEMENTED',\n ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK',\n ERR_INVALID_RECORD = 'ERR_INVALID_RECORD',\n ERR_ALREADY_SUCCEEDED = 'ERR_ALREADY_SUCCEEDED',\n ERR_NO_HANDLER_FOR_PROTOCOL = 'ERR_NO_HANDLER_FOR_PROTOCOL',\n ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS',\n ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS'\n}\n","import errCode from 'err-code'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport type { Source } from 'it-stream-types'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\n\n/**\n * Store the multiaddrs from every peer in the passed peer store\n */\nexport async function * storeAddresses (source: Source, peerStore: PeerStore) {\n yield * map(source, async (peer) => {\n // ensure we have the addresses for a given peer\n await peerStore.addressBook.add(peer.id, peer.multiaddrs)\n\n return peer\n })\n}\n\n/**\n * Filter peers by unique peer id\n */\nexport function uniquePeers (source: Source) {\n /** @type Set */\n const seen = new Set()\n\n return filter(source, (peer) => {\n // dedupe by peer id\n if (seen.has(peer.id.toString())) {\n return false\n }\n\n seen.add(peer.id.toString())\n\n return true\n })\n}\n\n/**\n * Require at least `min` peers to be yielded from `source`\n */\nexport async function * requirePeers (source: Source, min: number = 1) {\n let seen = 0\n\n for await (const peer of source) {\n seen++\n\n yield peer\n }\n\n if (seen < min) {\n throw errCode(new Error('not found'), 'NOT_FOUND')\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes, messages } from './errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './content-routing/utils.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport drain from 'it-drain'\nimport filter from 'it-filter'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error module with no types\n} from 'set-delayed-interval'\nimport { setMaxListeners } from 'events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:peer-routing')\n\nexport interface RefreshManagerInit {\n /**\n * Whether to enable the Refresh manager\n */\n enabled?: boolean\n\n /**\n * Boot delay to start the Refresh Manager (in ms)\n */\n bootDelay?: number\n\n /**\n * Interval between each Refresh Manager run (in ms)\n */\n interval?: number\n\n /**\n * How long to let each refresh run (in ms)\n */\n timeout?: number\n}\n\nexport interface PeerRoutingInit {\n routers: PeerRouting[]\n refreshManager?: RefreshManagerInit\n}\n\nexport class DefaultPeerRouting implements PeerRouting, Startable {\n private readonly components: Components\n private readonly routers: PeerRouting[]\n private readonly refreshManagerInit: RefreshManagerInit\n private timeoutId?: ReturnType\n private started: boolean\n private abortController?: TimeoutController\n\n constructor (components: Components, init: PeerRoutingInit) {\n this.components = components\n this.routers = init.routers\n this.refreshManagerInit = init.refreshManager ?? {}\n this.started = false\n\n this._findClosestPeersTask = this._findClosestPeersTask.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start peer routing service.\n */\n async start () {\n if (this.started || this.routers.length === 0 || this.timeoutId != null || this.refreshManagerInit.enabled === false) {\n return\n }\n\n this.timeoutId = setDelayedInterval(\n this._findClosestPeersTask, this.refreshManagerInit.interval, this.refreshManagerInit.bootDelay\n )\n\n this.started = true\n }\n\n /**\n * Recurrent task to find closest peers and add their addresses to the Address Book.\n */\n async _findClosestPeersTask () {\n if (this.abortController != null) {\n // we are already running the query\n return\n }\n\n try {\n this.abortController = new TimeoutController(this.refreshManagerInit.timeout ?? 10e3)\n\n // this controller may be used while dialing lots of peers so prevent MaxListenersExceededWarning\n // appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.abortController.signal)\n } catch {}\n\n // nb getClosestPeers adds the addresses to the address book\n await drain(this.getClosestPeers(this.components.getPeerId().toBytes(), { signal: this.abortController.signal }))\n } catch (err: any) {\n log.error(err)\n } finally {\n this.abortController?.clear()\n this.abortController = undefined\n }\n }\n\n /**\n * Stop peer routing service.\n */\n async stop () {\n clearDelayedInterval(this.timeoutId)\n\n // abort query if it is in-flight\n this.abortController?.abort()\n\n this.started = false\n }\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: PeerId, options?: AbortOptions): Promise {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n if (id.toString() === this.components.getPeerId().toString()) {\n throw errCode(new Error('Should not try to find self'), codes.ERR_FIND_SELF)\n }\n\n const output = await pipe(\n merge(\n ...this.routers.map(router => (async function * () {\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n log.error(err)\n }\n })())\n ),\n (source) => filter(source, Boolean),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n async (source) => await first(source)\n )\n\n if (output != null) {\n return output\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options?: AbortOptions): AsyncIterable {\n if (this.routers.length === 0) {\n throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.getClosestPeers(key, options))\n ),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\n }\n}\n","import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport {\n storeAddresses,\n uniquePeers,\n requirePeers\n} from './utils.js'\nimport drain from 'it-drain'\nimport merge from 'it-merge'\nimport { pipe } from 'it-pipe'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { CID } from 'multiformats/cid'\nimport type { Components } from '@libp2p/components'\n\nexport interface CompoundContentRoutingInit {\n routers: ContentRouting[]\n}\n\nexport class CompoundContentRouting implements ContentRouting, Startable {\n private readonly routers: ContentRouting[]\n private started: boolean\n private readonly components: Components\n\n constructor (components: Components, init: CompoundContentRoutingInit) {\n this.routers = init.routers ?? []\n this.started = false\n this.components = components\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n async stop () {\n this.started = false\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async * findProviders (key: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content this.routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n yield * pipe(\n merge(\n ...this.routers.map(router => router.findProviders(key, options))\n ),\n (source) => storeAddresses(source, this.components.getPeerStore()),\n (source) => uniquePeers(source),\n (source) => requirePeers(source)\n )\n }\n\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide (key: CID, options: AbortOptions = {}) {\n if (this.routers.length === 0) {\n throw errCode(new Error('No content routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n await Promise.all(this.routers.map(async (router) => await router.provide(key, options)))\n }\n\n /**\n * Store the given key/value pair in the available content routings\n */\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions) {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.getDHT()\n\n if (dht != null) {\n await drain(dht.put(key, value, options))\n }\n }\n\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n const dht = this.components.getDHT()\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n /**\n * Get the `n` values to the given key without sorting\n */\n async * getMany (key: Uint8Array, nVals: number, options: AbortOptions) { // eslint-disable-line require-await\n if (!this.isStarted()) {\n throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED)\n }\n\n if (nVals == null || nVals === 0) {\n return\n }\n\n let gotValues = 0\n const dht = this.components.getDHT()\n\n if (dht != null) {\n for await (const event of dht.get(key, options)) {\n if (event.name === 'VALUE') {\n yield { from: event.from, val: event.value }\n\n gotValues++\n\n if (gotValues === nVals) {\n break\n }\n }\n }\n }\n\n if (gotValues === 0) {\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n }\n}\n","import { peerIdFromString } from '@libp2p/peer-id'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isPeerId } from '@libp2p/interface-peer-id'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\n\nfunction peerIdFromMultiaddr (ma: Multiaddr) {\n const idStr = ma.getPeerId()\n\n if (idStr == null) {\n throw errCode(\n new Error(`${ma.toString()} does not have a valid peer type`),\n codes.ERR_INVALID_MULTIADDR\n )\n }\n\n try {\n return peerIdFromString(idStr)\n } catch (err: any) {\n throw errCode(\n new Error(`${ma.toString()} is not a valid peer type`),\n codes.ERR_INVALID_MULTIADDR\n )\n }\n}\n\n/**\n * Converts the given `peer` to a `Peer` object.\n */\nexport function getPeer (peer: PeerId | Multiaddr | string): PeerInfo {\n if (isPeerId(peer)) {\n return {\n id: peer,\n multiaddrs: [],\n protocols: []\n }\n }\n\n if (typeof peer === 'string') {\n peer = new Multiaddr(peer)\n }\n\n let addr\n\n if (Multiaddr.isMultiaddr(peer)) {\n addr = peer\n peer = peerIdFromMultiaddr(peer)\n }\n\n return {\n id: peer,\n multiaddrs: addr != null ? [addr] : [],\n protocols: []\n }\n}\n","import type { AddressManagerEvents } from '@libp2p/interface-address-manager'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { Components } from '@libp2p/components'\n\nexport interface AddressManagerInit {\n announceFilter?: AddressFilter\n\n /**\n * list of multiaddrs string representation to listen\n */\n listen?: string[]\n\n /**\n * list of multiaddrs string representation to announce\n */\n announce?: string[]\n\n /**\n * list of multiaddrs string representation to never announce\n */\n noAnnounce?: string[]\n}\n\nexport interface AddressFilter {\n (addrs: Multiaddr[]): Multiaddr[]\n}\n\nconst defaultAddressFilter = (addrs: Multiaddr[]): Multiaddr[] => addrs\n\nexport class DefaultAddressManager extends EventEmitter {\n private readonly components: Components\n private readonly listen: Set\n private readonly announce: Set\n private readonly observed: Set\n private readonly announceFilter: AddressFilter\n\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor (components: Components, init: AddressManagerInit) {\n super()\n\n const { listen = [], announce = [] } = init\n\n this.components = components\n this.listen = new Set(listen.map(ma => ma.toString()))\n this.announce = new Set(announce.map(ma => ma.toString()))\n this.observed = new Set()\n this.announceFilter = init.announceFilter ?? defaultAddressFilter\n }\n\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs (): Multiaddr[] {\n return Array.from(this.listen).map((a) => new Multiaddr(a))\n }\n\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs (): Multiaddr[] {\n return Array.from(this.announce).map((a) => new Multiaddr(a))\n }\n\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs (): Multiaddr[] {\n return Array.from(this.observed).map((a) => new Multiaddr(a))\n }\n\n /**\n * Add peer observed addresses\n */\n addObservedAddr (addr: string | Multiaddr): void {\n let ma = new Multiaddr(addr)\n const remotePeer = ma.getPeerId()\n\n // strip our peer id if it has been passed\n if (remotePeer != null) {\n const remotePeerId = peerIdFromString(remotePeer)\n\n // use same encoding for comparison\n if (remotePeerId.equals(this.components.getPeerId())) {\n ma = ma.decapsulate(new Multiaddr(`/p2p/${this.components.getPeerId().toString()}`))\n }\n }\n\n const addrString = ma.toString()\n\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return\n }\n\n this.observed.add(addrString)\n this.dispatchEvent(new CustomEvent('change:addresses'))\n }\n\n getAddresses (): Multiaddr[] {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString())\n\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.getTransportManager().getAddrs().map(ma => ma.toString())\n }\n\n addrs = addrs.concat(this.getObservedAddrs().map(ma => ma.toString()))\n\n // dedupe multiaddrs\n const addrSet = new Set(addrs)\n\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => new Multiaddr(str)))\n .map(ma => {\n if (ma.getPeerId() === this.components.getPeerId().toString()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${this.components.getPeerId().toString()}`)\n })\n }\n}\n","/**\n * Thin ESM wrapper for CJS named exports.\n *\n * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1\n */\n\nimport mergeOptions from './index.js';\nexport default mergeOptions;\n","/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor:visibility-change-emitter')\n\ninterface VisibilityChangeEmitterEvents {\n 'visibilityChange': CustomEvent\n}\n\ntype Hidden = 'hidden' | 'mozHidden' | 'msHidden' | 'webkitHidden'\n\n/**\n * Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.\n *\n * Warning: This does not work on all browsers, but should work on all modern browsers\n *\n * @example\n *\n * const myVisibilityEmitter = new VisibilityChangeEmitter();\n *\n * myVisibilityEmitter.on('visibilityChange', (pageInFocus) => {\n * if ( pageInFocus ){\n * // Page is in focus\n * console.log('In focus');\n * }\n * else {\n * // Page is blurred\n * console.log('Out of focus');\n * }\n * });\n * // To access the visibility state directly, call:\n * console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());\n */\nexport class VisibilityChangeEmitter extends EventEmitter {\n private hidden: Hidden\n private visibilityChange: string\n\n constructor () {\n super()\n\n this.hidden = 'hidden'\n this.visibilityChange = 'visibilityChange'\n\n if (globalThis.document != null) {\n this._initializeVisibilityVarNames()\n this._addVisibilityChangeListener()\n }\n }\n\n /**\n * document.hidden and document.visibilityChange are the two variables we need to check for;\n * Since these variables are named differently in different browsers, this function sets\n * the appropriate name based on the browser being used. Once executed, tha actual names of\n * document.hidden and document.visibilityChange are found in this._hidden and this._visibilityChange\n * respectively\n *\n * @private\n */\n _initializeVisibilityVarNames () {\n let hidden: Hidden = 'hidden'\n let visibilityChange = 'visibilitychange'\n\n if (typeof globalThis.document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support\n hidden = 'hidden'\n visibilityChange = 'visibilitychange'\n // @ts-expect-error mozHidden is a non-standard field name\n } else if (typeof globalThis.document.mozHidden !== 'undefined') {\n hidden = 'mozHidden'\n visibilityChange = 'mozvisibilitychange'\n // @ts-expect-error msHidden is a non-standard field name\n } else if (typeof globalThis.document.msHidden !== 'undefined') {\n hidden = 'msHidden'\n visibilityChange = 'msvisibilitychange'\n // @ts-expect-error webkitHidden is a non-standard field name\n } else if (typeof globalThis.document.webkitHidden !== 'undefined') {\n hidden = 'webkitHidden'\n visibilityChange = 'webkitvisibilitychange'\n }\n\n this.hidden = hidden\n this.visibilityChange = visibilityChange\n }\n\n /**\n * Adds an event listener on the document that listens to changes in document.visibilityChange\n * (or whatever name by which the visibilityChange variable is known in the browser)\n *\n * @private\n */\n _addVisibilityChangeListener () {\n // @ts-expect-error cannot index document object with string key\n if (typeof globalThis.document.addEventListener === 'undefined' || typeof document[this.hidden] === 'undefined') {\n log('Checking page visibility requires a browser that supports the Page Visibility API.')\n } else {\n // Handle page visibility change\n globalThis.document.addEventListener(this.visibilityChange, this._handleVisibilityChange.bind(this), false)\n }\n }\n\n /**\n * The function returns ```true``` if the page is visible or ```false``` if the page is not visible and\n * ```undefined``` if the page visibility API is not supported by the browser.\n */\n isVisible () {\n // @ts-expect-error cannot index document object with string key\n if (this.hidden === undefined || document[this.hidden] === undefined) {\n return undefined\n }\n\n // @ts-expect-error cannot index document object with string key\n return document[this.hidden] == null\n }\n\n /**\n * The function that is called when document.visibilityChange has changed\n * It emits an event called visibilityChange and sends the value of document.hidden as a\n * parameter\n *\n * @private\n */\n _handleVisibilityChange () {\n // @ts-expect-error cannot index document object with string key\n const visible = globalThis.document[this.hidden] === false\n log(visible ? 'Page Visible' : 'Page Hidden')\n\n // Emit the event\n this.dispatchEvent(new CustomEvent('visibilityChange', {\n detail: visible\n }))\n }\n}\n","/**\n * This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)\n */\n\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { VisibilityChangeEmitter } from './visibility-change-emitter.js'\nimport { logger } from '@libp2p/logger'\n\nconst log = logger('libp2p:connection-manager:latency-monitor')\n\nexport interface LatencyMonitorEvents {\n 'data': CustomEvent\n}\n\nexport interface LatencyMonitorInit {\n /**\n * How often to add a latency check event (ms)\n */\n latencyCheckIntervalMs?: number\n\n /**\n * How often to summarize latency check events. null or 0 disables event firing\n */\n dataEmitIntervalMs?: number\n\n /**\n * What cb-style async function to use\n */\n asyncTestFn?: (cb: () => void) => void\n\n /**\n * What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.\n */\n latencyRandomPercentage?: number\n}\n\nexport interface SummaryObject {\n /**\n * How many events were called\n */\n events: number\n\n /**\n * What was the min time for a cb to be called\n */\n minMs: number\n\n /**\n * What was the max time for a cb to be called\n */\n maxMs: number\n\n /**\n * What was the average time for a cb to be called\n */\n avgMs: number\n\n /**\n * How long this interval was in ms\n */\n lengthMs: number\n}\n\ninterface LatencyData {\n startTime: number\n events: number\n minMs: number\n maxMs: number\n totalMs: number\n}\n\n/**\n * A class to monitor latency of any async function which works in a browser or node. This works by periodically calling\n * the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this.\n * This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0.\n *\n * @extends {EventEmitter}\n *\n * The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop\n * and timing how long it takes to get back.\n *\n * @example\n * const monitor = new LatencyMonitor();\n * monitor.on('data', (summary) => console.log('Event Loop Latency: %O', summary));\n *\n * @example\n * const monitor = new LatencyMonitor({latencyCheckIntervalMs: 1000, dataEmitIntervalMs: 60000, asyncTestFn:ping});\n * monitor.on('data', (summary) => console.log('Ping Pong Latency: %O', summary));\n */\nexport class LatencyMonitor extends EventEmitter {\n private readonly latencyCheckIntervalMs: number\n private readonly latencyRandomPercentage: number\n private readonly latencyCheckMultiply: number\n private readonly latencyCheckSubtract: number\n private readonly dataEmitIntervalMs?: number\n private readonly asyncTestFn?: (cb: () => void) => void\n\n private readonly now: (num?: any) => any\n private readonly getDeltaMS: (num: number) => number\n private visibilityChangeEmitter?: VisibilityChangeEmitter\n private latencyData: LatencyData\n private checkLatencyID?: NodeJS.Timeout\n private emitIntervalID?: NodeJS.Timeout\n\n constructor (init: LatencyMonitorInit = {}) {\n super()\n\n const { latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = init\n\n // 0 isn't valid here, so its ok to use ||\n this.latencyCheckIntervalMs = latencyCheckIntervalMs ?? 500 // 0.5s\n this.latencyRandomPercentage = latencyRandomPercentage ?? 10\n this.latencyCheckMultiply = 2 * (this.latencyRandomPercentage / 100.0) * this.latencyCheckIntervalMs\n this.latencyCheckSubtract = this.latencyCheckMultiply / 2\n\n this.dataEmitIntervalMs = (dataEmitIntervalMs === null || dataEmitIntervalMs === 0)\n ? undefined\n : dataEmitIntervalMs ?? 5 * 1000 // 5s\n log('latencyCheckIntervalMs: %s dataEmitIntervalMs: %s',\n this.latencyCheckIntervalMs, this.dataEmitIntervalMs)\n if (this.dataEmitIntervalMs != null) {\n log('Expecting ~%s events per summary', this.latencyCheckIntervalMs / this.dataEmitIntervalMs)\n } else {\n log('Not emitting summaries')\n }\n\n this.asyncTestFn = asyncTestFn // If there is no asyncFn, we measure latency\n\n // If process: use high resolution timer\n if (globalThis.process?.hrtime != null) {\n log('Using process.hrtime for timing')\n this.now = globalThis.process.hrtime // eslint-disable-line no-undef\n this.getDeltaMS = (startTime) => {\n const hrtime = this.now(startTime)\n return (hrtime[0] * 1000) + (hrtime[1] / 1000000)\n }\n // Let's try for a timer that only monotonically increases\n } else if (typeof window !== 'undefined' && window.performance?.now != null) {\n log('Using performance.now for timing')\n this.now = window.performance.now.bind(window.performance)\n this.getDeltaMS = (startTime) => Math.round(this.now() - startTime)\n } else {\n log('Using Date.now for timing')\n this.now = Date.now\n this.getDeltaMS = (startTime) => this.now() - startTime\n }\n\n this.latencyData = this.initLatencyData()\n }\n\n start () {\n // We check for isBrowser because of browsers set max rates of timeouts when a page is hidden,\n // so we fall back to another library\n // See: http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs\n if (isBrowser()) {\n this.visibilityChangeEmitter = new VisibilityChangeEmitter()\n\n this.visibilityChangeEmitter.addEventListener('visibilityChange', (evt) => {\n const { detail: pageInFocus } = evt\n\n if (pageInFocus) {\n this._startTimers()\n } else {\n this._emitSummary()\n this._stopTimers()\n }\n })\n }\n\n if (this.visibilityChangeEmitter?.isVisible() === true) {\n this._startTimers()\n }\n }\n\n stop () {\n this._stopTimers()\n }\n\n /**\n * Start internal timers\n *\n * @private\n */\n _startTimers () {\n // Timer already started, ignore this\n if (this.checkLatencyID != null) {\n return\n }\n\n this.checkLatency()\n\n if (this.dataEmitIntervalMs != null) {\n this.emitIntervalID = setInterval(() => this._emitSummary(), this.dataEmitIntervalMs)\n if (typeof this.emitIntervalID.unref === 'function') {\n this.emitIntervalID.unref() // Doesn't block exit\n }\n }\n }\n\n /**\n * Stop internal timers\n *\n * @private\n */\n _stopTimers () {\n if (this.checkLatencyID != null) {\n clearTimeout(this.checkLatencyID)\n this.checkLatencyID = undefined\n }\n if (this.emitIntervalID != null) {\n clearInterval(this.emitIntervalID)\n this.emitIntervalID = undefined\n }\n }\n\n /**\n * Emit summary only if there were events. It might not have any events if it was forced via a page hidden/show\n *\n * @private\n */\n _emitSummary () {\n const summary = this.getSummary()\n if (summary.events > 0) {\n this.dispatchEvent(new CustomEvent('data', {\n detail: summary\n }))\n }\n }\n\n /**\n * Calling this function will end the collection period. If a timing event was already fired and somewhere in the queue,\n * it will not count for this time period\n */\n getSummary (): SummaryObject {\n // We might want to adjust for the number of expected events\n // Example: first 1 event it comes back, then such a long blocker that the next emit check comes\n // Then this fires - looks like no latency!!\n const latency = {\n events: this.latencyData.events,\n minMs: this.latencyData.minMs,\n maxMs: this.latencyData.maxMs,\n avgMs: this.latencyData.events > 0\n ? this.latencyData.totalMs / this.latencyData.events\n : Number.POSITIVE_INFINITY,\n lengthMs: this.getDeltaMS(this.latencyData.startTime)\n }\n this.latencyData = this.initLatencyData() // Clear\n\n log.trace('Summary: %O', latency)\n return latency\n }\n\n /**\n * Randomly calls an async fn every roughly latencyCheckIntervalMs (plus some randomness). If no async fn is found,\n * it will simply report on event loop latency.\n */\n checkLatency () {\n // Randomness is needed to avoid alignment by accident to regular things in the event loop\n const randomness = (Math.random() * this.latencyCheckMultiply) - this.latencyCheckSubtract\n\n // We use this to ensure that in case some overlap somehow, we don't take the wrong startTime/offset\n const localData = {\n deltaOffset: Math.ceil(this.latencyCheckIntervalMs + randomness),\n startTime: this.now()\n }\n\n const cb = () => {\n // We are already stopped, ignore this datapoint\n if (this.checkLatencyID == null) {\n return\n }\n const deltaMS = this.getDeltaMS(localData.startTime) - localData.deltaOffset\n this.checkLatency() // Start again ASAP\n\n // Add the data point. If this gets complex, refactor it\n this.latencyData.events++\n this.latencyData.minMs = Math.min(this.latencyData.minMs, deltaMS)\n this.latencyData.maxMs = Math.max(this.latencyData.maxMs, deltaMS)\n this.latencyData.totalMs += deltaMS\n log.trace('MS: %s Data: %O', deltaMS, this.latencyData)\n }\n log.trace('localData: %O', localData)\n\n this.checkLatencyID = setTimeout(() => {\n // This gets rid of including event loop\n if (this.asyncTestFn != null) {\n // Clear timing related things\n localData.deltaOffset = 0\n localData.startTime = this.now()\n this.asyncTestFn(cb)\n } else {\n // setTimeout is not more accurate than 1ms, so this will ensure positive numbers. Add 1 to emitted data to remove.\n // This is not the best, but for now it'll be just fine. This isn't meant to be sub ms accurate.\n localData.deltaOffset -= 1\n // If there is no function to test, we mean check latency which is a special case that is really cb => cb()\n // We avoid that for the few extra function all overheads. Also, we want to keep the timers different\n cb()\n }\n }, localData.deltaOffset)\n\n if (typeof this.checkLatencyID.unref === 'function') {\n this.checkLatencyID.unref() // Doesn't block exit\n }\n }\n\n initLatencyData (): LatencyData {\n return {\n startTime: this.now(),\n minMs: Number.POSITIVE_INFINITY,\n maxMs: Number.NEGATIVE_INFINITY,\n events: 0,\n totalMs: 0\n }\n }\n}\n\nfunction isBrowser () {\n return typeof globalThis.window !== 'undefined'\n}\n","\nexport const OPEN = 'OPEN'\nexport const CLOSING = 'CLOSING'\nexport const CLOSED = 'CLOSED'\n","import errCode from 'err-code'\nimport { anySignal } from 'any-signal'\nimport FIFO from 'p-fifo'\nimport { setMaxListeners } from 'events'\nimport { codes } from '../../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Dialer } from './index.js'\n\nconst log = logger('libp2p:dialer:dial-request')\n\nexport interface DialAction {\n (m: Multiaddr, options: AbortOptions): Promise\n}\n\nexport interface DialRequestOptions {\n addrs: Multiaddr[]\n dialAction: DialAction\n dialer: Dialer\n}\n\nexport class DialRequest {\n private readonly addrs: Multiaddr[]\n private readonly dialer: Dialer\n private readonly dialAction: DialAction\n\n /**\n * Manages running the `dialAction` on multiple provided `addrs` in parallel\n * up to a maximum determined by the number of tokens returned\n * from `dialer.getTokens`. Once a DialRequest is created, it can be\n * started using `DialRequest.run(options)`. Once a single dial has succeeded,\n * all other dials in the request will be cancelled.\n */\n constructor (options: DialRequestOptions) {\n const {\n addrs,\n dialAction,\n dialer\n } = options\n\n this.addrs = addrs\n this.dialer = dialer\n this.dialAction = dialAction\n }\n\n async run (options: AbortOptions = {}): Promise {\n const tokens = this.dialer.getTokens(this.addrs.length)\n\n // If no tokens are available, throw\n if (tokens.length < 1) {\n throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS)\n }\n\n const tokenHolder = new FIFO()\n\n for (const token of tokens) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n }\n\n const dialAbortControllers: Array<(AbortController | undefined)> = this.addrs.map(() => {\n const controller = new AbortController()\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n return controller\n })\n\n if (options.signal != null) {\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, options.signal)\n } catch {}\n }\n\n let completedDials = 0\n let done = false\n\n try {\n return await Promise.any(this.addrs.map(async (addr, i) => {\n const token = await tokenHolder.shift() // get token\n // End attempt once another attempt succeeded\n if (done) {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED)\n }\n\n const controller = dialAbortControllers[i]\n if (controller == null) {\n throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS)\n }\n let conn\n try {\n const signal = controller.signal\n conn = await this.dialAction(addr, { ...options, signal: (options.signal != null) ? anySignal([signal, options.signal]) : signal })\n // Remove the successful AbortController so it is not aborted\n dialAbortControllers[i] = undefined\n } finally {\n completedDials++\n // If we have more or equal dials remaining than tokens, recycle the token, otherwise release it\n if (this.addrs.length - completedDials >= tokens.length) {\n void tokenHolder.push(token).catch(err => {\n log.error(err)\n })\n } else {\n this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])\n }\n }\n\n if (conn == null) {\n // Notify Promise.any that attempt was not successful\n // to prevent from returning undefined despite there\n // were successful dial attempts\n throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED)\n } else {\n // This dial succeeded, don't attempt anything else\n done = true\n }\n\n return conn\n }))\n } finally {\n // success/failure happened, abort everything else\n dialAbortControllers.forEach(c => {\n if (c !== undefined) {\n c.abort()\n }\n })\n tokens.forEach(token => this.dialer.releaseToken(token)) // release tokens back to the dialer\n }\n }\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport isIpPrivate from 'private-ip'\n\n/**\n * Check if a given multiaddr has a private address.\n */\nexport function isPrivate (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return Boolean(isIpPrivate(address))\n}\n","import type { Address } from '@libp2p/interface-peer-store'\nimport { isPrivate } from './multiaddr/is-private.js'\n\n/**\n * Compare function for array.sort().\n * This sort aims to move the private addresses to the end of the array.\n * In case of equality, a certified address will come first.\n */\nexport function publicAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n const isAPrivate = isPrivate(a.multiaddr)\n const isBPrivate = isPrivate(b.multiaddr)\n\n if (isAPrivate && !isBPrivate) {\n return 1\n } else if (!isAPrivate && isBPrivate) {\n return -1\n }\n // Check certified?\n if (a.isCertified && !b.isCertified) {\n return -1\n } else if (!a.isCertified && b.isCertified) {\n return 1\n }\n\n return 0\n}\n","\n/**\n * How long in ms a dial attempt is allowed to take\n */\nexport const DIAL_TIMEOUT = 30e3\n\n/**\n * How long in ms an inbound connection upgrade is allowed to take\n */\nexport const INBOUND_UPGRADE_TIMEOUT = 30e3\n\n/**\n * Maximum allowed concurrent dials\n */\nexport const MAX_PARALLEL_DIALS = 100\n\n/**\n * Allowed parallel dials per DialRequest\n */\nexport const MAX_PER_PEER_DIALS = 4\n\n/**\n * Maximum number of allowed addresses to attempt to dial\n */\nexport const MAX_ADDRS_TO_DIAL = 25\n\nexport const METRICS = {\n computeThrottleMaxQueueSize: 1000,\n computeThrottleTimeout: 2000,\n movingAverageIntervals: [\n 60 * 1000, // 1 minute\n 5 * 60 * 1000, // 5 minutes\n 15 * 60 * 1000 // 15 minutes\n ],\n maxOldPeersRetention: 50\n}\n","import { logger } from '@libp2p/logger'\nimport all from 'it-all'\nimport filter from 'it-filter'\nimport { pipe } from 'it-pipe'\nimport errCode from 'err-code'\nimport { Multiaddr, Resolver } from '@multiformats/multiaddr'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { AbortError } from '@libp2p/interfaces/errors'\nimport { anySignal } from 'any-signal'\nimport { setMaxListeners } from 'events'\nimport { DialAction, DialRequest } from './dial-request.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { trackedMap } from '@libp2p/tracked-map'\nimport { codes } from '../../errors.js'\nimport {\n DIAL_TIMEOUT,\n MAX_PARALLEL_DIALS,\n MAX_PER_PEER_DIALS,\n MAX_ADDRS_TO_DIAL\n} from '../../constants.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { getPeer } from '../../get-peer.js'\nimport sort from 'it-sort'\nimport { Components, Initializable } from '@libp2p/components'\nimport map from 'it-map'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { ComponentMetricsTracker } from '@libp2p/interface-metrics'\n\nconst log = logger('libp2p:dialer')\n\nconst METRICS_COMPONENT = 'dialler'\nconst METRICS_PENDING_DIALS = 'pending-dials'\nconst METRICS_PENDING_DIAL_TARGETS = 'pending-dial-targets'\n\nexport interface DialTarget {\n id: string\n addrs: Multiaddr[]\n}\n\nexport interface PendingDial {\n dialRequest: DialRequest\n controller: TimeoutController\n promise: Promise\n destroy: () => void\n}\n\nexport interface PendingDialTarget {\n resolve: (value: any) => void\n reject: (err: Error) => void\n}\n\nexport interface DialerInit {\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take\n */\n dialTimeout?: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n metrics?: ComponentMetricsTracker\n}\n\nexport class Dialer implements Startable, Initializable {\n private components: Components = new Components()\n private readonly addressSorter: AddressSorter\n private readonly maxAddrsToDial: number\n private readonly timeout: number\n private readonly maxDialsPerPeer: number\n public tokens: number[]\n public pendingDials: Map\n public pendingDialTargets: Map\n private started: boolean\n\n constructor (init: DialerInit = {}) {\n this.started = false\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxAddrsToDial = init.maxAddrsToDial ?? MAX_ADDRS_TO_DIAL\n this.timeout = init.dialTimeout ?? DIAL_TIMEOUT\n this.maxDialsPerPeer = init.maxDialsPerPeer ?? MAX_PER_PEER_DIALS\n this.tokens = [...new Array(init.maxParallelDials ?? MAX_PARALLEL_DIALS)].map((_, index) => index)\n this.pendingDials = trackedMap({\n component: METRICS_COMPONENT,\n metric: METRICS_PENDING_DIALS,\n metrics: init.metrics\n })\n this.pendingDialTargets = trackedMap({\n component: METRICS_COMPONENT,\n metric: METRICS_PENDING_DIAL_TARGETS,\n metrics: init.metrics\n })\n\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n Multiaddr.resolvers.set(key, value)\n }\n }\n\n init (components: Components): void {\n this.components = components\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n }\n\n /**\n * Clears any pending dials\n */\n async stop () {\n this.started = false\n\n for (const dial of this.pendingDials.values()) {\n try {\n dial.controller.abort()\n } catch (err: any) {\n log.error(err)\n }\n }\n this.pendingDials.clear()\n\n for (const pendingTarget of this.pendingDialTargets.values()) {\n pendingTarget.reject(new AbortError('Dialer was destroyed'))\n }\n this.pendingDialTargets.clear()\n }\n\n /**\n * Connects to a given `peer` by dialing all of its known addresses.\n * The dial to the first address that is successfully able to upgrade a connection\n * will be used.\n */\n async dial (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (this.components.getPeerId().equals(id)) {\n throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF)\n }\n\n log('check multiaddrs %p', id)\n\n if (multiaddrs != null && multiaddrs.length > 0) {\n log('storing multiaddrs %p', id, multiaddrs)\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n if (await this.components.getConnectionGater().denyDialPeer(id)) {\n throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED)\n }\n\n log('creating dial target for %p', id)\n\n const dialTarget = await this._createCancellableDialTarget(id, options)\n\n if (dialTarget.addrs.length === 0) {\n throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES)\n }\n\n const pendingDial = this.pendingDials.get(dialTarget.id) ?? this._createPendingDial(dialTarget, options)\n\n try {\n const connection = await pendingDial.promise\n log('dial succeeded to %s', dialTarget.id)\n return connection\n } catch (err: any) {\n log('dial failed to %s', dialTarget.id, err)\n // Error is a timeout\n if (pendingDial.controller.signal.aborted) {\n err.code = codes.ERR_TIMEOUT\n }\n log.error(err)\n throw err\n } finally {\n pendingDial.destroy()\n }\n }\n\n /**\n * Connects to a given `peer` by dialing all of its known addresses.\n * The dial to the first address that is successfully able to upgrade a connection\n * will be used.\n */\n async _createCancellableDialTarget (peer: PeerId, options: AbortOptions): Promise {\n // Make dial target promise cancellable\n const id = `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n const cancellablePromise = new Promise((resolve, reject) => {\n this.pendingDialTargets.set(id, { resolve, reject })\n })\n\n try {\n const dialTarget = await Promise.race([\n this._createDialTarget(peer, options),\n cancellablePromise\n ])\n\n return dialTarget\n } finally {\n this.pendingDialTargets.delete(id)\n }\n }\n\n /**\n * Creates a DialTarget. The DialTarget is used to create and track\n * the DialRequest to a given peer.\n * If a multiaddr is received it should be the first address attempted.\n * Multiaddrs not supported by the available transports will be filtered out.\n */\n async _createDialTarget (peer: PeerId, options: AbortOptions): Promise {\n const knownAddrs = await pipe(\n await this.components.getPeerStore().addressBook.get(peer),\n (source) => filter(source, async (address) => {\n return !(await this.components.getConnectionGater().denyDialMultiaddr(peer, address.multiaddr))\n }),\n (source) => sort(source, this.addressSorter),\n (source) => map(source, (address) => {\n const ma = address.multiaddr\n\n if (peer.toString() === ma.getPeerId()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${peer.toString()}`)\n }),\n async (source) => await all(source)\n )\n\n const addrs: Multiaddr[] = []\n for (const a of knownAddrs) {\n const resolvedAddrs = await this._resolve(a, options)\n resolvedAddrs.forEach(ra => addrs.push(ra))\n }\n\n // Multiaddrs not supported by the available transports will be filtered out.\n const supportedAddrs = addrs.filter(a => this.components.getTransportManager().transportForMultiaddr(a))\n\n if (supportedAddrs.length > this.maxAddrsToDial) {\n await this.components.getPeerStore().delete(peer)\n throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES)\n }\n\n return {\n id: peer.toString(),\n addrs: supportedAddrs\n }\n }\n\n /**\n * Creates a PendingDial that wraps the underlying DialRequest\n */\n _createPendingDial (dialTarget: DialTarget, options: AbortOptions = {}): PendingDial {\n /**\n * @param {Multiaddr} addr\n * @param {{ signal: { aborted: any; }; }} options\n */\n const dialAction: DialAction = async (addr, options = {}) => {\n if (options.signal?.aborted === true) {\n throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)\n }\n\n return await this.components.getTransportManager().dial(addr, options)\n }\n\n const dialRequest = new DialRequest({\n addrs: dialTarget.addrs,\n dialAction,\n dialer: this\n })\n\n // Combine the timeout signal and options.signal, if provided\n const timeoutController = new TimeoutController(this.timeout)\n\n const signals = [timeoutController.signal]\n ;(options.signal != null) && signals.push(options.signal)\n const signal = anySignal(signals)\n\n // this signal will potentially be used while dialing lots of\n // peers so prevent MaxListenersExceededWarning appearing in the console\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, signal)\n } catch {}\n\n const pendingDial = {\n dialRequest,\n controller: timeoutController,\n promise: dialRequest.run({ ...options, signal }),\n destroy: () => {\n timeoutController.clear()\n this.pendingDials.delete(dialTarget.id)\n }\n }\n this.pendingDials.set(dialTarget.id, pendingDial)\n\n return pendingDial\n }\n\n getTokens (num: number) {\n const total = Math.min(num, this.maxDialsPerPeer, this.tokens.length)\n const tokens = this.tokens.splice(0, total)\n log('%d tokens request, returning %d, %d remaining', num, total, this.tokens.length)\n return tokens\n }\n\n releaseToken (token: number) {\n // Guard against duplicate releases\n if (this.tokens.includes(token)) {\n return\n }\n\n log('token %d released', token)\n this.tokens.push(token)\n }\n\n /**\n * Resolve multiaddr recursively\n */\n async _resolve (ma: Multiaddr, options: AbortOptions): Promise {\n // TODO: recursive logic should live in multiaddr once dns4/dns6 support is in place\n // Now only supporting resolve for dnsaddr\n const resolvableProto = ma.protoNames().includes('dnsaddr')\n\n // Multiaddr is not resolvable? End recursion!\n if (!resolvableProto) {\n return [ma]\n }\n\n const resolvedMultiaddrs = await this._resolveRecord(ma, options)\n const recursiveMultiaddrs = await Promise.all(resolvedMultiaddrs.map(async (nm) => {\n return await this._resolve(nm, options)\n }))\n\n const addrs = recursiveMultiaddrs.flat()\n return addrs.reduce((array, newM) => {\n if (array.find(m => m.equals(newM)) == null) {\n array.push(newM)\n }\n return array\n }, ([]))\n }\n\n /**\n * Resolve a given multiaddr. If this fails, an empty array will be returned\n */\n async _resolveRecord (ma: Multiaddr, options: AbortOptions): Promise {\n try {\n ma = new Multiaddr(ma.toString()) // Use current multiaddr module\n const multiaddrs = await ma.resolve(options)\n return multiaddrs\n } catch (err) {\n log.error(`multiaddr ${ma.toString()} could not be resolved`, err)\n return []\n }\n }\n}\n","\nexport function mapIterable (iter: IterableIterator, map: (val: T) => R): IterableIterator {\n const iterator: IterableIterator = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerMap {\n private readonly map: Map\n\n constructor (map?: PeerMap) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value)\n }\n }\n }\n\n [Symbol.iterator] () {\n return this.entries()\n }\n\n clear () {\n this.map.clear()\n }\n\n delete (peer: PeerId) {\n this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, T], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [peerIdFromString(val[0]), val[1]]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap) => void): void {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T) {\n this.map.set(peer.toString(), value)\n }\n\n keys (): IterableIterator {\n return mapIterable(\n this.map.keys(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n values () {\n return this.map.values()\n }\n\n get size () {\n return this.map.size\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerSet {\n private readonly set: Set\n\n constructor (set?: PeerSet | Iterable) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size () {\n return this.set.size\n }\n\n [Symbol.iterator] () {\n return this.values()\n }\n\n add (peer: PeerId) {\n this.set.add(peer.toString())\n }\n\n clear () {\n this.set.clear()\n }\n\n delete (peer: PeerId) {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const id = peerIdFromString(str)\n\n predicate(id, id, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values () {\n return mapIterable(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n}\n","import type { PeerId } from '@libp2p/interface-peer-id'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { mapIterable } from './util.js'\n\n/**\n * We can't use PeerIds as list entries because list entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n */\nexport class PeerList {\n private readonly list: string[]\n\n constructor (list?: PeerList) {\n this.list = []\n\n if (list != null) {\n for (const value of list) {\n this.list.push(value.toString())\n }\n }\n }\n\n [Symbol.iterator] () {\n return mapIterable<[number, string], PeerId>(\n this.list.entries(),\n (val) => {\n return peerIdFromString(val[1])\n }\n )\n }\n\n concat (list: PeerList) {\n const output = new PeerList(this)\n\n for (const value of list) {\n output.push(value)\n }\n\n return output\n }\n\n entries (): IterableIterator<[number, PeerId]> {\n return mapIterable<[number, string], [number, PeerId]>(\n this.list.entries(),\n (val) => {\n return [val[0], peerIdFromString(val[1])]\n }\n )\n }\n\n every (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): boolean {\n return this.list.every((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n filter (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerList {\n const output = new PeerList()\n\n this.list.forEach((str, index) => {\n const peerId = peerIdFromString(str)\n\n if (predicate(peerId, index, this)) {\n output.push(peerId)\n }\n })\n\n return output\n }\n\n find (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): PeerId | undefined {\n const str = this.list.find((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n findIndex (predicate: (peerId: PeerId, index: number, arr: PeerList) => boolean): number {\n return this.list.findIndex((str, index) => {\n return predicate(peerIdFromString(str), index, this)\n })\n }\n\n forEach (predicate: (peerId: PeerId, index: number, arr: PeerList) => void): void {\n this.list.forEach((str, index) => {\n predicate(peerIdFromString(str), index, this)\n })\n }\n\n includes (peerId: PeerId): boolean {\n return this.list.includes(peerId.toString())\n }\n\n indexOf (peerId: PeerId): number {\n return this.list.indexOf(peerId.toString())\n }\n\n pop (): PeerId | undefined {\n const str = this.list.pop()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n push (...peerIds: PeerId[]) {\n for (const peerId of peerIds) {\n this.list.push(peerId.toString())\n }\n }\n\n shift (): PeerId | undefined {\n const str = this.list.shift()\n\n if (str == null) {\n return undefined\n }\n\n return peerIdFromString(str)\n }\n\n unshift (...peerIds: PeerId[]) {\n let len = this.list.length\n\n for (let i = peerIds.length - 1; i > -1; i--) {\n len = this.list.unshift(peerIds[i].toString())\n }\n\n return len\n }\n\n get length () {\n return this.list.length\n }\n}\n","\nexport const KEEP_ALIVE = 'keep-alive'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport mergeOptions from 'merge-options'\nimport { LatencyMonitor, SummaryObject } from './latency-monitor.js'\n// @ts-expect-error retimer does not have types\nimport retimer from 'retimer'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { codes } from '../errors.js'\nimport { isPeerId, PeerId } from '@libp2p/interface-peer-id'\nimport { setMaxListeners } from 'events'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport { Components, Initializable } from '@libp2p/components'\nimport * as STATUS from '@libp2p/interface-connection/status'\nimport { Dialer } from './dialer/index.js'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { Resolver } from '@multiformats/multiaddr'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { KEEP_ALIVE } from '@libp2p/interface-peer-store/tags'\n\nconst log = logger('libp2p:connection-manager')\n\nconst defaultOptions: Partial = {\n maxConnections: Infinity,\n minConnections: 0,\n maxData: Infinity,\n maxSentData: Infinity,\n maxReceivedData: Infinity,\n maxEventLoopDelay: Infinity,\n pollInterval: 2000,\n autoDialInterval: 10000,\n movingAverageInterval: 60000\n}\n\nconst METRICS_SYSTEM = 'libp2p'\nconst METRICS_COMPONENT = 'connection-manager'\nconst STARTUP_RECONNECT_TIMEOUT = 60000\n\nexport interface ConnectionManagerInit {\n /**\n * The maximum number of connections to keep open\n */\n maxConnections: number\n\n /**\n * The minimum number of connections to keep open\n */\n minConnections: number\n\n /**\n * The max data (in and out), per average interval to allow\n */\n maxData?: number\n\n /**\n * The max outgoing data, per average interval to allow\n */\n maxSentData?: number\n\n /**\n * The max incoming data, per average interval to allow\n */\n maxReceivedData?: number\n\n /**\n * The upper limit the event loop can take to run\n */\n maxEventLoopDelay?: number\n\n /**\n * How often, in milliseconds, metrics and latency should be checked\n */\n pollInterval?: number\n\n /**\n * How often, in milliseconds, to compute averages\n */\n movingAverageInterval?: number\n\n /**\n * If true, try to connect to all discovered peers up to the connection manager limit\n */\n autoDial?: boolean\n\n /**\n * How long to wait between attempting to keep our number of concurrent connections\n * above minConnections\n */\n autoDialInterval: number\n\n /**\n * Sort the known addresses of a peer before trying to dial\n */\n addressSorter?: AddressSorter\n\n /**\n * Number of max concurrent dials\n */\n maxParallelDials?: number\n\n /**\n * Number of max addresses to dial for a given peer\n */\n maxAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take, including DNS resolution\n * of the multiaddr, opening a socket and upgrading it to a Connection.\n */\n dialTimeout?: number\n\n /**\n * When a new inbound connection is opened, the upgrade process (e.g. protect,\n * encrypt, multiplex etc) must complete within this number of ms.\n */\n inboundUpgradeTimeout: number\n\n /**\n * Number of max concurrent dials per peer\n */\n maxDialsPerPeer?: number\n\n /**\n * Multiaddr resolvers to use when dialing\n */\n resolvers?: Record\n\n /**\n * On startup we try to dial any peer that has previously been\n * tagged with KEEP_ALIVE up to this timeout in ms. (default: 60000)\n */\n startupReconnectTimeout?: number\n}\n\nexport interface ConnectionManagerEvents {\n 'peer:connect': CustomEvent\n 'peer:disconnect': CustomEvent\n}\n\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager extends EventEmitter implements ConnectionManager, Startable, Initializable {\n public readonly dialer: Dialer\n private components = new Components()\n private readonly opts: Required\n private readonly connections: Map\n private started: boolean\n private timer?: ReturnType\n private readonly latencyMonitor: LatencyMonitor\n private readonly startupReconnectTimeout: number\n private connectOnStartupController?: TimeoutController\n private readonly dialTimeout: number\n\n constructor (init: ConnectionManagerInit) {\n super()\n\n this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n\n if (this.opts.maxConnections < this.opts.minConnections) {\n throw errCode(new Error('Connection Manager maxConnections must be greater than minConnections'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log('options: %o', this.opts)\n\n /**\n * Map of connections per peer\n */\n this.connections = new Map()\n\n this.started = false\n this._checkMetrics = this._checkMetrics.bind(this)\n\n this.latencyMonitor = new LatencyMonitor({\n latencyCheckIntervalMs: init.pollInterval,\n dataEmitIntervalMs: init.pollInterval\n })\n\n try {\n // This emitter gets listened to a lot\n setMaxListeners?.(Infinity, this)\n } catch {}\n\n this.dialer = new Dialer(this.opts)\n\n this.onConnect = this.onConnect.bind(this)\n this.onDisconnect = this.onDisconnect.bind(this)\n\n this.startupReconnectTimeout = init.startupReconnectTimeout ?? STARTUP_RECONNECT_TIMEOUT\n this.dialTimeout = init.dialTimeout ?? 30000\n }\n\n init (components: Components): void {\n this.components = components\n\n this.dialer.init(components)\n\n // track inbound/outbound connections\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'connections',\n label: 'direction',\n value: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n }\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.stat.direction === 'inbound') {\n metric.inbound++\n } else {\n metric.outbound++\n }\n }\n }\n\n return metric\n }\n })\n\n // track total number of streams per protocol\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'protocol-streams-total',\n label: 'protocol',\n value: () => {\n const metric: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n metric[key] = (metric[key] ?? 0) + 1\n }\n }\n }\n\n return metric\n }\n })\n\n // track 90th percentile of streams per protocol\n this.components.getMetrics()?.updateComponentMetric({\n system: METRICS_SYSTEM,\n component: METRICS_COMPONENT,\n metric: 'protocol-streams-per-connection-90th-percentile',\n label: 'protocol',\n value: () => {\n const allStreams: Record = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams: Record = {}\n\n for (const stream of conn.streams) {\n const key = `${stream.stat.direction} ${stream.stat.protocol ?? 'unnegotiated'}`\n\n streams[key] = (streams[key] ?? 0) + 1\n }\n\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? []\n allStreams[protocol].push(count)\n }\n }\n }\n\n const metric: Record = {}\n\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b)\n\n const index = Math.floor(counts.length * 0.9)\n metric[protocol] = counts[index]\n }\n\n return metric\n }\n })\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start () {\n if (this.components.getMetrics() != null) {\n this.timer = this.timer ?? retimer(this._checkMetrics, this.opts.pollInterval)\n }\n\n // latency monitor\n this.latencyMonitor.start()\n this._onLatencyMeasure = this._onLatencyMeasure.bind(this)\n this.latencyMonitor.addEventListener('data', this._onLatencyMeasure)\n await this.dialer.start()\n\n this.started = true\n log('started')\n }\n\n async afterStart () {\n this.components.getUpgrader().addEventListener('connection', this.onConnect)\n this.components.getUpgrader().addEventListener('connectionEnd', this.onDisconnect)\n\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers: PeerId[] = []\n\n for (const peer of await this.components.getPeerStore().all()) {\n const tags = await this.components.getPeerStore().getTags(peer.id)\n const hasKeepAlive = tags.filter(tag => tag.name === KEEP_ALIVE).length > 0\n\n if (hasKeepAlive) {\n keepAlivePeers.push(peer.id)\n }\n }\n\n this.connectOnStartupController?.clear()\n this.connectOnStartupController = new TimeoutController(this.startupReconnectTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, this.connectOnStartupController.signal)\n } catch {}\n\n await Promise.all(\n keepAlivePeers.map(async peer => {\n await this.openConnection(peer, {\n signal: this.connectOnStartupController?.signal\n })\n .catch(err => {\n log.error(err)\n })\n })\n )\n })\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n this.connectOnStartupController?.clear()\n })\n }\n\n async beforeStop () {\n // if we are still dialing KEEP_ALIVE peers, abort those dials\n this.connectOnStartupController?.abort()\n this.components.getUpgrader().removeEventListener('connection', this.onConnect)\n this.components.getUpgrader().removeEventListener('connectionEnd', this.onDisconnect)\n }\n\n /**\n * Stops the Connection Manager\n */\n async stop () {\n this.timer?.clear()\n\n this.latencyMonitor.removeEventListener('data', this._onLatencyMeasure)\n this.latencyMonitor.stop()\n await this.dialer.stop()\n\n this.started = false\n await this._close()\n log('stopped')\n }\n\n /**\n * Cleans up the connections\n */\n async _close () {\n // Close all connections we're tracking\n const tasks: Array> = []\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close()\n } catch (err) {\n log.error(err)\n }\n })())\n }\n }\n\n log('closing %d connections', tasks.length)\n await Promise.all(tasks)\n this.connections.clear()\n }\n\n /**\n * Checks the libp2p metrics to determine if any values have exceeded\n * the configured maximums.\n *\n * @private\n */\n async _checkMetrics () {\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n try {\n const movingAverages = metrics.getGlobal().getMovingAverages()\n const received = movingAverages.dataReceived[this.opts.movingAverageInterval].movingAverage\n await this._checkMaxLimit('maxReceivedData', received)\n const sent = movingAverages.dataSent[this.opts.movingAverageInterval].movingAverage\n await this._checkMaxLimit('maxSentData', sent)\n const total = received + sent\n await this._checkMaxLimit('maxData', total)\n log.trace('metrics update', total)\n } finally {\n this.timer = retimer(this._checkMetrics, this.opts.pollInterval)\n }\n }\n }\n\n onConnect (evt: CustomEvent) {\n void this._onConnect(evt).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close()\n return\n }\n\n const peerId = connection.remotePeer\n const peerIdStr = peerId.toString()\n const storedConns = this.connections.get(peerIdStr)\n\n if (storedConns != null) {\n storedConns.push(connection)\n } else {\n this.connections.set(peerIdStr, [connection])\n }\n\n if (peerId.publicKey != null) {\n await this.components.getPeerStore().keyBook.set(peerId, peerId.publicKey)\n }\n\n const numConnections = this.getConnections().length\n const toPrune = numConnections - this.opts.maxConnections\n\n await this._checkMaxLimit('maxConnections', numConnections, toPrune)\n this.dispatchEvent(new CustomEvent('peer:connect', { detail: connection }))\n }\n\n /**\n * Removes the connection from tracking\n */\n onDisconnect (evt: CustomEvent) {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return\n }\n\n const peerId = connection.remotePeer.toString()\n let storedConn = this.connections.get(peerId)\n\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id)\n this.connections.set(peerId, storedConn)\n } else if (storedConn != null) {\n this.connections.delete(peerId)\n this.dispatchEvent(new CustomEvent('peer:disconnect', { detail: connection }))\n\n this.components.getMetrics()?.onPeerDisconnected(connection.remotePeer)\n }\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n if (peerId != null) {\n return this.connections.get(peerId.toString()) ?? []\n }\n\n let conns: Connection[] = []\n\n for (const c of this.connections.values()) {\n conns = conns.concat(c)\n }\n\n return conns\n }\n\n async openConnection (peerId: PeerId, options: AbortOptions = {}): Promise {\n log('dial to %p', peerId)\n const existingConnections = this.getConnections(peerId)\n\n if (existingConnections.length > 0) {\n log('had an existing connection to %p', peerId)\n\n return existingConnections[0]\n }\n\n let timeoutController: TimeoutController | undefined\n\n if (options?.signal == null) {\n timeoutController = new TimeoutController(this.dialTimeout)\n options.signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n const connection = await this.dialer.dial(peerId, options)\n let peerConnections = this.connections.get(peerId.toString())\n\n if (peerConnections == null) {\n peerConnections = []\n this.connections.set(peerId.toString(), peerConnections)\n }\n\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false\n\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true\n }\n }\n\n if (!trackedConnection) {\n peerConnections.push(connection)\n }\n\n return connection\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n }\n }\n\n async closeConnections (peerId: PeerId): Promise {\n const connections = this.connections.get(peerId.toString()) ?? []\n\n await Promise.all(\n connections.map(async connection => {\n return await connection.close()\n })\n )\n }\n\n /**\n * Get all open connections with a peer\n */\n getAll (peerId: PeerId): Connection[] {\n if (!isPeerId(peerId)) {\n throw errCode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const id = peerId.toString()\n const connections = this.connections.get(id)\n\n // Return all open connections\n if (connections != null) {\n return connections.filter(connection => connection.stat.status === STATUS.OPEN)\n }\n\n return []\n }\n\n /**\n * If the event loop is slow, maybe close a connection\n */\n _onLatencyMeasure (evt: CustomEvent) {\n const { detail: summary } = evt\n\n this._checkMaxLimit('maxEventLoopDelay', summary.avgMs, 1)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * If the `value` of `name` has exceeded its limit, maybe close a connection\n */\n async _checkMaxLimit (name: keyof ConnectionManagerInit, value: number, toPrune: number = 1) {\n const limit = this.opts[name]\n log.trace('checking limit of %s. current value: %d of %d', name, value, limit)\n if (value > limit) {\n log('%s: limit exceeded: %p, %d/%d, pruning %d connection(s)', this.components.getPeerId(), name, value, limit, toPrune)\n await this._maybePruneConnections(toPrune)\n }\n }\n\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async _maybePruneConnections (toPrune: number) {\n const connections = this.getConnections()\n\n if (connections.length <= this.opts.minConnections || toPrune < 1) {\n return\n }\n\n const peerValues = new PeerMap()\n\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer\n\n if (peerValues.has(remotePeer)) {\n continue\n }\n\n const tags = await this.components.getPeerStore().getTags(remotePeer)\n\n // sum all tag values\n peerValues.set(remotePeer, tags.reduce((acc, curr) => {\n return acc + curr.value\n }, 0))\n }\n\n // sort by value, lowest to highest\n const sortedConnections = connections.sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0\n const peerBValue = peerValues.get(b.remotePeer) ?? 0\n\n if (peerAValue > peerBValue) {\n return 1\n }\n\n if (peerAValue < peerBValue) {\n return -1\n }\n\n return 0\n })\n\n // close some connections\n const toClose = []\n\n for (const connection of sortedConnections) {\n log('too many connections open - closing a connection to %p', connection.remotePeer)\n toClose.push(connection)\n\n if (toClose.length === toPrune) {\n break\n }\n }\n\n // close connections\n await Promise.all(\n toClose.map(async connection => {\n try {\n await connection.close()\n } catch (err) {\n log.error(err)\n }\n\n // TODO: should not need to invoke this manually\n this.onDisconnect(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n })\n )\n }\n}\n","import { logger } from '@libp2p/logger'\nimport mergeOptions from 'merge-options'\n// @ts-expect-error retimer does not have types\nimport retimer from 'retimer'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:connection-manager:auto-dialler')\n\nexport interface AutoDiallerInit {\n /**\n * Should preemptively guarantee connections are above the low watermark\n */\n enabled?: boolean\n\n /**\n * The minimum number of connections to avoid pruning\n */\n minConnections?: number\n\n /**\n * How often, in milliseconds, it should preemptively guarantee connections are above the low watermark\n */\n autoDialInterval?: number\n}\n\nconst defaultOptions: Partial = {\n enabled: true,\n minConnections: 0,\n autoDialInterval: 10000\n}\n\nexport class AutoDialler implements Startable {\n private readonly components: Components\n private readonly options: Required\n private running: boolean\n private autoDialTimeout?: ReturnType\n\n /**\n * Proactively tries to connect to known peers stored in the PeerStore.\n * It will keep the number of connections below the upper limit and sort\n * the peers to connect based on wether we know their keys and protocols.\n */\n constructor (components: Components, init: AutoDiallerInit) {\n this.components = components\n this.options = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)\n this.running = false\n this._autoDial = this._autoDial.bind(this)\n\n log('options: %j', this.options)\n }\n\n isStarted () {\n return this.running\n }\n\n /**\n * Starts the auto dialer\n */\n async start () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = true\n\n void this._autoDial().catch(err => {\n log.error('could start autodial', err)\n })\n\n log('started')\n }\n\n /**\n * Stops the auto dialler\n */\n async stop () {\n if (!this.options.enabled) {\n log('not enabled')\n return\n }\n\n this.running = false\n\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n log('stopped')\n }\n\n async _autoDial () {\n if (this.autoDialTimeout != null) {\n this.autoDialTimeout.clear()\n }\n\n const minConnections = this.options.minConnections\n\n // Already has enough connections\n if (this.components.getConnectionManager().getConnections().length >= minConnections) {\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n\n return\n }\n\n // Sort peers on whether we know protocols or public keys for them\n const allPeers = await this.components.getPeerStore().all()\n\n const peers = await pipe(\n // shuffle the peers\n allPeers.sort(() => Math.random() > 0.5 ? 1 : -1),\n (source) => filter(source, (peer) => !peer.id.equals(this.components.getPeerId())),\n (source) => sort(source, (a, b) => {\n if (b.protocols.length > a.protocols.length) {\n return 1\n } else if (b.id.publicKey != null && a.id.publicKey == null) {\n return 1\n }\n return -1\n }),\n async (source) => await all(source)\n )\n\n for (let i = 0; this.running && i < peers.length && this.components.getConnectionManager().getConnections().length < minConnections; i++) {\n // Connection Manager was stopped during async dial\n if (!this.running) {\n return\n }\n\n const peer = peers[i]\n\n if (this.components.getConnectionManager().getConnections(peer.id).length === 0) {\n log('connecting to a peerStore stored peer %p', peer.id)\n try {\n await this.components.getConnectionManager().openConnection(peer.id)\n } catch (err: any) {\n log.error('could not connect to peerStore stored peer', err)\n }\n }\n }\n\n // Connection Manager was stopped\n if (!this.running) {\n return\n }\n\n this.autoDialTimeout = retimer(this._autoDial, this.options.autoDialInterval)\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface CircuitRelay {\n type?: CircuitRelay.Type\n srcPeer?: CircuitRelay.Peer\n dstPeer?: CircuitRelay.Peer\n code?: CircuitRelay.Status\n}\n\nexport namespace CircuitRelay {\n export enum Status {\n SUCCESS = 'SUCCESS',\n HOP_SRC_ADDR_TOO_LONG = 'HOP_SRC_ADDR_TOO_LONG',\n HOP_DST_ADDR_TOO_LONG = 'HOP_DST_ADDR_TOO_LONG',\n HOP_SRC_MULTIADDR_INVALID = 'HOP_SRC_MULTIADDR_INVALID',\n HOP_DST_MULTIADDR_INVALID = 'HOP_DST_MULTIADDR_INVALID',\n HOP_NO_CONN_TO_DST = 'HOP_NO_CONN_TO_DST',\n HOP_CANT_DIAL_DST = 'HOP_CANT_DIAL_DST',\n HOP_CANT_OPEN_DST_STREAM = 'HOP_CANT_OPEN_DST_STREAM',\n HOP_CANT_SPEAK_RELAY = 'HOP_CANT_SPEAK_RELAY',\n HOP_CANT_RELAY_TO_SELF = 'HOP_CANT_RELAY_TO_SELF',\n STOP_SRC_ADDR_TOO_LONG = 'STOP_SRC_ADDR_TOO_LONG',\n STOP_DST_ADDR_TOO_LONG = 'STOP_DST_ADDR_TOO_LONG',\n STOP_SRC_MULTIADDR_INVALID = 'STOP_SRC_MULTIADDR_INVALID',\n STOP_DST_MULTIADDR_INVALID = 'STOP_DST_MULTIADDR_INVALID',\n STOP_RELAY_REFUSED = 'STOP_RELAY_REFUSED',\n MALFORMED_MESSAGE = 'MALFORMED_MESSAGE'\n }\n\n enum __StatusValues {\n SUCCESS = 100,\n HOP_SRC_ADDR_TOO_LONG = 220,\n HOP_DST_ADDR_TOO_LONG = 221,\n HOP_SRC_MULTIADDR_INVALID = 250,\n HOP_DST_MULTIADDR_INVALID = 251,\n HOP_NO_CONN_TO_DST = 260,\n HOP_CANT_DIAL_DST = 261,\n HOP_CANT_OPEN_DST_STREAM = 262,\n HOP_CANT_SPEAK_RELAY = 270,\n HOP_CANT_RELAY_TO_SELF = 280,\n STOP_SRC_ADDR_TOO_LONG = 320,\n STOP_DST_ADDR_TOO_LONG = 321,\n STOP_SRC_MULTIADDR_INVALID = 350,\n STOP_DST_MULTIADDR_INVALID = 351,\n STOP_RELAY_REFUSED = 390,\n MALFORMED_MESSAGE = 400\n }\n\n export namespace Status {\n export const codec = () => {\n return enumeration(__StatusValues)\n }\n }\n\n export enum Type {\n HOP = 'HOP',\n STOP = 'STOP',\n STATUS = 'STATUS',\n CAN_HOP = 'CAN_HOP'\n }\n\n enum __TypeValues {\n HOP = 1,\n STOP = 2,\n STATUS = 3,\n CAN_HOP = 4\n }\n\n export namespace Type {\n export const codec = () => {\n return enumeration(__TypeValues)\n }\n }\n\n export interface Peer {\n id: Uint8Array\n addrs: Uint8Array[]\n }\n\n export namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.id != null) {\n writer.uint32(10)\n writer.bytes(obj.id)\n } else {\n throw new Error('Protocol error: required field \"id\" was not found in object')\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n writer.uint32(18)\n writer.bytes(value)\n }\n } else {\n throw new Error('Protocol error: required field \"addrs\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.addrs = obj.addrs ?? []\n obj.addrs.push(reader.bytes())\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n obj.addrs = obj.addrs ?? []\n\n if (obj.id == null) {\n throw new Error('Protocol error: value for required field \"id\" was not found in protobuf')\n }\n\n if (obj.addrs == null) {\n throw new Error('Protocol error: value for required field \"addrs\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.type != null) {\n writer.uint32(8)\n CircuitRelay.Type.codec().encode(obj.type, writer)\n }\n\n if (obj.srcPeer != null) {\n writer.uint32(18)\n CircuitRelay.Peer.codec().encode(obj.srcPeer, writer)\n }\n\n if (obj.dstPeer != null) {\n writer.uint32(26)\n CircuitRelay.Peer.codec().encode(obj.dstPeer, writer)\n }\n\n if (obj.code != null) {\n writer.uint32(32)\n CircuitRelay.Status.codec().encode(obj.code, writer)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.type = CircuitRelay.Type.codec().decode(reader)\n break\n case 2:\n obj.srcPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 3:\n obj.dstPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())\n break\n case 4:\n obj.code = CircuitRelay.Status.codec().decode(reader)\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: CircuitRelay): Uint8Array => {\n return encodeMessage(obj, CircuitRelay.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): CircuitRelay => {\n return decodeMessage(buf, CircuitRelay.codec())\n }\n}\n","import { abortableSource } from 'abortable-iterator'\nimport { logger } from '@libp2p/logger'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { MultiaddrConnection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:stream:converter')\n\nexport interface Timeline {\n /**\n * Connection opening timestamp\n */\n open: number\n\n /**\n * Connection upgraded timestamp\n */\n upgraded?: number\n\n /**\n * Connection closed timestamp\n */\n close?: number\n}\n\ninterface StreamOptions {\n signal?: AbortSignal\n\n}\n\ninterface StreamProperties {\n stream: Duplex\n remoteAddr: Multiaddr\n localAddr: Multiaddr\n}\n\n/**\n * Convert a duplex iterable into a MultiaddrConnection.\n * https://github.com/libp2p/interface-transport#multiaddrconnection\n */\nexport function streamToMaConnection (props: StreamProperties, options: StreamOptions = {}) {\n const { stream, remoteAddr } = props\n const { sink, source } = stream\n\n const mapSource = (async function * () {\n for await (const list of source) {\n yield * list\n }\n }())\n\n const maConn: MultiaddrConnection = {\n async sink (source) {\n if (options.signal != null) {\n source = abortableSource(source, options.signal)\n }\n\n try {\n await sink(source)\n await close()\n } catch (err: any) {\n // If aborted we can safely ignore\n if (err.type !== 'aborted') {\n // If the source errored the socket will already have been destroyed by\n // toIterable.duplex(). If the socket errored it will already be\n // destroyed. There's nothing to do here except log the error & return.\n log(err)\n }\n }\n },\n source: (options.signal != null) ? abortableSource(mapSource, options.signal) : mapSource,\n remoteAddr,\n /** @type {Timeline} */\n timeline: { open: Date.now(), close: undefined },\n async close () {\n await sink(async function * () {\n yield new Uint8Array(0)\n }())\n await close()\n }\n }\n\n async function close () {\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now()\n }\n return await Promise.resolve()\n }\n\n return maConn\n}\n","\nexport const RELAY_CODEC = '/libp2p/circuit/relay/0.1.0'\n","import { Multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { StreamHandler } from './stream-handler.js'\n\n/**\n * Write a response\n */\nfunction writeResponse (streamHandler: StreamHandler, status: CircuitRelay.Status) {\n streamHandler.write({\n type: CircuitRelay.Type.STATUS,\n code: status\n })\n}\n\n/**\n * Validate incomming HOP/STOP message\n */\nexport function validateAddrs (msg: CircuitRelay, streamHandler: StreamHandler) {\n try {\n if (msg.dstPeer?.addrs != null) {\n msg.dstPeer.addrs.forEach((addr) => {\n return new Multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_DST_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_DST_MULTIADDR_INVALID)\n throw err\n }\n\n try {\n if (msg.srcPeer?.addrs != null) {\n msg.srcPeer.addrs.forEach((addr) => {\n return new Multiaddr(addr)\n })\n }\n } catch (err: any) {\n writeResponse(streamHandler, msg.type === CircuitRelay.Type.HOP\n ? CircuitRelay.Status.HOP_SRC_MULTIADDR_INVALID\n : CircuitRelay.Status.STOP_SRC_MULTIADDR_INVALID)\n throw err\n }\n}\n","import { logger } from '@libp2p/logger'\nimport * as lp from 'it-length-prefixed'\nimport { Handshake, handshake } from 'it-handshake'\nimport { CircuitRelay } from '../pb/index.js'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { Source } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stream-handler')\n\nexport interface StreamHandlerOptions {\n /**\n * A duplex iterable\n */\n stream: Stream\n\n /**\n * max bytes length of message\n */\n maxLength?: number\n}\n\nexport class StreamHandler {\n private readonly stream: Stream\n private readonly shake: Handshake\n private readonly decoder: Source\n\n constructor (options: StreamHandlerOptions) {\n const { stream, maxLength = 4096 } = options\n\n this.stream = stream\n this.shake = handshake(this.stream)\n this.decoder = lp.decode.fromReader(this.shake.reader, { maxDataLength: maxLength })\n }\n\n /**\n * Read and decode message\n */\n async read () {\n // @ts-expect-error FIXME is a source, needs to be a generator\n const msg = await this.decoder.next()\n\n if (msg.value != null) {\n const value = CircuitRelay.decode(msg.value)\n log('read message type', value.type)\n return value\n }\n\n log('read received no value, closing stream')\n // End the stream, we didn't get data\n this.close()\n }\n\n /**\n * Encode and write array of buffers\n */\n write (msg: CircuitRelay) {\n log('write message type %s', msg.type)\n this.shake.write(lp.encode.single(CircuitRelay.encode(msg)))\n }\n\n /**\n * Return the handshake rest stream and invalidate handler\n */\n rest () {\n this.shake.rest()\n return this.shake.stream\n }\n\n /**\n * @param {CircuitRelay} msg - An unencoded CircuitRelay protobuf message\n */\n end (msg: CircuitRelay) {\n this.write(msg)\n this.close()\n }\n\n /**\n * Close the stream\n */\n close () {\n log('closing the stream')\n void this.rest().sink([]).catch(err => {\n log.error(err)\n })\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { validateAddrs } from './utils.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:stop')\n\nexport interface HandleStopOptions {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n}\n\n/**\n * Handles incoming STOP requests\n */\nexport function handleStop (options: HandleStopOptions): Duplex | undefined {\n const {\n connection,\n request,\n streamHandler\n } = options\n\n // Validate the STOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid stop request via peer %p %o', connection.remotePeer, err)\n return\n }\n\n // The request is valid\n log('stop request is valid')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n\n return streamHandler.rest()\n}\n\nexport interface StopOptions extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Creates a STOP request\n */\nexport async function stop (options: StopOptions) {\n const {\n connection,\n request,\n signal\n } = options\n\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n log('starting stop request to %p', connection.remotePeer)\n const streamHandler = new StreamHandler({ stream })\n\n streamHandler.write(request)\n const response = await streamHandler.read()\n\n if (response == null) {\n streamHandler.close()\n return\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('stop request to %p was successful', connection.remotePeer)\n return streamHandler.rest()\n }\n\n log('stop request failed with code %d', response.code)\n streamHandler.close()\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { validateAddrs } from './utils.js'\nimport { StreamHandler } from './stream-handler.js'\nimport { CircuitRelay as CircuitPB } from '../pb/index.js'\nimport { pipe } from 'it-pipe'\nimport { codes as Errors } from '../../errors.js'\nimport { stop } from './stop.js'\nimport { RELAY_CODEC } from '../multicodec.js'\nimport type { Connection } from '@libp2p/interface-connection'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport type { Duplex } from 'it-stream-types'\nimport type { Circuit } from '../transport.js'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst log = logger('libp2p:circuit:hop')\n\nexport interface HopRequest {\n connection: Connection\n request: CircuitPB\n streamHandler: StreamHandler\n circuit: Circuit\n connectionManager: ConnectionManager\n}\n\nexport async function handleHop (hopRequest: HopRequest): Promise {\n const {\n connection,\n request,\n streamHandler,\n circuit,\n connectionManager\n } = hopRequest\n\n // Ensure hop is enabled\n if (!circuit.hopEnabled()) {\n log('HOP request received but we are not acting as a relay')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n }\n\n // Validate the HOP request has the required input\n try {\n validateAddrs(request, streamHandler)\n } catch (err: any) {\n log.error('invalid hop request via peer %p %o', connection.remotePeer, err)\n\n return\n }\n\n if (request.dstPeer == null) {\n log('HOP request received but we do not receive a dstPeer')\n return\n }\n\n // Get the connection to the destination (stop) peer\n const destinationPeer = peerIdFromBytes(request.dstPeer.id)\n\n const destinationConnections = connectionManager.getConnections(destinationPeer)\n if (destinationConnections.length === 0 && !circuit.hopActive()) {\n log('HOP request received but we are not connected to the destination peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // TODO: Handle being an active relay\n if (destinationConnections.length === 0) {\n log('did not have connection to remote peer')\n return streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.HOP_NO_CONN_TO_DST\n })\n }\n\n // Handle the incoming HOP request by performing a STOP request\n const stopRequest = {\n type: CircuitPB.Type.STOP,\n dstPeer: request.dstPeer,\n srcPeer: request.srcPeer\n }\n\n let destinationStream: Duplex\n try {\n log('performing STOP request')\n const result = await stop({\n connection: destinationConnections[0],\n request: stopRequest\n })\n\n if (result == null) {\n throw new Error('Could not stop')\n }\n\n destinationStream = result\n } catch (err: any) {\n log.error(err)\n\n return\n }\n\n log('hop request from %p is valid', connection.remotePeer)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.SUCCESS\n })\n const sourceStream = streamHandler.rest()\n\n log('creating related connections')\n // Short circuit the two streams to create the relayed connection\n return await pipe(\n sourceStream,\n destinationStream,\n sourceStream\n )\n}\n\nexport interface HopConfig extends AbortOptions {\n connection: Connection\n request: CircuitPB\n}\n\n/**\n * Performs a HOP request to a relay peer, to request a connection to another\n * peer. A new, virtual, connection will be created between the two via the relay.\n */\nexport async function hop (options: HopConfig): Promise> {\n const {\n connection,\n request,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write(request)\n\n const response = await streamHandler.read()\n\n if (response == null) {\n throw errCode(new Error('HOP request had no response'), Errors.ERR_HOP_REQUEST_FAILED)\n }\n\n if (response.code === CircuitPB.Status.SUCCESS) {\n log('hop request was successful')\n\n return streamHandler.rest()\n }\n\n log('hop request failed with code %d, closing stream', response.code)\n streamHandler.close()\n\n throw errCode(new Error(`HOP request failed with code \"${response.code ?? 'unknown'}\"`), Errors.ERR_HOP_REQUEST_FAILED)\n}\n\nexport interface CanHopOptions extends AbortOptions {\n connection: Connection\n}\n\n/**\n * Performs a CAN_HOP request to a relay peer, in order to understand its capabilities\n */\nexport async function canHop (options: CanHopOptions) {\n const {\n connection,\n signal\n } = options\n\n // Create a new stream to the relay\n const stream = await connection.newStream(RELAY_CODEC, {\n signal\n })\n\n // Send the HOP request\n const streamHandler = new StreamHandler({ stream })\n streamHandler.write({\n type: CircuitPB.Type.CAN_HOP\n })\n\n const response = await streamHandler.read()\n await streamHandler.close()\n\n if (response == null || response.code !== CircuitPB.Status.SUCCESS) {\n return false\n }\n\n return true\n}\n\nexport interface HandleCanHopOptions {\n connection: Connection\n streamHandler: StreamHandler\n circuit: Circuit\n}\n\n/**\n * Creates an unencoded CAN_HOP response based on the Circuits configuration\n */\nexport function handleCanHop (options: HandleCanHopOptions) {\n const {\n connection,\n streamHandler,\n circuit\n } = options\n const canHop = circuit.hopEnabled()\n log('can hop (%s) request from %p', canHop, connection.remotePeer)\n streamHandler.end({\n type: CircuitPB.Type.STATUS,\n code: canHop ? CircuitPB.Status.SUCCESS : CircuitPB.Status.HOP_CANT_SPEAK_RELAY\n })\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mafmt from '@multiformats/mafmt'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { CircuitRelay as CircuitPB } from './pb/index.js'\nimport { codes } from '../errors.js'\nimport { streamToMaConnection } from '@libp2p/utils/stream-to-ma-conn'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { createListener } from './listener.js'\nimport { handleCanHop, handleHop, hop } from './circuit/hop.js'\nimport { handleStop } from './circuit/stop.js'\nimport { StreamHandler } from './circuit/stream-handler.js'\nimport { symbol } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { Components, Initializable } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Listener, Transport, CreateListenerOptions, ConnectionHandler } from '@libp2p/interface-transport'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { RelayConfig } from '../index.js'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\n\nconst log = logger('libp2p:circuit')\n\nexport class Circuit implements Transport, Initializable {\n private handler?: ConnectionHandler\n private components: Components = new Components()\n private readonly _init: RelayConfig\n\n constructor (init: RelayConfig) {\n this._init = init\n }\n\n init (components: Components): void {\n this.components = components\n void this.components.getRegistrar().handle(RELAY_CODEC, (data) => {\n void this._onProtocol(data).catch(err => {\n log.error(err)\n })\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n hopEnabled () {\n return true\n }\n\n hopActive () {\n return true\n }\n\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return 'libp2p/circuit-relay-v1'\n }\n\n async _onProtocol (data: IncomingStreamData) {\n const { connection, stream } = data\n const controller = new TimeoutController(this._init.hop.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n try {\n const source = abortableDuplex(stream, controller.signal)\n const streamHandler = new StreamHandler({\n stream: {\n ...stream,\n ...source\n }\n })\n const request = await streamHandler.read()\n\n if (request == null) {\n log('request was invalid, could not read from stream')\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n\n let virtualConnection: Duplex | undefined\n\n switch (request.type) {\n case CircuitPB.Type.CAN_HOP: {\n log('received CAN_HOP request from %p', connection.remotePeer)\n await handleCanHop({ circuit: this, connection, streamHandler })\n break\n }\n case CircuitPB.Type.HOP: {\n log('received HOP request from %p', connection.remotePeer)\n await handleHop({\n connection,\n request,\n streamHandler,\n circuit: this,\n connectionManager: this.components.getConnectionManager()\n })\n break\n }\n case CircuitPB.Type.STOP: {\n log('received STOP request from %p', connection.remotePeer)\n virtualConnection = await handleStop({\n connection,\n request,\n streamHandler\n })\n break\n }\n default: {\n log('Request of type %s not supported', request.type)\n streamHandler.write({\n type: CircuitPB.Type.STATUS,\n code: CircuitPB.Status.MALFORMED_MESSAGE\n })\n streamHandler.close()\n return\n }\n }\n\n if (virtualConnection != null) {\n const remoteAddr = connection.remoteAddr\n .encapsulate('/p2p-circuit')\n .encapsulate(new Multiaddr(request.dstPeer?.addrs[0]))\n const localAddr = new Multiaddr(request.srcPeer?.addrs[0])\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr,\n localAddr\n })\n const type = request.type === CircuitPB.Type.HOP ? 'relay' : 'inbound'\n log('new %s connection %s', type, maConn.remoteAddr)\n\n const conn = await this.components.getUpgrader().upgradeInbound(maConn)\n log('%s connection %s upgraded', type, maConn.remoteAddr)\n\n if (this.handler != null) {\n this.handler(conn)\n }\n }\n } finally {\n controller.clear()\n }\n }\n\n /**\n * Dial a peer over a relay\n */\n async dial (ma: Multiaddr, options: AbortOptions = {}): Promise {\n // Check the multiaddr to see if it contains a relay and a destination peer\n const addrs = ma.toString().split('/p2p-circuit')\n const relayAddr = new Multiaddr(addrs[0])\n const destinationAddr = new Multiaddr(addrs[addrs.length - 1])\n const relayId = relayAddr.getPeerId()\n const destinationId = destinationAddr.getPeerId()\n\n if (relayId == null || destinationId == null) {\n const errMsg = 'Circuit relay dial failed as addresses did not have peer id'\n log.error(errMsg)\n throw errCode(new Error(errMsg), codes.ERR_RELAYED_DIAL)\n }\n\n const relayPeer = peerIdFromString(relayId)\n const destinationPeer = peerIdFromString(destinationId)\n\n let disconnectOnFailure = false\n const relayConnections = this.components.getConnectionManager().getConnections(relayPeer)\n let relayConnection = relayConnections[0]\n\n if (relayConnection == null) {\n await this.components.getPeerStore().addressBook.add(relayPeer, [relayAddr])\n relayConnection = await this.components.getConnectionManager().openConnection(relayPeer, options)\n disconnectOnFailure = true\n }\n\n try {\n const virtualConnection = await hop({\n ...options,\n connection: relayConnection,\n request: {\n type: CircuitPB.Type.HOP,\n srcPeer: {\n id: this.components.getPeerId().toBytes(),\n addrs: this.components.getAddressManager().getAddresses().map(addr => addr.bytes)\n },\n dstPeer: {\n id: destinationPeer.toBytes(),\n addrs: [new Multiaddr(destinationAddr).bytes]\n }\n }\n })\n\n const localAddr = relayAddr.encapsulate(`/p2p-circuit/p2p/${this.components.getPeerId().toString()}`)\n const maConn = streamToMaConnection({\n stream: virtualConnection,\n remoteAddr: ma,\n localAddr\n })\n log('new outbound connection %s', maConn.remoteAddr)\n\n return await this.components.getUpgrader().upgradeOutbound(maConn)\n } catch (err: any) {\n log.error('Circuit relay dial failed', err)\n disconnectOnFailure && await relayConnection.close()\n throw err\n }\n }\n\n /**\n * Create a listener\n */\n createListener (options: CreateListenerOptions): Listener {\n // Called on successful HOP and STOP requests\n this.handler = options.handler\n\n return createListener({\n connectionManager: this.components.getConnectionManager(),\n peerStore: this.components.getPeerStore()\n })\n }\n\n /**\n * Filter check for all Multiaddrs that this transport can dial on\n *\n * @param {Multiaddr[]} multiaddrs\n * @returns {Multiaddr[]}\n */\n filter (multiaddrs: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n return mafmt.Circuit.matches(ma)\n })\n }\n}\n","import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { Listener } from '@libp2p/interface-transport'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface ListenerOptions {\n peerStore: PeerStore\n connectionManager: ConnectionManager\n}\n\nexport function createListener (options: ListenerOptions): Listener {\n const listeningAddrs = new Map()\n\n /**\n * Add swarm handler and listen for incoming connections\n */\n async function listen (addr: Multiaddr): Promise {\n const addrString = addr.toString().split('/p2p-circuit').find(a => a !== '')\n const ma = new Multiaddr(addrString)\n\n const relayPeerStr = ma.getPeerId()\n\n if (relayPeerStr == null) {\n throw new Error('Could not determine relay peer from multiaddr')\n }\n\n const relayPeerId = peerIdFromString(relayPeerStr)\n\n await options.peerStore.addressBook.add(relayPeerId, [ma])\n\n const relayConn = await options.connectionManager.openConnection(relayPeerId)\n const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit')\n\n listeningAddrs.set(relayConn.remotePeer.toString(), relayedAddr)\n listener.dispatchEvent(new CustomEvent('listening'))\n }\n\n /**\n * Get fixed up multiaddrs\n *\n * NOTE: This method will grab the peers multiaddrs and expand them such that:\n *\n * a) If it's an existing /p2p-circuit address for a specific relay i.e.\n * `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the\n * address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where\n * `QmPeer` is this peers id\n * b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit\n * addr, such when dialing over a relay with this address, it will create the circuit using\n * the encapsulated transport address. This is useful when for example, a peer should only\n * be dialed over TCP rather than any other transport\n *\n * @returns {Multiaddr[]}\n */\n function getAddrs () {\n const addrs = []\n for (const addr of listeningAddrs.values()) {\n addrs.push(addr)\n }\n return addrs\n }\n\n const listener: Listener = Object.assign(new EventEmitter(), {\n close: async () => await Promise.resolve(),\n listen,\n getAddrs\n })\n\n // Remove listeningAddrs when a peer disconnects\n options.connectionManager.addEventListener('peer:disconnect', (evt) => {\n const { detail: connection } = evt\n const deleted = listeningAddrs.delete(connection.remotePeer.toString())\n\n if (deleted) {\n // Announce listen addresses change\n listener.dispatchEvent(new CustomEvent('close'))\n }\n })\n\n return listener\n}\n","import { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\n\n/**\n * Convert a namespace string into a cid\n */\nexport async function namespaceToCid (namespace: string): Promise {\n const bytes = new TextEncoder().encode(namespace)\n const hash = await sha256.digest(bytes)\n\n return CID.createV0(hash)\n}\n","const minute = 60 * 1000\n\n/**\n * Delay before HOP relay service is advertised on the network\n */\nexport const ADVERTISE_BOOT_DELAY = 15 * minute\n\n/**\n * Delay Between HOP relay service advertisements on the network\n */\nexport const ADVERTISE_TTL = 30 * minute\n\n/**\n * Multicodec code\n */\nexport const CIRCUIT_PROTO_CODE = 290\n\n/**\n * PeerStore metadaBook key for HOP relay service\n */\nexport const HOP_METADATA_KEY = 'hop_relay'\n\n/**\n * PeerStore metadaBook value for HOP relay service\n */\nexport const HOP_METADATA_VALUE = 'true'\n\n/**\n * Relay HOP relay service namespace for discovery\n */\nexport const RELAY_RENDEZVOUS_NS = '/libp2p/relay'\n","import { logger } from '@libp2p/logger'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RELAY_CODEC } from './multicodec.js'\nimport { canHop } from './circuit/hop.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n CIRCUIT_PROTO_CODE,\n HOP_METADATA_KEY,\n HOP_METADATA_VALUE,\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AddressSorter, PeerProtocolsChangeData } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Components } from '@libp2p/components'\nimport sort from 'it-sort'\nimport all from 'it-all'\nimport { pipe } from 'it-pipe'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\n\nconst log = logger('libp2p:auto-relay')\n\nconst noop = () => {}\n\nexport interface AutoRelayInit {\n addressSorter?: AddressSorter\n maxListeners?: number\n onError?: (error: Error, msg?: string) => void\n}\n\nexport class AutoRelay {\n private readonly components: Components\n private readonly addressSorter: AddressSorter\n private readonly maxListeners: number\n private readonly listenRelays: Set\n private readonly onError: (error: Error, msg?: string) => void\n\n constructor (components: Components, init: AutoRelayInit) {\n this.components = components\n this.addressSorter = init.addressSorter ?? publicAddressesFirst\n this.maxListeners = init.maxListeners ?? 1\n this.listenRelays = new Set()\n this.onError = init.onError ?? noop\n\n this._onProtocolChange = this._onProtocolChange.bind(this)\n this._onPeerDisconnected = this._onPeerDisconnected.bind(this)\n\n this.components.getPeerStore().addEventListener('change:protocols', (evt) => {\n void this._onProtocolChange(evt).catch(err => {\n log.error(err)\n })\n })\n this.components.getConnectionManager().addEventListener('peer:disconnect', this._onPeerDisconnected)\n }\n\n /**\n * Check if a peer supports the relay protocol.\n * If the protocol is not supported, check if it was supported before and remove it as a listen relay.\n * If the protocol is supported, check if the peer supports **HOP** and add it as a listener if\n * inside the threshold.\n */\n async _onProtocolChange (evt: CustomEvent) {\n const {\n peerId,\n protocols\n } = evt.detail\n const id = peerId.toString()\n\n // Check if it has the protocol\n const hasProtocol = protocols.find(protocol => protocol === RELAY_CODEC)\n\n // If no protocol, check if we were keeping the peer before as a listenRelay\n if (hasProtocol == null) {\n if (this.listenRelays.has(id)) {\n await this._removeListenRelay(id)\n }\n\n return\n }\n\n if (this.listenRelays.has(id)) {\n return\n }\n\n // If protocol, check if can hop, store info in the metadataBook and listen on it\n try {\n const connections = this.components.getConnectionManager().getConnections(peerId)\n\n if (connections.length === 0) {\n return\n }\n\n const connection = connections[0]\n\n // Do not hop on a relayed connection\n if (connection.remoteAddr.protoCodes().includes(CIRCUIT_PROTO_CODE)) {\n log(`relayed connection to ${id} will not be used to hop on`)\n return\n }\n\n const supportsHop = await canHop({ connection })\n\n if (supportsHop) {\n await this.components.getPeerStore().metadataBook.setValue(peerId, HOP_METADATA_KEY, uint8ArrayFromString(HOP_METADATA_VALUE))\n await this._addListenRelay(connection, id)\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n /**\n * Peer disconnects\n */\n _onPeerDisconnected (evt: CustomEvent) {\n const connection = evt.detail\n const peerId = connection.remotePeer\n const id = peerId.toString()\n\n // Not listening on this relay\n if (!this.listenRelays.has(id)) {\n return\n }\n\n this._removeListenRelay(id).catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Attempt to listen on the given relay connection\n */\n async _addListenRelay (connection: Connection, id: string): Promise {\n try {\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n // Get peer known addresses and sort them with public addresses first\n const remoteAddrs = await pipe(\n await this.components.getPeerStore().addressBook.get(connection.remotePeer),\n (source) => sort(source, this.addressSorter),\n async (source) => await all(source)\n )\n\n // Attempt to listen on relay\n const result = await Promise.all(\n remoteAddrs.map(async addr => {\n try {\n let multiaddr = addr.multiaddr\n\n if (multiaddr.getPeerId() == null) {\n multiaddr = multiaddr.encapsulate(`/p2p/${connection.remotePeer.toString()}`)\n }\n\n multiaddr = multiaddr.encapsulate('/p2p-circuit')\n\n // Announce multiaddrs will update on listen success by TransportManager event being triggered\n await this.components.getTransportManager().listen([multiaddr])\n return true\n } catch (err: any) {\n log.error('error listening on circuit address', err)\n this.onError(err)\n }\n\n return false\n })\n )\n\n if (result.includes(true)) {\n this.listenRelays.add(id)\n }\n } catch (err: any) {\n this.onError(err)\n this.listenRelays.delete(id)\n }\n }\n\n /**\n * Remove listen relay\n */\n async _removeListenRelay (id: string) {\n if (this.listenRelays.delete(id)) {\n // TODO: this should be responsibility of the connMgr\n await this._listenOnAvailableHopRelays([id])\n }\n }\n\n /**\n * Try to listen on available hop relay connections.\n * The following order will happen while we do not have enough relays.\n * 1. Check the metadata store for known relays, try to listen on the ones we are already connected.\n * 2. Dial and try to listen on the peers we know that support hop but are not connected.\n * 3. Search the network.\n */\n async _listenOnAvailableHopRelays (peersToIgnore: string[] = []) {\n // TODO: The peer redial issue on disconnect should be handled by connection gating\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n\n const knownHopsToDial = []\n const peers = await this.components.getPeerStore().all()\n\n // Check if we have known hop peers to use and attempt to listen on the already connected\n for (const { id, metadata } of peers) {\n const idStr = id.toString()\n\n // Continue to next if listening on this or peer to ignore\n if (this.listenRelays.has(idStr)) {\n continue\n }\n\n if (peersToIgnore.includes(idStr)) {\n continue\n }\n\n const supportsHop = metadata.get(HOP_METADATA_KEY)\n\n // Continue to next if it does not support Hop\n if ((supportsHop == null) || uint8ArrayToString(supportsHop) !== HOP_METADATA_VALUE) {\n continue\n }\n\n const connections = this.components.getConnectionManager().getConnections(id)\n\n // If not connected, store for possible later use.\n if (connections.length === 0) {\n knownHopsToDial.push(id)\n continue\n }\n\n await this._addListenRelay(connections[0], idStr)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to listen on known peers that are not connected\n for (const peerId of knownHopsToDial) {\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n\n // Try to find relays to hop on the network\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n for await (const provider of this.components.getContentRouting().findProviders(cid)) {\n if (provider.multiaddrs.length === 0) {\n continue\n }\n\n const peerId = provider.id\n await this.components.getPeerStore().addressBook.add(peerId, provider.multiaddrs)\n\n await this._tryToListenOnRelay(peerId)\n\n // Check if already listening on enough relays\n if (this.listenRelays.size >= this.maxListeners) {\n return\n }\n }\n } catch (err: any) {\n this.onError(err)\n }\n }\n\n async _tryToListenOnRelay (peerId: PeerId) {\n try {\n const connection = await this.components.getConnectionManager().openConnection(peerId)\n await this._addListenRelay(connection, peerId.toString())\n } catch (err: any) {\n log.error('Could not use %p as relay', peerId, err)\n this.onError(err, `could not connect and listen on known hop relay ${peerId.toString()}`)\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { codes } from '../errors.js'\nimport {\n setDelayedInterval,\n clearDelayedInterval\n// @ts-expect-error set-delayed-interval does not export types\n} from 'set-delayed-interval'\nimport { AutoRelay } from './auto-relay.js'\nimport { namespaceToCid } from './utils.js'\nimport {\n RELAY_RENDEZVOUS_NS\n} from './constants.js'\nimport type { AddressSorter } from '@libp2p/interface-peer-store'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport type { RelayConfig } from '../index.js'\n\nconst log = logger('libp2p:relay')\n\nexport interface RelayAdvertiseConfig {\n bootDelay?: number\n enabled?: boolean\n ttl?: number\n}\n\nexport interface AutoRelayConfig {\n enabled?: boolean\n\n /**\n * maximum number of relays to listen\n */\n maxListeners: number\n}\n\nexport interface RelayInit extends RelayConfig {\n addressSorter?: AddressSorter\n}\n\nexport class Relay implements Startable {\n private readonly components: Components\n private readonly init: RelayInit\n // @ts-expect-error this field isn't used anywhere?\n private readonly autoRelay?: AutoRelay\n private timeout?: any\n private started: boolean\n\n /**\n * Creates an instance of Relay\n */\n constructor (components: Components, init: RelayInit) {\n this.components = components\n // Create autoRelay if enabled\n this.autoRelay = init.autoRelay?.enabled !== false\n ? new AutoRelay(components, {\n addressSorter: init.addressSorter,\n ...init.autoRelay\n })\n : undefined\n\n this.started = false\n this.init = init\n this._advertiseService = this._advertiseService.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Start Relay service\n */\n async start () {\n // Advertise service if HOP enabled\n if (this.init.hop.enabled !== false && this.init.advertise.enabled !== false) {\n this.timeout = setDelayedInterval(\n this._advertiseService, this.init.advertise.ttl, this.init.advertise.bootDelay\n )\n }\n\n this.started = true\n }\n\n /**\n * Stop Relay service\n */\n async stop () {\n if (this.timeout != null) {\n clearDelayedInterval(this.timeout)\n }\n\n this.started = false\n }\n\n /**\n * Advertise hop relay service in the network.\n */\n async _advertiseService () {\n try {\n const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)\n await this.components.getContentRouting().provide(cid)\n } catch (err: any) {\n if (err.code === codes.ERR_NO_ROUTERS_AVAILABLE) {\n log.error('a content router, such as a DHT, must be provided in order to advertise the relay service', err)\n // Stop the advertise\n await this.stop()\n } else {\n log.error(err)\n }\n }\n }\n}\n","import 'node-forge/lib/x509.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\n\nconst pki = forge.pki\n\n/**\n * Gets a self-signed X.509 certificate for the key.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n *\n * TODO: move to libp2p-crypto package\n */\nexport const certificateForKey = (key: any, privateKey: forge.pki.rsa.PrivateKey) => {\n const publicKey = pki.rsa.setPublicKey(privateKey.n, privateKey.e)\n const cert = pki.createCertificate()\n cert.publicKey = publicKey\n cert.serialNumber = '01'\n cert.validity.notBefore = new Date()\n cert.validity.notAfter = new Date()\n cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10) // eslint-disable-line @typescript-eslint/restrict-plus-operands\n const attrs = [{\n name: 'organizationName',\n value: 'ipfs'\n }, {\n shortName: 'OU',\n value: 'keystore'\n }, {\n name: 'commonName',\n value: key.id\n }]\n cert.setSubject(attrs)\n cert.setIssuer(attrs)\n cert.setExtensions([{\n name: 'basicConstraints',\n cA: true\n }, {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n }, {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n emailProtection: true,\n timeStamping: true\n }, {\n name: 'nsCertType',\n client: true,\n server: true,\n email: true,\n objsign: true,\n sslCA: true,\n emailCA: true,\n objCA: true\n }])\n // self-sign certificate\n cert.sign(privateKey)\n\n return cert\n}\n\n/**\n * Finds the first item in a collection that is matched in the\n * `asyncCompare` function.\n *\n * `asyncCompare` is an async function that must\n * resolve to either `true` or `false`.\n *\n * @param {Array} array\n * @param {function(*)} asyncCompare - An async function that returns a boolean\n */\nexport async function findAsync (array: T[], asyncCompare: (val: T) => Promise) {\n const promises = array.map(asyncCompare)\n const results = await Promise.all(promises)\n const index = results.findIndex(result => result)\n return array[index]\n}\n","import 'node-forge/lib/pkcs7.js'\nimport 'node-forge/lib/pbe.js'\n// @ts-expect-error types are missing\nimport forge from 'node-forge/lib/forge.js'\nimport { certificateForKey, findAsync } from './util.js'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { codes } from '../errors.js'\nimport { logger } from '@libp2p/logger'\nimport type { KeyChain } from './index.js'\n\nconst log = logger('libp2p:keychain:cms')\n\nconst privates = new WeakMap()\n\n/**\n * Cryptographic Message Syntax (aka PKCS #7)\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content.\n *\n * See RFC 5652 for all the details.\n */\nexport class CMS {\n private readonly keychain: KeyChain\n\n /**\n * Creates a new instance with a keychain\n */\n constructor (keychain: KeyChain, dek: string) {\n if (keychain == null) {\n throw errCode(new Error('keychain is required'), codes.ERR_KEYCHAIN_REQUIRED)\n }\n\n this.keychain = keychain\n privates.set(this, { dek })\n }\n\n /**\n * Creates some protected data.\n *\n * The output Uint8Array contains the PKCS #7 message in DER.\n */\n async encrypt (name: string, plain: Uint8Array): Promise {\n if (!(plain instanceof Uint8Array)) {\n throw errCode(new Error('Plain data must be a Uint8Array'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const key = await this.keychain.findKeyByName(name)\n const pem = await this.keychain.getPrivateKey(name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n const certificate = await certificateForKey(key, privateKey)\n\n // create a p7 enveloped message\n const p7 = forge.pkcs7.createEnvelopedData()\n p7.addRecipient(certificate)\n p7.content = forge.util.createBuffer(plain)\n p7.encrypt()\n\n // convert message to DER\n const der = forge.asn1.toDer(p7.toAsn1()).getBytes()\n return uint8ArrayFromString(der, 'ascii')\n }\n\n /**\n * Reads some protected data.\n *\n * The keychain must contain one of the keys used to encrypt the data. If none of the keys\n * exists, an Error is returned with the property 'missingKeys'. It is array of key ids.\n */\n async decrypt (cmsData: Uint8Array): Promise {\n if (!(cmsData instanceof Uint8Array)) {\n throw errCode(new Error('CMS data is required'), codes.ERR_INVALID_PARAMETERS)\n }\n\n let cms: any\n try {\n const buf = forge.util.createBuffer(uint8ArrayToString(cmsData, 'ascii'))\n const obj = forge.asn1.fromDer(buf)\n\n cms = forge.pkcs7.messageFromAsn1(obj)\n } catch (err: any) {\n log.error(err)\n throw errCode(new Error('Invalid CMS'), codes.ERR_INVALID_CMS)\n }\n\n // Find a recipient whose key we hold. We only deal with recipient certs\n // issued by ipfs (O=ipfs).\n const recipients: any = cms.recipients\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'O' && a.value === 'ipfs'))\n // @ts-expect-error cms types not defined\n .filter(r => r.issuer.find(a => a.shortName === 'CN'))\n // @ts-expect-error cms types not defined\n .map(r => {\n return {\n recipient: r,\n // @ts-expect-error cms types not defined\n keyId: r.issuer.find(a => a.shortName === 'CN').value\n }\n })\n\n const r = await findAsync(recipients, async (recipient: any) => {\n try {\n const key = await this.keychain.findKeyById(recipient.keyId)\n if (key != null) {\n return true\n }\n } catch (err: any) {\n return false\n }\n return false\n })\n\n if (r == null) {\n // @ts-expect-error cms types not defined\n const missingKeys: string[] = recipients.map(r => r.keyId)\n throw errCode(new Error(`Decryption needs one of the key(s): ${missingKeys.join(', ')}`), codes.ERR_MISSING_KEYS, {\n missingKeys\n })\n }\n\n const key = await this.keychain.findKeyById(r.keyId)\n\n if (key == null) {\n throw errCode(new Error('No key available to decrypto'), codes.ERR_NO_KEY)\n }\n\n const pem = await this.keychain.getPrivateKey(key.name)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = forge.pki.decryptRsaPrivateKey(pem, dek)\n cms.decrypt(r.recipient, privateKey)\n return uint8ArrayFromString(cms.content.getBytes(), 'ascii')\n }\n}\n","/* eslint max-nested-callbacks: [\"error\", 5] */\n\nimport { logger } from '@libp2p/logger'\nimport sanitize from 'sanitize-filename'\nimport mergeOptions from 'merge-options'\nimport { Key } from 'interface-datastore/key'\nimport { CMS } from './cms.js'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Components } from '@libp2p/components'\nimport { pbkdf2, randomBytes } from '@libp2p/crypto'\n\nconst log = logger('libp2p:keychain')\n\nexport interface DekOptions {\n hash: string\n salt: string\n iterationCount: number\n keyLength: number\n}\n\nexport interface KeyChainInit {\n pass?: string\n dek?: DekOptions\n}\n\n/**\n * Information about a key.\n */\nexport interface KeyInfo {\n /**\n * The universally unique key id\n */\n id: string\n\n /**\n * The local key name.\n */\n name: string\n}\n\nconst keyPrefix = '/pkcs8/'\nconst infoPrefix = '/info/'\nconst privates = new WeakMap()\n\n// NIST SP 800-132\nconst NIST = {\n minKeyLength: 112 / 8,\n minSaltLength: 128 / 8,\n minIterationCount: 1000\n}\n\nconst defaultOptions = {\n // See https://cryptosense.com/parametesr-choice-for-pbkdf2/\n dek: {\n keyLength: 512 / 8,\n iterationCount: 10000,\n salt: 'you should override this value with a crypto secure random number',\n hash: 'sha2-512'\n }\n}\n\nfunction validateKeyName (name: string) {\n if (name == null) {\n return false\n }\n if (typeof name !== 'string') {\n return false\n }\n return name === sanitize(name.trim()) && name.length > 0\n}\n\n/**\n * Throws an error after a delay\n *\n * This assumes than an error indicates that the keychain is under attack. Delay returning an\n * error to make brute force attacks harder.\n */\nasync function randomDelay () {\n const min = 200\n const max = 1000\n const delay = Math.random() * (max - min) + min\n\n await new Promise(resolve => setTimeout(resolve, delay))\n}\n\n/**\n * Converts a key name into a datastore name\n */\nfunction DsName (name: string) {\n return new Key(keyPrefix + name)\n}\n\n/**\n * Converts a key name into a datastore info name\n */\nfunction DsInfoName (name: string) {\n return new Key(infoPrefix + name)\n}\n\n/**\n * Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.\n *\n * A key in the store has two entries\n * - '/info/*key-name*', contains the KeyInfo for the key\n * - '/pkcs8/*key-name*', contains the PKCS #8 for the key\n *\n */\nexport class KeyChain {\n private readonly components: Components\n private init: KeyChainInit\n\n /**\n * Creates a new instance of a key chain\n */\n constructor (components: Components, init: KeyChainInit) {\n this.components = components\n this.init = mergeOptions(defaultOptions, init)\n\n // Enforce NIST SP 800-132\n if (this.init.pass != null && this.init.pass?.length < 20) {\n throw new Error('pass must be least 20 characters')\n }\n if (this.init.dek?.keyLength != null && this.init.dek.keyLength < NIST.minKeyLength) {\n throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)\n }\n if (this.init.dek?.salt?.length != null && this.init.dek.salt.length < NIST.minSaltLength) {\n throw new Error(`dek.saltLength must be least ${NIST.minSaltLength} bytes`)\n }\n if (this.init.dek?.iterationCount != null && this.init.dek.iterationCount < NIST.minIterationCount) {\n throw new Error(`dek.iterationCount must be least ${NIST.minIterationCount}`)\n }\n\n const dek = this.init.pass != null && this.init.dek?.salt != null\n ? pbkdf2(\n this.init.pass,\n this.init.dek?.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n\n privates.set(this, { dek })\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data\n * using the Cryptographic Message Syntax (CMS).\n *\n * CMS describes an encapsulation syntax for data protection. It\n * is used to digitally sign, digest, authenticate, or encrypt\n * arbitrary message content\n */\n get cms () {\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n\n return new CMS(this, dek)\n }\n\n /**\n * Generates the options for a keychain. A random salt is produced.\n *\n * @returns {object}\n */\n static generateOptions (): KeyChainInit {\n const options = Object.assign({}, defaultOptions)\n const saltLength = Math.ceil(NIST.minSaltLength / 3) * 3 // no base64 padding\n options.dek.salt = uint8ArrayToString(randomBytes(saltLength), 'base64')\n return options\n }\n\n /**\n * Gets an object that can encrypt/decrypt protected data.\n * The default options for a keychain.\n *\n * @returns {object}\n */\n static get options () {\n return defaultOptions\n }\n\n /**\n * Create a new key.\n *\n * @param {string} name - The local key name; cannot already exist.\n * @param {string} type - One of the key types; 'rsa'.\n * @param {number} [size = 2048] - The key size in bits. Used for rsa keys only\n */\n async createKey (name: string, type: 'RSA' | 'Ed25519', size = 2048): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error('Invalid key name'), codes.ERR_INVALID_KEY_NAME)\n }\n\n if (typeof type !== 'string') {\n await randomDelay()\n throw errCode(new Error('Invalid key type'), codes.ERR_INVALID_KEY_TYPE)\n }\n\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error('Key name already exists'), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n switch (type.toLowerCase()) {\n case 'rsa':\n if (!Number.isSafeInteger(size) || size < 2048) {\n await randomDelay()\n throw errCode(new Error('Invalid RSA key size'), codes.ERR_INVALID_KEY_SIZE)\n }\n break\n default:\n break\n }\n\n let keyInfo\n try {\n const keypair = await generateKeyPair(type, size)\n const kid = await keypair.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await keypair.export(dek)\n keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n\n await batch.commit()\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n return keyInfo\n }\n\n /**\n * List all the keys.\n *\n * @returns {Promise}\n */\n async listKeys () {\n const query = {\n prefix: infoPrefix\n }\n\n const info = []\n for await (const value of this.components.getDatastore().query(query)) {\n info.push(JSON.parse(uint8ArrayToString(value.value)))\n }\n\n return info\n }\n\n /**\n * Find a key by it's id\n */\n async findKeyById (id: string): Promise {\n try {\n const keys = await this.listKeys()\n return keys.find((k) => k.id === id)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Find a key by it's name.\n *\n * @param {string} name - The local key name.\n * @returns {Promise}\n */\n async findKeyByName (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n const dsname = DsInfoName(name)\n try {\n const res = await this.components.getDatastore().get(dsname)\n return JSON.parse(uint8ArrayToString(res))\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Remove an existing key.\n *\n * @param {string} name - The local key name; must already exist.\n * @returns {Promise}\n */\n async removeKey (name: string) {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n const dsname = DsName(name)\n const keyInfo = await this.findKeyByName(name)\n const batch = this.components.getDatastore().batch()\n batch.delete(dsname)\n batch.delete(DsInfoName(name))\n await batch.commit()\n return keyInfo\n }\n\n /**\n * Rename a key\n *\n * @param {string} oldName - The old local key name; must already exist.\n * @param {string} newName - The new local key name; must not already exist.\n * @returns {Promise}\n */\n async renameKey (oldName: string, newName: string): Promise {\n if (!validateKeyName(oldName) || oldName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid old key name '${oldName}'`), codes.ERR_OLD_KEY_NAME_INVALID)\n }\n if (!validateKeyName(newName) || newName === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid new key name '${newName}'`), codes.ERR_NEW_KEY_NAME_INVALID)\n }\n const oldDsname = DsName(oldName)\n const newDsname = DsName(newName)\n const oldInfoName = DsInfoName(oldName)\n const newInfoName = DsInfoName(newName)\n\n const exists = await this.components.getDatastore().has(newDsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${newName}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n try {\n const pem = await this.components.getDatastore().get(oldDsname)\n const res = await this.components.getDatastore().get(oldInfoName)\n\n const keyInfo = JSON.parse(uint8ArrayToString(res))\n keyInfo.name = newName\n const batch = this.components.getDatastore().batch()\n batch.put(newDsname, pem)\n batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))\n batch.delete(oldDsname)\n batch.delete(oldInfoName)\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Export an existing key as a PEM encrypted PKCS #8 string\n */\n async exportKey (name: string, password: string) {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (password == null) {\n await randomDelay()\n throw errCode(new Error('Password is required'), codes.ERR_PASSWORD_REQUIRED)\n }\n\n const dsname = DsName(name)\n try {\n const res = await this.components.getDatastore().get(dsname)\n const pem = uint8ArrayToString(res)\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const privateKey = await importKey(pem, dek)\n return await privateKey.export(password)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Import a new key from a PEM encoded PKCS #8 string\n *\n * @param {string} name - The local key name; must not already exist.\n * @param {string} pem - The PEM encoded PKCS #8 string\n * @param {string} password - The password.\n * @returns {Promise}\n */\n async importKey (name: string, pem: string, password: string): Promise {\n if (!validateKeyName(name) || name === 'self') {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (pem == null) {\n await randomDelay()\n throw errCode(new Error('PEM encoded key is required'), codes.ERR_PEM_REQUIRED)\n }\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n let privateKey\n try {\n privateKey = await importKey(pem, password)\n } catch (err: any) {\n await randomDelay()\n throw errCode(new Error('Cannot read the key, most likely the password is wrong'), codes.ERR_CANNOT_READ_KEY)\n }\n\n let kid\n try {\n kid = await privateKey.id()\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n pem = await privateKey.export(dek)\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n\n const keyInfo = {\n name: name,\n id: kid\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n\n return keyInfo\n }\n\n /**\n * Import a peer key\n */\n async importPeer (name: string, peer: PeerId): Promise {\n try {\n if (!validateKeyName(name)) {\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n if (peer == null || peer.privateKey == null) {\n throw errCode(new Error('Peer.privKey is required'), codes.ERR_MISSING_PRIVATE_KEY)\n }\n\n const privateKey = await unmarshalPrivateKey(peer.privateKey)\n\n const dsname = DsName(name)\n const exists = await this.components.getDatastore().has(dsname)\n if (exists) {\n await randomDelay()\n throw errCode(new Error(`Key '${name}' already exists`), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const dek = cached.dek\n const pem = await privateKey.export(dek)\n const keyInfo: KeyInfo = {\n name: name,\n id: peer.toString()\n }\n const batch = this.components.getDatastore().batch()\n batch.put(dsname, uint8ArrayFromString(pem))\n batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n return keyInfo\n } catch (err: any) {\n await randomDelay()\n throw err\n }\n }\n\n /**\n * Gets the private key as PEM encoded PKCS #8 string\n */\n async getPrivateKey (name: string): Promise {\n if (!validateKeyName(name)) {\n await randomDelay()\n throw errCode(new Error(`Invalid key name '${name}'`), codes.ERR_INVALID_KEY_NAME)\n }\n\n try {\n const dsname = DsName(name)\n const res = await this.components.getDatastore().get(dsname)\n return uint8ArrayToString(res)\n } catch (err: any) {\n await randomDelay()\n log.error(err)\n throw errCode(new Error(`Key '${name}' does not exist.`), codes.ERR_KEY_NOT_FOUND)\n }\n }\n\n /**\n * Rotate keychain password and re-encrypt all associated keys\n */\n async rotateKeychainPass (oldPass: string, newPass: string) {\n if (typeof oldPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid old pass type '${typeof oldPass}'`), codes.ERR_INVALID_OLD_PASS_TYPE)\n }\n if (typeof newPass !== 'string') {\n await randomDelay()\n throw errCode(new Error(`Invalid new pass type '${typeof newPass}'`), codes.ERR_INVALID_NEW_PASS_TYPE)\n }\n if (newPass.length < 20) {\n await randomDelay()\n throw errCode(new Error(`Invalid pass length ${newPass.length}`), codes.ERR_INVALID_PASS_LENGTH)\n }\n log('recreating keychain')\n const cached = privates.get(this)\n\n if (cached == null) {\n throw errCode(new Error('dek missing'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const oldDek = cached.dek\n this.init.pass = newPass\n const newDek = newPass != null && this.init.dek?.salt != null\n ? pbkdf2(\n newPass,\n this.init.dek.salt,\n this.init.dek?.iterationCount,\n this.init.dek?.keyLength,\n this.init.dek?.hash)\n : ''\n privates.set(this, { dek: newDek })\n const keys = await this.listKeys()\n for (const key of keys) {\n const res = await this.components.getDatastore().get(DsName(key.name))\n const pem = uint8ArrayToString(res)\n const privateKey = await importKey(pem, oldDek)\n const password = newDek.toString()\n const keyAsPEM = await privateKey.export(password)\n\n // Update stored key\n const batch = this.components.getDatastore().batch()\n const keyInfo = {\n name: key.name,\n id: key.id\n }\n batch.put(DsName(key.name), uint8ArrayFromString(keyAsPEM))\n batch.put(DsInfoName(key.name), uint8ArrayFromString(JSON.stringify(keyInfo)))\n await batch.commit()\n }\n log('keychain reconstructed')\n }\n}\n","import type { MovingAverage } from '@libp2p/interface-metrics'\n\nexport class DefaultMovingAverage {\n public movingAverage: number\n public variance: number\n public deviation: number\n public forecast: number\n private readonly timespan: number\n private previousTime?: number\n\n constructor (timespan: number) {\n if (typeof timespan !== 'number') {\n throw new Error('must provide a timespan to the moving average constructor')\n }\n\n if (timespan <= 0) {\n throw new Error('must provide a timespan > 0 to the moving average constructor')\n }\n\n this.timespan = timespan\n this.movingAverage = 0\n this.variance = 0\n this.deviation = 0\n this.forecast = 0\n }\n\n alpha (t: number, pt: number) {\n return 1 - (Math.exp(-(t - pt) / this.timespan))\n }\n\n push (time: number, value: number) {\n if (this.previousTime != null) {\n // calculate moving average\n const a = this.alpha(time, this.previousTime)\n const diff = value - this.movingAverage\n const incr = a * diff\n this.movingAverage = a * value + (1 - a) * this.movingAverage\n // calculate variance & deviation\n this.variance = (1 - a) * (this.variance + diff * incr)\n this.deviation = Math.sqrt(this.variance)\n // calculate forecast\n this.forecast = this.movingAverage + a * diff\n } else {\n this.movingAverage = value\n }\n\n this.previousTime = time\n }\n}\n\nexport function createMovingAverage (timespan: number): MovingAverage {\n return new DefaultMovingAverage(timespan)\n}\n","import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { createMovingAverage } from './moving-average.js'\n// @ts-expect-error no types\nimport retimer from 'retimer'\nimport type { MovingAverages, Stats, TransferStats } from '@libp2p/interface-metrics'\n\nexport interface StatsEvents {\n 'update': CustomEvent\n}\n\nexport interface StatsInit {\n enabled: boolean\n initialCounters: ['dataReceived', 'dataSent']\n movingAverageIntervals: number[]\n computeThrottleMaxQueueSize: number\n computeThrottleTimeout: number\n}\n\nexport class DefaultStats extends EventEmitter implements Stats {\n private readonly enabled: boolean\n public queue: Array<[string, number, number]>\n private stats: TransferStats\n private frequencyLastTime: number\n private frequencyAccumulators: Record\n private movingAverages: MovingAverages\n private timeout?: any\n private readonly computeThrottleMaxQueueSize: number\n private readonly computeThrottleTimeout: number\n private readonly movingAverageIntervals: number[]\n\n /**\n * A queue based manager for stat processing\n */\n constructor (init: StatsInit) {\n super()\n\n this.enabled = init.enabled\n this.queue = []\n this.stats = {\n dataReceived: 0n,\n dataSent: 0n\n }\n this.frequencyLastTime = Date.now()\n this.frequencyAccumulators = {}\n this.movingAverages = {\n dataReceived: [],\n dataSent: []\n }\n this.computeThrottleMaxQueueSize = init.computeThrottleMaxQueueSize\n this.computeThrottleTimeout = init.computeThrottleTimeout\n\n this._update = this._update.bind(this)\n\n this.movingAverageIntervals = init.movingAverageIntervals\n\n for (let i = 0; i < init.initialCounters.length; i++) {\n const key = init.initialCounters[i]\n this.stats[key] = 0n\n this.movingAverages[key] = []\n\n for (let k = 0; k < this.movingAverageIntervals.length; k++) {\n const interval = this.movingAverageIntervals[k]\n const ma = this.movingAverages[key][interval] = createMovingAverage(interval)\n ma.push(this.frequencyLastTime, 0)\n }\n }\n }\n\n /**\n * Initializes the internal timer if there are items in the queue. This\n * should only need to be called if `Stats.stop` was previously called, as\n * `Stats.push` will also start the processing\n */\n start () {\n if (!this.enabled) {\n return\n }\n\n if (this.queue.length > 0) {\n this._resetComputeTimeout()\n }\n }\n\n /**\n * Stops processing and computing of stats by clearing the internal\n * timer\n */\n stop () {\n if (this.timeout != null) {\n this.timeout.clear()\n this.timeout = null\n }\n }\n\n /**\n * Returns a clone of the current stats.\n */\n getSnapshot () {\n return Object.assign({}, this.stats)\n }\n\n /**\n * Returns a clone of the internal movingAverages\n */\n getMovingAverages (): MovingAverages {\n return Object.assign({}, this.movingAverages)\n }\n\n /**\n * Pushes the given operation data to the queue, along with the\n * current Timestamp, then resets the update timer.\n */\n push (counter: string, inc: number) {\n this.queue.push([counter, inc, Date.now()])\n this._resetComputeTimeout()\n }\n\n /**\n * Resets the timeout for triggering updates.\n */\n _resetComputeTimeout () {\n this.timeout = retimer(this._update, this._nextTimeout())\n }\n\n /**\n * Calculates and returns the timeout for the next update based on\n * the urgency of the update.\n */\n _nextTimeout () {\n // calculate the need for an update, depending on the queue length\n const urgency = this.queue.length / this.computeThrottleMaxQueueSize\n const timeout = Math.max(this.computeThrottleTimeout * (1 - urgency), 0)\n return timeout\n }\n\n /**\n * If there are items in the queue, they will will be processed and\n * the frequency for all items will be updated based on the Timestamp\n * of the last item in the queue. The `update` event will also be emitted\n * with the latest stats.\n *\n * If there are no items in the queue, no action is taken.\n */\n _update () {\n this.timeout = null\n if (this.queue.length > 0) {\n let last: [string, number, number] = ['', 0, 0]\n\n for (last of this.queue) {\n this._applyOp(last)\n }\n\n this.queue = []\n\n if (last.length > 2 && last[0] !== '') {\n this._updateFrequency(last[2]) // contains timestamp of last op\n }\n\n this.dispatchEvent(new CustomEvent('update', {\n detail: this.stats\n }))\n }\n }\n\n /**\n * For each key in the stats, the frequency and moving averages\n * will be updated via Stats._updateFrequencyFor based on the time\n * difference between calls to this method.\n */\n _updateFrequency (latestTime: number) {\n const timeDiff = latestTime - this.frequencyLastTime\n\n this._updateFrequencyFor('dataReceived', timeDiff, latestTime)\n this._updateFrequencyFor('dataSent', timeDiff, latestTime)\n\n this.frequencyLastTime = latestTime\n }\n\n /**\n * Updates the `movingAverages` for the given `key` and also\n * resets the `frequencyAccumulator` for the `key`.\n */\n _updateFrequencyFor (key: 'dataReceived' | 'dataSent', timeDiffMS: number, latestTime: number) {\n const count = this.frequencyAccumulators[key] ?? 0\n this.frequencyAccumulators[key] = 0\n // if `timeDiff` is zero, `hz` becomes Infinity, so we fallback to 1ms\n const safeTimeDiff = timeDiffMS ?? 1\n const hz = (count / safeTimeDiff) * 1000\n\n let movingAverages = this.movingAverages[key]\n if (movingAverages == null) {\n movingAverages = this.movingAverages[key] = []\n }\n\n const intervals = this.movingAverageIntervals\n\n for (let i = 0; i < intervals.length; i++) {\n const movingAverageInterval = intervals[i]\n let movingAverage = movingAverages[movingAverageInterval]\n if (movingAverage == null) {\n movingAverage = movingAverages[movingAverageInterval] = createMovingAverage(movingAverageInterval)\n }\n movingAverage.push(latestTime, hz)\n }\n }\n\n /**\n * For the given operation, `op`, the stats and `frequencyAccumulator`\n * will be updated or initialized if they don't already exist.\n */\n _applyOp (op: [string, number, number]) {\n const key = op[0]\n const inc = op[1]\n\n if (typeof inc !== 'number') {\n throw new Error('invalid increment number')\n }\n\n let n: bigint\n\n if (!Object.prototype.hasOwnProperty.call(this.stats, key)) {\n // @ts-expect-error cannot index type with key\n n = this.stats[key] = 0n\n } else {\n // @ts-expect-error cannot index type with key\n n = this.stats[key]\n }\n\n // @ts-expect-error cannot index type with key\n this.stats[key] = n + BigInt(inc)\n\n if (this.frequencyAccumulators[key] == null) {\n this.frequencyAccumulators[key] = 0\n }\n\n this.frequencyAccumulators[key] += inc\n }\n}\n","import { pipe } from 'it-pipe'\nimport each from 'it-foreach'\nimport LRU from 'hashlru'\nimport { METRICS as defaultOptions } from '../constants.js'\nimport { DefaultStats, StatsInit } from './stats.js'\nimport type { ComponentMetricsUpdate, Metrics, Stats, TrackedMetric, TrackStreamOptions } from '@libp2p/interface-metrics'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\n\nconst initialCounters: ['dataReceived', 'dataSent'] = [\n 'dataReceived',\n 'dataSent'\n]\n\nconst directionToEvent = {\n in: 'dataReceived',\n out: 'dataSent'\n}\n\nexport interface OnMessageOptions {\n remotePeer: PeerId\n protocol?: string\n direction: 'in' | 'out'\n dataLength: number\n}\n\nexport interface MetricsInit {\n enabled: boolean\n computeThrottleMaxQueueSize: number\n computeThrottleTimeout: number\n movingAverageIntervals: number[]\n maxOldPeersRetention: number\n}\n\nexport class DefaultMetrics implements Metrics, Startable {\n public globalStats: DefaultStats\n\n private readonly enabled: boolean\n private readonly peerStats: Map\n private readonly protocolStats: Map\n private readonly oldPeers: ReturnType\n private running: boolean\n private readonly systems: Map>>\n private readonly statsInit: StatsInit\n\n constructor (init: MetricsInit) {\n this.enabled = init.enabled\n this.statsInit = {\n ...init,\n initialCounters\n }\n this.globalStats = new DefaultStats(this.statsInit)\n this.peerStats = new Map()\n this.protocolStats = new Map()\n this.oldPeers = LRU(init.maxOldPeersRetention ?? defaultOptions.maxOldPeersRetention)\n this.running = false\n this._onMessage = this._onMessage.bind(this)\n this.systems = new Map()\n }\n\n isStarted () {\n return this.running\n }\n\n /**\n * Must be called for stats to saved. Any data pushed for tracking\n * will be ignored.\n */\n async start () {\n if (!this.enabled) {\n return\n }\n\n this.running = true\n }\n\n /**\n * Stops all averages timers and prevents new data from being tracked.\n * Once `stop` is called, `start` must be called to resume stats tracking.\n */\n async stop () {\n if (!this.running) {\n return\n }\n\n this.running = false\n this.globalStats.stop()\n\n for (const stats of this.peerStats.values()) {\n stats.stop()\n }\n\n for (const stats of this.protocolStats.values()) {\n stats.stop()\n }\n }\n\n /**\n * Gets the global `Stats` object\n */\n getGlobal () {\n return this.globalStats\n }\n\n /**\n * Returns a list of `PeerId` strings currently being tracked\n */\n getPeers () {\n return Array.from(this.peerStats.keys())\n }\n\n getComponentMetrics () {\n return this.systems\n }\n\n updateComponentMetric (update: ComponentMetricsUpdate) {\n const { system = 'libp2p', component, metric, value, label, help } = update\n\n if (!this.systems.has(system)) {\n this.systems.set(system, new Map())\n }\n\n const systemMetrics = this.systems.get(system)\n\n if (systemMetrics == null) {\n throw new Error('Unknown metric system')\n }\n\n if (!systemMetrics.has(component)) {\n systemMetrics.set(component, new Map())\n }\n\n const componentMetrics = systemMetrics.get(component)\n\n if (componentMetrics == null) {\n throw new Error('Unknown metric component')\n }\n\n componentMetrics.set(metric, {\n label,\n help,\n calculate: typeof value !== 'function' ? () => value : value\n })\n }\n\n /**\n * Returns the `Stats` object for the given `PeerId` whether it\n * is a live peer, or in the disconnected peer LRU cache.\n */\n forPeer (peerId: PeerId): Stats | undefined {\n const idString = peerId.toString()\n return this.peerStats.get(idString) ?? this.oldPeers.get(idString)\n }\n\n /**\n * Returns a list of all protocol strings currently being tracked\n */\n getProtocols (): string[] {\n return Array.from(this.protocolStats.keys())\n }\n\n /**\n * Returns the `Stats` object for the given `protocol`\n */\n forProtocol (protocol: string): Stats | undefined {\n return this.protocolStats.get(protocol)\n }\n\n /**\n * Should be called when all connections to a given peer\n * have closed. The `Stats` collection for the peer will\n * be stopped and moved to an LRU for temporary retention.\n */\n onPeerDisconnected (peerId: PeerId) {\n const idString = peerId.toString()\n const peerStats = this.peerStats.get(idString)\n\n if (peerStats != null) {\n peerStats.stop()\n\n this.peerStats.delete(idString)\n this.oldPeers.set(idString, peerStats)\n }\n }\n\n /**\n * Takes the metadata for a message and tracks it in the\n * appropriate categories. If the protocol is present, protocol\n * stats will also be tracked.\n */\n _onMessage (opts: OnMessageOptions) {\n if (!this.running) {\n return\n }\n\n const { remotePeer, protocol, direction, dataLength } = opts\n\n const key = directionToEvent[direction]\n\n let peerStats = this.forPeer(remotePeer)\n if (peerStats == null) {\n const stats = new DefaultStats(this.statsInit)\n this.peerStats.set(remotePeer.toString(), stats)\n peerStats = stats\n }\n\n // Peer and global stats\n peerStats.push(key, dataLength)\n this.globalStats.push(key, dataLength)\n\n // Protocol specific stats\n if (protocol != null) {\n let protocolStats = this.forProtocol(protocol)\n\n if (protocolStats == null) {\n const stats = new DefaultStats(this.statsInit)\n this.protocolStats.set(protocol, stats)\n protocolStats = stats\n }\n\n protocolStats.push(key, dataLength)\n }\n }\n\n /**\n * Replaces the `PeerId` string with the given `peerId`.\n * If stats are already being tracked for the given `peerId`, the\n * placeholder stats will be merged with the existing stats.\n *\n * @param {PeerId} placeholder - A peerId string\n * @param {PeerId} peerId\n * @returns {void}\n */\n updatePlaceholder (placeholder: PeerId, peerId: PeerId) {\n if (!this.running) {\n return\n }\n\n const placeholderString = placeholder.toString()\n const placeholderStats = this.peerStats.get(placeholderString) ?? this.oldPeers.get(placeholderString)\n const peerIdString = peerId.toString()\n const existingStats = this.peerStats.get(peerIdString) ?? this.oldPeers.get(peerIdString)\n let mergedStats = placeholderStats\n\n // If we already have stats, merge the two\n if (existingStats != null) {\n // If existing, merge\n mergedStats = mergeStats(existingStats, mergedStats)\n // Attempt to delete from the old peers list just in case it was tracked there\n this.oldPeers.remove(peerIdString)\n }\n\n this.peerStats.delete(placeholder.toString())\n this.peerStats.set(peerIdString, mergedStats)\n mergedStats.start()\n }\n\n /**\n * Tracks data running through a given Duplex Iterable `stream`. If\n * the `peerId` is not provided, a placeholder string will be created and\n * returned. This allows lazy tracking of a peer when the peer is not yet known.\n * When the `PeerId` is known, `Metrics.updatePlaceholder` should be called\n * with the placeholder string returned from here, and the known `PeerId`.\n */\n trackStream (opts: TrackStreamOptions): void {\n const { stream, remotePeer, protocol } = opts\n\n if (!this.running) {\n return\n }\n\n const source = stream.source\n stream.source = each(source, chunk => this._onMessage({\n remotePeer,\n protocol,\n direction: 'in',\n dataLength: chunk.byteLength\n }))\n\n const sink = stream.sink\n stream.sink = async source => {\n return await pipe(\n source,\n (source) => each(source, chunk => {\n this._onMessage({\n remotePeer,\n protocol,\n direction: 'out',\n dataLength: chunk.byteLength\n })\n }),\n sink\n )\n }\n }\n}\n\n/**\n * Merges `other` into `target`. `target` will be modified\n * and returned\n */\nfunction mergeStats (target: DefaultStats, other: DefaultStats) {\n target.stop()\n other.stop()\n\n // Merge queues\n target.queue = [...target.queue, ...other.queue]\n\n // TODO: how to merge moving averages?\n return target\n}\n","export default async function pReflect(promise) {\n\ttry {\n\t\tconst value = await promise;\n\n\t\treturn {\n\t\t\tstatus: 'fulfilled',\n\t\t\tvalue,\n\t\t\tisFulfilled: true,\n\t\t\tisRejected: false\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tstatus: 'rejected',\n\t\t\treason: error,\n\t\t\tisFulfilled: false,\n\t\t\tisRejected: true\n\t\t};\n\t}\n}\n\nexport function isFulfilled(promiseResult) {\n\treturn 'value' in promiseResult;\n}\n\nexport function isRejected(promiseResult) {\n\treturn 'reason' in promiseResult;\n}\n","import checkPrivateRedeclaration from \"./checkPrivateRedeclaration.js\";\nexport default function _classPrivateFieldInitSpec(obj, privateMap, value) {\n checkPrivateRedeclaration(obj, privateMap);\n privateMap.set(obj, value);\n}","export default function _checkPrivateRedeclaration(obj, privateCollection) {\n if (privateCollection.has(obj)) {\n throw new TypeError(\"Cannot initialize the same private elements twice on an object\");\n }\n}","export default function _classExtractFieldDescriptor(receiver, privateMap, action) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to \" + action + \" private field on non-instance\");\n }\n\n return privateMap.get(receiver);\n}","import classApplyDescriptorSet from \"./classApplyDescriptorSet.js\";\nimport classExtractFieldDescriptor from \"./classExtractFieldDescriptor.js\";\nexport default function _classPrivateFieldSet(receiver, privateMap, value) {\n var descriptor = classExtractFieldDescriptor(receiver, privateMap, \"set\");\n classApplyDescriptorSet(receiver, descriptor, value);\n return value;\n}","export default function _classApplyDescriptorSet(receiver, descriptor, value) {\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError(\"attempted to set read only private field\");\n }\n\n descriptor.value = value;\n }\n}","import classApplyDescriptorGet from \"./classApplyDescriptorGet.js\";\nimport classExtractFieldDescriptor from \"./classExtractFieldDescriptor.js\";\nexport default function _classPrivateFieldGet(receiver, privateMap) {\n var descriptor = classExtractFieldDescriptor(receiver, privateMap, \"get\");\n return classApplyDescriptorGet(receiver, descriptor);\n}","export default function _classApplyDescriptorGet(receiver, descriptor) {\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n\n return descriptor.value;\n}","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\t\treturn current.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n}\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tif (queue.size > 0) {\n\t\t\tqueue.dequeue()();\n\t\t}\n\t};\n\n\tconst run = async (fn, resolve, args) => {\n\t\tactiveCount++;\n\n\t\tconst result = (async () => fn(...args))();\n\n\t\tresolve(result);\n\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\tnext();\n\t};\n\n\tconst enqueue = (fn, resolve, args) => {\n\t\tqueue.enqueue(run.bind(undefined, fn, resolve, args));\n\n\t\t(async () => {\n\t\t\t// This function needs to wait until the next microtask before comparing\n\t\t\t// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously\n\t\t\t// when the run function is dequeued and called. The comparison in the if-statement\n\t\t\t// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.\n\t\t\tawait Promise.resolve();\n\n\t\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\t\tqueue.dequeue()();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst generator = (fn, ...args) => new Promise(resolve => {\n\t\tenqueue(fn, resolve, args);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue: () => {\n\t\t\t\tqueue.clear();\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n","import pReflect from 'p-reflect';\nimport pLimit from 'p-limit';\n\nexport default async function pSettle(array, options = {}) {\n\tconst {concurrency = Number.POSITIVE_INFINITY} = options;\n\tconst limit = pLimit(concurrency);\n\n\treturn Promise.all(array.map(element => {\n\t\tif (element && typeof element.then === 'function') {\n\t\t\treturn pReflect(element);\n\t\t}\n\n\t\tif (typeof element === 'function') {\n\t\t\treturn pReflect(limit(() => element()));\n\t\t}\n\n\t\treturn pReflect(Promise.resolve(element));\n\t}));\n}\n","import { logger } from '@libp2p/logger'\nimport pSettle from 'p-settle'\nimport { codes } from './errors.js'\nimport errCode from 'err-code'\nimport type { Listener, Transport, TransportManager, TransportManagerEvents } from '@libp2p/interface-transport'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport { trackedMap } from '@libp2p/tracked-map'\n\nconst log = logger('libp2p:transports')\n\nexport interface TransportManagerInit {\n faultTolerance?: FaultTolerance\n}\n\nexport class DefaultTransportManager extends EventEmitter implements TransportManager, Startable {\n private readonly components: Components\n private readonly transports: Map\n private readonly listeners: Map\n private readonly faultTolerance: FaultTolerance\n private started: boolean\n\n constructor (components: Components, init: TransportManagerInit = {}) {\n super()\n\n this.components = components\n this.started = false\n this.transports = new Map()\n this.listeners = trackedMap({\n component: 'transport-manager',\n metric: 'listeners',\n metrics: this.components.getMetrics()\n })\n this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL\n }\n\n /**\n * Adds a `Transport` to the manager\n */\n add (transport: Transport) {\n const tag = transport[Symbol.toStringTag]\n\n if (tag == null) {\n throw errCode(new Error('Transport must have a valid tag'), codes.ERR_INVALID_KEY)\n }\n\n if (this.transports.has(tag)) {\n throw errCode(new Error('There is already a transport with this tag'), codes.ERR_DUPLICATE_TRANSPORT)\n }\n\n log('adding transport %s', tag)\n\n this.transports.set(tag, transport)\n\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, [])\n }\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.getAddressManager().getListenAddrs()\n\n await this.listen(addrs)\n\n this.started = true\n }\n\n /**\n * Stops all listeners\n */\n async stop () {\n const tasks = []\n for (const [key, listeners] of this.listeners) {\n log('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n }\n\n await Promise.all(tasks)\n log('all listeners closed')\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, [])\n }\n\n this.started = false\n }\n\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial (ma: Multiaddr, options?: AbortOptions): Promise {\n const transport = this.transportForMultiaddr(ma)\n\n if (transport == null) {\n throw errCode(new Error(`No transport available for address ${String(ma)}`), codes.ERR_TRANSPORT_UNAVAILABLE)\n }\n\n try {\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.getUpgrader()\n })\n } catch (err: any) {\n if (err.code == null) {\n err.code = codes.ERR_TRANSPORT_DIAL_FAILED\n }\n\n throw err\n }\n }\n\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs (): Multiaddr[] {\n let addrs: Multiaddr[] = []\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()]\n }\n }\n return addrs\n }\n\n /**\n * Returns all the transports instances\n */\n getTransports () {\n return Array.of(...this.transports.values())\n }\n\n /**\n * Finds a transport that matches the given Multiaddr\n */\n transportForMultiaddr (ma: Multiaddr) {\n for (const transport of this.transports.values()) {\n const addrs = transport.filter([ma])\n\n if (addrs.length > 0) {\n return transport\n }\n }\n }\n\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen (addrs: Multiaddr[]) {\n if (addrs == null || addrs.length === 0) {\n log('no addresses were provided for listening, this node is dial only')\n return\n }\n\n const couldNotListen = []\n\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.filter(addrs)\n const tasks = []\n\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n log('creating listener for %s on %s', key, addr)\n const listener = transport.createListener({\n upgrader: this.components.getUpgrader()\n })\n\n let listeners = this.listeners.get(key)\n\n if (listeners == null) {\n listeners = []\n this.listeners.set(key, listeners)\n }\n\n listeners.push(listener)\n\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.dispatchEvent(new CustomEvent('listener:listening', {\n detail: listener\n }))\n })\n listener.addEventListener('close', () => {\n this.dispatchEvent(new CustomEvent('listener:close', {\n detail: listener\n }))\n })\n\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr))\n }\n\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key)\n continue\n }\n\n const results = await pSettle(tasks)\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.isFulfilled)\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw errCode(new Error(`Transport (${key}) could not listen on any available address`), codes.ERR_NO_VALID_ADDRESSES)\n }\n }\n\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`\n if (this.faultTolerance === FaultTolerance.FATAL_ALL) {\n throw errCode(new Error(message), codes.ERR_NO_VALID_ADDRESSES)\n }\n log(`libp2p in dial mode only: ${message}`)\n }\n }\n\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove (key: string) {\n log('removing %s', key)\n\n // Close any running listeners\n for (const listener of this.listeners.get(key) ?? []) {\n await listener.close()\n }\n\n this.transports.delete(key)\n this.listeners.delete(key)\n }\n\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll () {\n const tasks = []\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key))\n }\n\n await Promise.all(tasks)\n }\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n","\nexport const PROTOCOL_ID = '/multistream/1.0.0'\n","\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport errCode from 'err-code'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport first from 'it-first'\nimport { abortableSource } from 'abortable-iterator'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Pushable } from 'it-pushable'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Source } from 'it-stream-types'\nimport type { Reader } from 'it-reader'\nimport type { MultistreamSelectInit } from '.'\n\nconst NewLine = uint8ArrayFromString('\\n')\n\nexport function encode (buffer: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const list = new Uint8ArrayList(buffer, NewLine)\n\n return lp.encode.single(list)\n}\n\n/**\n * `write` encodes and writes a single buffer\n */\nexport function write (writer: Pushable, buffer: Uint8Array | Uint8ArrayList, options: MultistreamSelectInit = {}) {\n const encoded = encode(buffer)\n\n if (options.writeBytes === true) {\n writer.push(encoded.subarray())\n } else {\n writer.push(encoded)\n }\n}\n\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport function writeAll (writer: Pushable, buffers: Uint8Array[], options: MultistreamSelectInit = {}) {\n const list = new Uint8ArrayList()\n\n for (const buf of buffers) {\n list.append(encode(buf))\n }\n\n if (options.writeBytes === true) {\n writer.push(list.subarray())\n } else {\n writer.push(list)\n }\n}\n\nexport async function read (reader: Reader, options?: AbortOptions): Promise {\n let byteLength = 1 // Read single byte chunks until the length is known\n const varByteSource = { // No return impl - we want the reader to remain readable\n [Symbol.asyncIterator]: () => varByteSource,\n next: async () => await reader.next(byteLength)\n }\n\n let input: Source = varByteSource\n\n // If we have been passed an abort signal, wrap the input source in an abortable\n // iterator that will throw if the operation is aborted\n if (options?.signal != null) {\n input = abortableSource(varByteSource, options.signal)\n }\n\n // Once the length has been parsed, read chunk for that length\n const onLength = (l: number) => {\n byteLength = l\n }\n\n const buf = await pipe(\n input,\n lp.decode({ onLength }),\n async (source) => await first(source)\n )\n\n if (buf == null) {\n throw errCode(new Error('no buffer returned'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n if (buf.get(buf.byteLength - 1) !== NewLine[0]) {\n throw errCode(new Error('missing newline'), 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE')\n }\n\n return buf.sublist(0, -1) // Remove newline\n}\n\nexport async function readString (reader: Reader, options?: AbortOptions) {\n const buf = await read(reader, options)\n\n return uint8ArrayToString(buf.subarray())\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { PROTOCOL_ID } from './index.js'\nimport type { Duplex } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:select')\n\nexport async function select (stream: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function select (stream: Duplex, protocols: string | string[], options: MultistreamSelectInit = {}): Promise> {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols]\n const { reader, writer, rest, stream: shakeStream } = handshake(stream)\n\n const protocol = protocols.shift()\n\n if (protocol == null) {\n throw new Error('At least one protocol must be specified')\n }\n\n log('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol)\n const p1 = uint8ArrayFromString(PROTOCOL_ID)\n const p2 = uint8ArrayFromString(protocol)\n multistream.writeAll(writer, [p1, p2], options)\n\n let response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(reader, options)\n log('select: read \"%s\"', response)\n }\n\n // We're done\n if (response === protocol) {\n rest()\n return { stream: shakeStream, protocol }\n }\n\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n log('select: write \"%s\"', protocol)\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n const response = await multistream.readString(reader, options)\n log('select: read \"%s\" for \"%s\"', response, protocol)\n\n if (response === protocol) {\n rest() // End our writer so others can start writing to stream\n return { stream: shakeStream, protocol }\n }\n }\n\n rest()\n throw errCode(new Error('protocol selection failed'), 'ERR_UNSUPPORTED_PROTOCOL')\n}\n","import { logger } from '@libp2p/logger'\nimport * as multistream from './multistream.js'\nimport { handshake } from 'it-handshake'\nimport { PROTOCOL_ID } from './constants.js'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { Duplex } from 'it-stream-types'\nimport type { ByteArrayInit, ByteListInit, MultistreamSelectInit, ProtocolStream } from './index.js'\n\nconst log = logger('libp2p:mss:handle')\n\nexport async function handle (stream: Duplex, protocols: string | string[], options: ByteArrayInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: ByteListInit): Promise>\nexport async function handle (stream: Duplex, protocols: string | string[], options?: MultistreamSelectInit): Promise> {\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n const { writer, reader, rest, stream: shakeStream } = handshake(stream)\n\n while (true) {\n const protocol = await multistream.readString(reader, options)\n log('read \"%s\"', protocol)\n\n if (protocol === PROTOCOL_ID) {\n log('respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n multistream.write(writer, uint8ArrayFromString(PROTOCOL_ID), options)\n continue\n }\n\n if (protocols.includes(protocol)) {\n multistream.write(writer, uint8ArrayFromString(protocol), options)\n log('respond with \"%s\" for \"%s\"', protocol, protocol)\n rest()\n return { stream: shakeStream, protocol }\n }\n\n if (protocol === 'ls') {\n // \\n\\n\\n\n multistream.write(writer, new Uint8ArrayList(...protocols.map(p => multistream.encode(uint8ArrayFromString(p)))), options)\n // multistream.writeAll(writer, protocols.map(p => uint8ArrayFromString(p)))\n log('respond with \"%s\" for %s', protocols, protocol)\n continue\n }\n\n multistream.write(writer, uint8ArrayFromString('na'), options)\n log('respond with \"na\" for \"%s\"', protocol)\n }\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type * as Status from './status.js'\nimport type { Duplex } from 'it-stream-types'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface ConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\nexport type Direction = 'inbound' | 'outbound'\n\nexport interface ConnectionStat {\n /**\n * Outbound conections are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the connection\n */\n timeline: ConnectionTimeline\n\n /**\n * Once a multiplexer has been negotiated for this stream, it will be set on the stat object\n */\n multiplexer?: string\n\n /**\n * Once a connection encrypter has been negotiated for this stream, it will be set on the stat object\n */\n encryption?: string\n\n /**\n * The current status of the connection\n */\n status: keyof typeof Status\n}\n\nexport interface StreamTimeline {\n open: number\n close?: number\n}\n\nexport interface StreamStat {\n /**\n * Outbound streams are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the stream\n */\n timeline: StreamTimeline\n\n /**\n * Once a protocol has been negotiated for this stream, it will be set on the stat object\n */\n protocol?: string\n}\n\n/**\n * A Stream is a data channel between two peers that\n * can be written to and read from at both ends.\n *\n * It may be encrypted and multiplexed depending on the\n * configuration of the nodes.\n */\nexport interface Stream extends Duplex {\n /**\n * Close a stream for reading and writing\n */\n close: () => void\n\n /**\n * Close a stream for reading only\n */\n closeRead: () => void\n\n /**\n * Close a stream for writing only\n */\n closeWrite: () => void\n\n /**\n * Call when a local error occurs, should close the stream for reading and writing\n */\n abort: (err: Error) => void\n\n /**\n * Call when a remote error occurs, should close the stream for reading and writing\n */\n reset: () => void\n\n /**\n * Unique identifier for a stream\n */\n id: string\n\n /**\n * Stats about this stream\n */\n stat: StreamStat\n\n /**\n * User defined stream metadata\n */\n metadata: Record\n}\n\n/**\n * A Connection is a high-level representation of a connection\n * to a remote peer that may have been secured by encryption and\n * multiplexed, depending on the configuration of the nodes\n * between which the connection is made.\n */\nexport interface Connection {\n id: string\n stat: ConnectionStat\n remoteAddr: Multiaddr\n remotePeer: PeerId\n tags: string[]\n streams: Stream[]\n\n newStream: (multicodecs: string | string[], options?: AbortOptions) => Promise\n addStream: (stream: Stream) => void\n removeStream: (id: string) => void\n close: () => Promise\n}\n\nexport const symbol = Symbol.for('@libp2p/connection')\n\nexport function isConnection (other: any): other is Connection {\n return other != null && Boolean(other[symbol])\n}\n\nexport interface ConnectionGater {\n /**\n * denyDialMultiaddr tests whether we're permitted to Dial the\n * specified peer.\n *\n * This is called by the dialer.connectToPeer implementation before\n * dialling a peer.\n *\n * Return true to prevent dialing the passed peer.\n */\n denyDialPeer: (peerId: PeerId) => Promise\n\n /**\n * denyDialMultiaddr tests whether we're permitted to dial the specified\n * multiaddr for the given peer.\n *\n * This is called by the dialer.connectToPeer implementation after it has\n * resolved the peer's addrs, and prior to dialling each.\n *\n * Return true to prevent dialing the passed peer on the passed multiaddr.\n */\n denyDialMultiaddr: (peerId: PeerId, multiaddr: Multiaddr) => Promise\n\n /**\n * denyInboundConnection tests whether an incipient inbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has accepted a connection from its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyInboundConnection: (maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundConnection tests whether an incipient outbound connection is allowed.\n *\n * This is called by the upgrader, or by the transport directly (e.g. QUIC,\n * Bluetooth), straight after it has created a connection with its socket.\n *\n * Return true to deny the incoming passed connection.\n */\n denyOutboundConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyInboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundEncryptedConnection tests whether a given connection, now encrypted,\n * is allowed.\n *\n * This is called by the upgrader, after it has performed the security\n * handshake, and before it negotiates the muxer, or by the directly by the\n * transport, at the exact same checkpoint.\n *\n * Return true to deny the passed secured connection.\n */\n denyOutboundEncryptedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyInboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyInboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * denyOutboundUpgradedConnection tests whether a fully capable connection is allowed.\n *\n * This is called after encryption has been negotiated and the connection has been\n * multiplexed, if a multiplexer is configured.\n *\n * Return true to deny the passed upgraded connection.\n */\n denyOutboundUpgradedConnection: (peerId: PeerId, maConn: MultiaddrConnection) => Promise\n\n /**\n * Used by the address book to filter passed addresses.\n *\n * Return true to allow storing the passed multiaddr for the passed peer.\n */\n filterMultiaddrForPeer: (peer: PeerId, multiaddr: Multiaddr) => Promise\n}\n\nexport interface ConnectionProtector {\n\n /**\n * Takes a given Connection and creates a private encryption stream\n * between its two peers from the PSK the Protector instance was\n * created with.\n */\n protect: (connection: MultiaddrConnection) => Promise\n}\n\nexport interface MultiaddrConnectionTimeline {\n open: number\n upgraded?: number\n close?: number\n}\n\n/**\n * A MultiaddrConnection is returned by transports after dialing\n * a peer. It is a low-level primitive and is the raw connection\n * without encryption or stream multiplexing.\n */\nexport interface MultiaddrConnection extends Duplex {\n close: (err?: Error) => Promise\n remoteAddr: Multiaddr\n timeline: MultiaddrConnectionTimeline\n}\n","import type { Multiaddr } from '@multiformats/multiaddr'\nimport errCode from 'err-code'\nimport { OPEN, CLOSING, CLOSED } from '@libp2p/interface-connection/status'\nimport { symbol } from '@libp2p/interface-connection'\nimport type { Connection, ConnectionStat, Stream } from '@libp2p/interface-connection'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\nconst log = logger('libp2p:connection')\n\ninterface ConnectionInit {\n remoteAddr: Multiaddr\n remotePeer: PeerId\n newStream: (protocols: string[], options?: AbortOptions) => Promise\n close: () => Promise\n getStreams: () => Stream[]\n stat: ConnectionStat\n}\n\n/**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\nexport class ConnectionImpl implements Connection {\n /**\n * Connection identifier.\n */\n public readonly id: string\n\n /**\n * Observed multiaddr of the remote peer\n */\n public readonly remoteAddr: Multiaddr\n\n /**\n * Remote peer id\n */\n public readonly remotePeer: PeerId\n\n /**\n * Connection metadata\n */\n public readonly stat: ConnectionStat\n\n /**\n * User provided tags\n *\n */\n public tags: string[]\n\n /**\n * Reference to the new stream function of the multiplexer\n */\n private readonly _newStream: (protocols: string[], options?: AbortOptions) => Promise\n\n /**\n * Reference to the close function of the raw connection\n */\n private readonly _close: () => Promise\n\n /**\n * Reference to the getStreams function of the muxer\n */\n private readonly _getStreams: () => Stream[]\n\n private _closing: boolean\n\n /**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\n constructor (init: ConnectionInit) {\n const { remoteAddr, remotePeer, newStream, close, getStreams, stat } = init\n\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`\n this.remoteAddr = remoteAddr\n this.remotePeer = remotePeer\n this.stat = {\n ...stat,\n status: OPEN\n }\n this._newStream = newStream\n this._close = close\n this._getStreams = getStreams\n this.tags = []\n this._closing = false\n }\n\n get [Symbol.toStringTag] () {\n return 'Connection'\n }\n\n get [symbol] () {\n return true\n }\n\n /**\n * Get all the streams of the muxer\n */\n get streams () {\n return this._getStreams()\n }\n\n /**\n * Create a new stream from this connection\n */\n async newStream (protocols: string | string[], options?: AbortOptions): Promise {\n if (this.stat.status === CLOSING) {\n throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED')\n }\n\n if (this.stat.status === CLOSED) {\n throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED')\n }\n\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n const stream = await this._newStream(protocols, options)\n\n stream.stat.direction = 'outbound'\n\n return stream\n }\n\n /**\n * Add a stream when it is opened to the registry\n */\n addStream (stream: Stream) {\n stream.stat.direction = 'inbound'\n }\n\n /**\n * Remove stream registry after it is closed\n */\n removeStream (id: string) {\n\n }\n\n /**\n * Close the connection\n */\n async close () {\n if (this.stat.status === CLOSED || this._closing) {\n return\n }\n\n this.stat.status = CLOSING\n\n // close all streams - this can throw if we're not multiplexed\n try {\n this.streams.forEach(s => s.close())\n } catch (err) {\n log.error(err)\n }\n\n // Close raw connection\n this._closing = true\n await this._close()\n this._closing = false\n\n this.stat.timeline.close = Date.now()\n this.stat.status = CLOSED\n }\n}\n\nexport function createConnection (init: ConnectionInit): Connection {\n return new ConnectionImpl(init)\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isTopology, StreamHandlerOptions, StreamHandlerRecord } from '@libp2p/interface-registrar'\nimport merge from 'merge-options'\nimport type { Registrar, StreamHandler, Topology } from '@libp2p/interface-registrar'\nimport type { PeerProtocolsChangeData } from '@libp2p/interface-peer-store'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:registrar')\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar implements Registrar {\n private readonly topologies: Map>\n private readonly handlers: Map\n private readonly components: Components\n\n constructor (components: Components) {\n this.topologies = new Map()\n this.handlers = new Map()\n this.components = components\n\n this._onDisconnect = this._onDisconnect.bind(this)\n this._onProtocolChange = this._onProtocolChange.bind(this)\n\n this.components.getConnectionManager().addEventListener('peer:disconnect', this._onDisconnect)\n\n // happens after identify\n this.components.getPeerStore().addEventListener('change:protocols', this._onProtocolChange)\n }\n\n getProtocols () {\n return Array.from(new Set([\n ...this.topologies.keys(),\n ...this.handlers.keys()\n ])).sort()\n }\n\n getHandler (protocol: string) {\n const handler = this.handlers.get(protocol)\n\n if (handler == null) {\n throw errCode(new Error(`No handler registered for protocol ${protocol}`), codes.ERR_NO_HANDLER_FOR_PROTOCOL)\n }\n\n return handler\n }\n\n getTopologies (protocol: string) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n return []\n }\n\n return [\n ...topologies.values()\n ]\n }\n\n /**\n * Registers the `handler` for each protocol\n */\n async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise {\n if (this.handlers.has(protocol)) {\n throw errCode(new Error(`Handler already registered for protocol ${protocol}`), codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED)\n }\n\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts)\n\n this.handlers.set(protocol, {\n handler,\n options\n })\n\n // Add new protocols to self protocols in the Protobook\n await this.components.getPeerStore().protoBook.add(this.components.getPeerId(), [protocol])\n }\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle (protocols: string | string[]) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols]\n\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol)\n })\n\n // Remove protocols from self protocols in the Protobook\n await this.components.getPeerStore().protoBook.remove(this.components.getPeerId(), protocolList)\n }\n\n /**\n * Register handlers for a set of multicodecs given\n */\n async register (protocol: string, topology: Topology): Promise {\n if (!isTopology(topology)) {\n log.error('topology must be an instance of interfaces/topology')\n throw errCode(new Error('topology must be an instance of interfaces/topology'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n\n let topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n topologies = new Map()\n this.topologies.set(protocol, topologies)\n }\n\n topologies.set(id, topology)\n\n // Set registrar\n await topology.setRegistrar(this)\n\n return id\n }\n\n /**\n * Unregister topology\n */\n unregister (id: string) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id)\n\n if (topologies.size === 0) {\n this.topologies.delete(protocol)\n }\n }\n }\n }\n\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect (evt: CustomEvent) {\n const connection = evt.detail\n\n void this.components.getPeerStore().protoBook.get(connection.remotePeer)\n .then(peerProtocols => {\n for (const protocol of peerProtocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(connection.remotePeer)\n }\n }\n })\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Check if a new peer support the multicodecs for this topology\n */\n _onProtocolChange (evt: CustomEvent) {\n const { peerId, protocols, oldProtocols } = evt.detail\n\n const removed = oldProtocols.filter(protocol => !protocols.includes(protocol))\n const added = protocols.filter(protocol => !oldProtocols.includes(protocol))\n\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n topology.onDisconnect(peerId)\n }\n }\n\n for (const protocol of added) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n const connection = this.components.getConnectionManager().getConnections(peerId)[0]\n\n if (connection == null) {\n continue\n }\n\n topology.onConnect(peerId, connection)\n }\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as mss from '@libp2p/multistream-select'\nimport { pipe } from 'it-pipe'\n// @ts-expect-error mutable-proxy does not export types\nimport mutableProxy from 'mutable-proxy'\nimport { codes } from './errors.js'\nimport { createConnection } from '@libp2p/connection'\nimport { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport type { MultiaddrConnection, Connection, Stream } from '@libp2p/interface-connection'\nimport type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'\nimport type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Upgrader, UpgraderEvents } from '@libp2p/interface-transport'\nimport type { Duplex } from 'it-stream-types'\nimport { Components, isInitializable } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport type { Registrar } from '@libp2p/interface-registrar'\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:upgrader')\n\ninterface CreateConectionOptions {\n cryptoProtocol: string\n direction: 'inbound' | 'outbound'\n maConn: MultiaddrConnection\n upgradedConn: Duplex\n remotePeer: PeerId\n muxerFactory?: StreamMuxerFactory\n}\n\ninterface OnStreamOptions {\n connection: Connection\n stream: Stream\n protocol: string\n}\n\nexport interface CryptoResult extends SecuredConnection {\n protocol: string\n}\n\nexport interface UpgraderInit {\n connectionEncryption: ConnectionEncrypter[]\n muxers: StreamMuxerFactory[]\n\n /**\n * An amount of ms by which an inbound connection upgrade\n * must complete\n */\n inboundUpgradeTimeout: number\n}\n\nfunction findIncomingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxInboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_INBOUND_STREAMS\n}\n\nfunction findOutgoingStreamLimit (protocol: string, registrar: Registrar) {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxOutboundStreams\n } catch (err: any) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err\n }\n }\n\n return DEFAULT_MAX_OUTBOUND_STREAMS\n}\n\nfunction countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection) {\n let streamCount = 0\n\n connection.streams.forEach(stream => {\n if (stream.stat.direction === direction && stream.stat.protocol === protocol) {\n streamCount++\n }\n })\n\n return streamCount\n}\n\nexport class DefaultUpgrader extends EventEmitter implements Upgrader {\n private readonly components: Components\n private readonly connectionEncryption: Map\n private readonly muxers: Map\n private readonly inboundUpgradeTimeout: number\n\n constructor (components: Components, init: UpgraderInit) {\n super()\n\n this.components = components\n this.connectionEncryption = new Map()\n\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter)\n })\n\n this.muxers = new Map()\n\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer)\n })\n\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout\n }\n\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound (maConn: MultiaddrConnection): Promise {\n let encryptedConn\n let remotePeer\n let upgradedConn: Duplex\n let muxerFactory: StreamMuxerFactory | undefined\n let cryptoProtocol\n let setPeer\n let proxyPeer\n const metrics = this.components.getMetrics()\n\n const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const abortableStream = abortableDuplex(maConn, timeoutController.signal)\n maConn.source = abortableStream.source\n maConn.sink = abortableStream.sink\n\n if (await this.components.getConnectionGater().denyInboundConnection(maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())\n const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n setPeer({ toString: () => idString })\n metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })\n }\n\n log('starting the inbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n const protector = this.components.getConnectionProtector()\n\n if (protector != null) {\n log('protecting the inbound connection')\n protectedConn = await protector.protect(maConn)\n }\n\n try {\n // Encrypt the connection\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptInbound(protectedConn))\n\n if (await this.components.getConnectionGater().denyInboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n // Multiplex the connection\n if (this.muxers.size > 0) {\n const multiplexed = await this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers)\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n } else {\n upgradedConn = encryptedConn\n }\n } catch (err: any) {\n log.error('Failed to upgrade inbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n if (await this.components.getConnectionGater().denyInboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n metrics.updatePlaceholder(proxyPeer, remotePeer)\n setPeer(remotePeer)\n }\n\n log('Successfully upgraded inbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n } finally {\n timeoutController.clear()\n }\n }\n\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound (maConn: MultiaddrConnection): Promise {\n const idStr = maConn.remoteAddr.getPeerId()\n if (idStr == null) {\n throw errCode(new Error('outbound connection must have a peer id'), codes.ERR_INVALID_MULTIADDR)\n }\n\n const remotePeerId = peerIdFromString(idStr)\n\n if (await this.components.getConnectionGater().denyOutboundConnection(remotePeerId, maConn)) {\n throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n let encryptedConn\n let remotePeer\n let upgradedConn\n let cryptoProtocol\n let muxerFactory\n let setPeer\n let proxyPeer\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())\n const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n setPeer({ toB58String: () => idString })\n metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })\n }\n\n log('Starting the outbound connection upgrade')\n\n // Protect\n let protectedConn = maConn\n const protector = this.components.getConnectionProtector()\n\n if (protector != null) {\n protectedConn = await protector.protect(maConn)\n }\n\n try {\n // Encrypt the connection\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptOutbound(protectedConn, remotePeerId))\n\n if (await this.components.getConnectionGater().denyOutboundEncryptedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n // Multiplex the connection\n if (this.muxers.size > 0) {\n const multiplexed = await this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers)\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n } else {\n upgradedConn = encryptedConn\n }\n } catch (err: any) {\n log.error('Failed to upgrade outbound connection', err)\n await maConn.close(err)\n throw err\n }\n\n if (await this.components.getConnectionGater().denyOutboundUpgradedConnection(remotePeer, {\n ...protectedConn,\n ...encryptedConn\n })) {\n throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)\n }\n\n if (metrics != null) {\n metrics.updatePlaceholder(proxyPeer, remotePeer)\n setPeer(remotePeer)\n }\n\n log('Successfully upgraded outbound connection')\n\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer\n })\n }\n\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection (opts: CreateConectionOptions): Connection {\n const {\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n remotePeer,\n muxerFactory\n } = opts\n\n let muxer: StreamMuxer | undefined\n let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise) | undefined\n let connection: Connection // eslint-disable-line prefer-const\n\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return\n }\n\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.getRegistrar().getProtocols()\n const { stream, protocol } = await mss.handle(muxedStream, protocols)\n log('%s: incoming stream opened on %s', direction, protocol)\n\n const metrics = this.components.getMetrics()\n\n if (metrics != null) {\n metrics.trackStream({ stream, remotePeer, protocol })\n }\n\n if (connection == null) {\n return\n }\n\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.getRegistrar())\n const streamCount = countStreams(protocol, 'inbound', connection)\n\n if (streamCount === incomingLimit) {\n muxedStream.abort(errCode(new Error(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`), codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS))\n\n return\n }\n\n muxedStream.stat.protocol = protocol\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n this.components.getPeerStore().protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))\n\n connection.addStream(muxedStream)\n this._onStream({ connection, stream: { ...muxedStream, ...stream }, protocol })\n })\n .catch(err => {\n log.error(err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n })\n },\n // Run anytime a stream closes\n onStreamEnd: muxedStream => {\n connection?.removeStream(muxedStream.id)\n }\n })\n\n if (isInitializable(muxer)) {\n muxer.init(this.components)\n }\n\n newStream = async (protocols: string[], options: AbortOptions = {}): Promise => {\n if (muxer == null) {\n throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE)\n }\n\n log('%s: starting new stream on %s', direction, protocols)\n const muxedStream = muxer.newStream()\n const metrics = this.components.getMetrics()\n let controller: TimeoutController | undefined\n\n try {\n if (options.signal == null) {\n log('No abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)\n\n controller = new TimeoutController(30000)\n options.signal = controller.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n }\n\n const { stream, protocol } = await mss.select(muxedStream, protocols, options)\n\n if (metrics != null) {\n metrics.trackStream({ stream, remotePeer, protocol })\n }\n\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.getRegistrar())\n const streamCount = countStreams(protocol, 'outbound', connection)\n\n if (streamCount === outgoingLimit) {\n const err = errCode(new Error(`Too many outbound protocol streams for protocol \"${protocol}\" - limit ${outgoingLimit}`), codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)\n muxedStream.abort(err)\n\n throw err\n }\n\n muxedStream.stat.protocol = protocol\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n this.components.getPeerStore().protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))\n\n return {\n ...muxedStream,\n ...stream,\n stat: {\n ...muxedStream.stat,\n protocol\n }\n }\n } catch (err: any) {\n log.error('could not create new stream', err)\n\n if (muxedStream.stat.timeline.close == null) {\n muxedStream.close()\n }\n\n if (err.code != null) {\n throw err\n }\n\n throw errCode(err, codes.ERR_UNSUPPORTED_PROTOCOL)\n } finally {\n if (controller != null) {\n controller.clear()\n }\n }\n }\n\n // Pipe all data through the muxer\n pipe(upgradedConn, muxer, upgradedConn).catch(log.error)\n }\n\n const _timeline = maConn.timeline\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.stat.status === 'OPEN') {\n await connection.close()\n }\n } catch (err: any) {\n log.error(err)\n } finally {\n this.dispatchEvent(new CustomEvent('connectionEnd', {\n detail: connection\n }))\n }\n })().catch(err => {\n log.error(err)\n })\n }\n\n return Reflect.set(...args)\n }\n })\n maConn.timeline.upgraded = Date.now()\n\n const errConnectionNotMultiplexed = () => {\n throw errCode(new Error('connection is not multiplexed'), codes.ERR_CONNECTION_NOT_MULTIPLEXED)\n }\n\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer: remotePeer,\n stat: {\n status: 'OPEN',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol\n },\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => muxer != null ? muxer.streams : errConnectionNotMultiplexed(),\n close: async () => {\n await maConn.close()\n // Ensure remaining streams are closed\n if (muxer != null) {\n muxer.close()\n }\n }\n })\n\n this.dispatchEvent(new CustomEvent('connection', {\n detail: connection\n }))\n\n return connection\n }\n\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream (opts: OnStreamOptions): void {\n const { connection, stream, protocol } = opts\n const { handler } = this.components.getRegistrar().getHandler(protocol)\n\n handler({ connection, stream })\n }\n\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound (connection: Duplex): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('handling inbound crypto protocol selection', protocols)\n\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting inbound connection...')\n\n return {\n ...await encrypter.secureInbound(this.components.getPeerId(), stream),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\n }\n\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound (connection: MultiaddrConnection, remotePeerId: PeerId): Promise {\n const protocols = Array.from(this.connectionEncryption.keys())\n log('selecting outbound crypto protocol', protocols)\n\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n const encrypter = this.connectionEncryption.get(protocol)\n\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`)\n }\n\n log('encrypting outbound connection to %p', remotePeerId)\n\n return {\n ...await encrypter.secureOutbound(this.components.getPeerId(), stream, remotePeerId),\n protocol\n }\n } catch (err: any) {\n throw errCode(err, codes.ERR_ENCRYPTION_FAILED)\n }\n }\n\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map): Promise<{ stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('outbound selecting muxer %s', protocols)\n try {\n const { stream, protocol } = await mss.select(connection, protocols, {\n writeBytes: true\n })\n log('%s selected as muxer protocol', protocol)\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing outbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound (connection: MultiaddrConnection, muxers: Map): Promise<{ stream: Duplex, muxerFactory?: StreamMuxerFactory}> {\n const protocols = Array.from(muxers.keys())\n log('inbound handling muxers %s', protocols)\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n writeBytes: true\n })\n const muxerFactory = muxers.get(protocol)\n return { stream, muxerFactory }\n } catch (err: any) {\n log.error('error multiplexing inbound stream', err)\n throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Identify {\n protocolVersion?: string\n agentVersion?: string\n publicKey?: Uint8Array\n listenAddrs: Uint8Array[]\n observedAddr?: Uint8Array\n protocols: string[]\n signedPeerRecord?: Uint8Array\n}\n\nexport namespace Identify {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.protocolVersion != null) {\n writer.uint32(42)\n writer.string(obj.protocolVersion)\n }\n\n if (obj.agentVersion != null) {\n writer.uint32(50)\n writer.string(obj.agentVersion)\n }\n\n if (obj.publicKey != null) {\n writer.uint32(10)\n writer.bytes(obj.publicKey)\n }\n\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n writer.uint32(18)\n writer.bytes(value)\n }\n } else {\n throw new Error('Protocol error: required field \"listenAddrs\" was not found in object')\n }\n\n if (obj.observedAddr != null) {\n writer.uint32(34)\n writer.bytes(obj.observedAddr)\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n writer.uint32(26)\n writer.string(value)\n }\n } else {\n throw new Error('Protocol error: required field \"protocols\" was not found in object')\n }\n\n if (obj.signedPeerRecord != null) {\n writer.uint32(66)\n writer.bytes(obj.signedPeerRecord)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 5:\n obj.protocolVersion = reader.string()\n break\n case 6:\n obj.agentVersion = reader.string()\n break\n case 1:\n obj.publicKey = reader.bytes()\n break\n case 2:\n obj.listenAddrs = obj.listenAddrs ?? []\n obj.listenAddrs.push(reader.bytes())\n break\n case 4:\n obj.observedAddr = reader.bytes()\n break\n case 3:\n obj.protocols = obj.protocols ?? []\n obj.protocols.push(reader.string())\n break\n case 8:\n obj.signedPeerRecord = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n obj.listenAddrs = obj.listenAddrs ?? []\n obj.protocols = obj.protocols ?? []\n\n if (obj.listenAddrs == null) {\n throw new Error('Protocol error: value for required field \"listenAddrs\" was not found in protobuf')\n }\n\n if (obj.protocols == null) {\n throw new Error('Protocol error: value for required field \"protocols\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Identify): Uint8Array => {\n return encodeMessage(obj, Identify.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Identify => {\n return decodeMessage(buf, Identify.codec())\n }\n}\n","export const version = '0.38.0'\nexport const name = 'libp2p'\n","\nimport { version } from '../version.js'\n\nexport const PROTOCOL_VERSION = 'ipfs/0.1.0' // deprecated\nexport const AGENT_VERSION = `js-libp2p/${version}`\nexport const MULTICODEC_IDENTIFY = '/ipfs/id/1.0.0' // deprecated\nexport const MULTICODEC_IDENTIFY_PUSH = '/ipfs/id/push/1.0.0' // deprecated\n\nexport const IDENTIFY_PROTOCOL_VERSION = '0.1.0'\nexport const MULTICODEC_IDENTIFY_PROTOCOL_NAME = 'id'\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME = 'id/push'\nexport const MULTICODEC_IDENTIFY_PROTOCOL_VERSION = '1.0.0'\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION = '1.0.0'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport drain from 'it-drain'\nimport first from 'it-first'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Multiaddr, protocols } from '@multiformats/multiaddr'\nimport { Identify } from './pb/message.js'\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport {\n MULTICODEC_IDENTIFY,\n MULTICODEC_IDENTIFY_PUSH,\n IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME,\n MULTICODEC_IDENTIFY_PROTOCOL_VERSION,\n MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION\n} from './consts.js'\nimport { codes } from '../errors.js'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Connection, Stream } from '@libp2p/interface-connection'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { peerIdFromKeys } from '@libp2p/peer-id'\nimport type { Components } from '@libp2p/components'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:identify')\n\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8\n\nexport interface HostProperties {\n agentVersion: string\n}\n\nexport interface IdentifyServiceInit {\n /**\n * The prefix to use for the protocol (default: 'ipfs')\n */\n protocolPrefix: string\n\n /**\n * What details we should send as part of an identify message\n */\n host: HostProperties\n\n /**\n * How long we should wait for a remote peer to send their identify response\n */\n timeout: number\n\n /**\n * Identify responses larger than this in bytes will be rejected (default: 8192)\n */\n maxIdentifyMessageSize?: number\n\n maxInboundStreams: number\n maxOutboundStreams: number\n\n maxPushIncomingStreams: number\n maxPushOutgoingStreams: number\n}\n\nexport class IdentifyService implements Startable {\n private readonly components: Components\n private readonly identifyProtocolStr: string\n private readonly identifyPushProtocolStr: string\n private readonly host: {\n protocolVersion: string\n agentVersion: string\n }\n\n private readonly init: IdentifyServiceInit\n private started: boolean\n\n constructor (components: Components, init: IdentifyServiceInit) {\n this.components = components\n this.started = false\n this.init = init\n\n this.identifyProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`\n this.identifyPushProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`\n\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n ...init.host\n }\n\n // When a new connection happens, trigger identify\n this.components.getConnectionManager().addEventListener('peer:connect', (evt) => {\n const connection = evt.detail\n this.identify(connection).catch(log.error)\n })\n\n // When self multiaddrs change, trigger identify-push\n this.components.getPeerStore().addEventListener('change:multiaddrs', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.getPeerId().equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n\n // When self protocols change, trigger identify-push\n this.components.getPeerStore().addEventListener('change:protocols', (evt) => {\n const { peerId } = evt.detail\n\n if (this.components.getPeerId().equals(peerId)) {\n void this.pushToPeerStore().catch(err => log.error(err))\n }\n })\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n if (this.started) {\n return\n }\n\n await this.components.getPeerStore().metadataBook.setValue(this.components.getPeerId(), 'AgentVersion', uint8ArrayFromString(this.host.agentVersion))\n await this.components.getPeerStore().metadataBook.setValue(this.components.getPeerId(), 'ProtocolVersion', uint8ArrayFromString(this.host.protocolVersion))\n\n await this.components.getRegistrar().handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n await this.components.getRegistrar().handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n log.error(err)\n })\n }, {\n maxInboundStreams: this.init.maxPushIncomingStreams,\n maxOutboundStreams: this.init.maxPushOutgoingStreams\n })\n\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.identifyProtocolStr)\n await this.components.getRegistrar().unhandle(this.identifyPushProtocolStr)\n\n this.started = false\n }\n\n /**\n * Send an Identify Push update to the list of connections\n */\n async push (connections: Connection[]): Promise {\n const signedPeerRecord = await this.components.getPeerStore().addressBook.getRawEnvelope(this.components.getPeerId())\n const listenAddrs = this.components.getAddressManager().getAddresses().map((ma) => ma.bytes)\n const protocols = await this.components.getPeerStore().protoBook.get(this.components.getPeerId())\n\n const pushes = connections.map(async connection => {\n let stream: Stream | undefined\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n stream = await connection.newStream([this.identifyPushProtocolStr], {\n signal: timeoutController.signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n await pipe(\n [Identify.encode({\n listenAddrs,\n signedPeerRecord,\n protocols\n })],\n lp.encode(),\n source,\n drain\n )\n } catch (err: any) {\n // Just log errors\n log.error('could not push identify update to peer', err)\n } finally {\n if (stream != null) {\n stream.close()\n }\n\n timeoutController.clear()\n }\n })\n\n await Promise.all(pushes)\n }\n\n /**\n * Calls `push` on all peer connections\n */\n async pushToPeerStore () {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return\n }\n\n const connections: Connection[] = []\n\n for (const conn of this.components.getConnectionManager().getConnections()) {\n const peerId = conn.remotePeer\n const peer = await this.components.getPeerStore().get(peerId)\n\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n continue\n }\n\n connections.push(conn)\n }\n\n await this.push(connections)\n }\n\n async _identify (connection: Connection, options: AbortOptions = {}): Promise {\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.identifyProtocolStr], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data == null) {\n throw errCode(new Error('No data could be retrieved'), codes.ERR_CONNECTION_ENDED)\n }\n\n try {\n return Identify.decode(data)\n } catch (err: any) {\n throw errCode(err, codes.ERR_INVALID_MESSAGE)\n }\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Requests the `Identify` message from peer associated with the given `connection`.\n * If the identified peer does not match the `PeerId` associated with the connection,\n * an error will be thrown.\n */\n async identify (connection: Connection, options: AbortOptions = {}): Promise {\n const message = await this._identify(connection, options)\n\n const {\n publicKey,\n listenAddrs,\n protocols,\n observedAddr,\n signedPeerRecord,\n agentVersion,\n protocolVersion\n } = message\n\n if (publicKey == null) {\n throw errCode(new Error('public key was missing from identify message'), codes.ERR_MISSING_PUBLIC_KEY)\n }\n\n const id = await peerIdFromKeys(publicKey)\n\n if (!connection.remotePeer.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (this.components.getPeerId().equals(id)) {\n throw errCode(new Error('identified peer is our own peer id?'), codes.ERR_INVALID_PEER)\n }\n\n // Get the observedAddr if there is one\n const cleanObservedAddr = IdentifyService.getCleanMultiaddr(observedAddr)\n\n if (signedPeerRecord != null) {\n log('received signed peer record from %p', id)\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(signedPeerRecord, PeerRecord.DOMAIN)\n\n if (!envelope.peerId.equals(id)) {\n throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER)\n }\n\n if (await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)) {\n await this.components.getPeerStore().protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n return\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('no signed peer record received from %p', id)\n }\n\n log('falling back to legacy addresses from %p', id)\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.getPeerStore().addressBook.set(id, listenAddrs.map((addr) => new Multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n await this.components.getPeerStore().protoBook.set(id, protocols)\n\n if (agentVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'AgentVersion', uint8ArrayFromString(agentVersion))\n }\n\n if (protocolVersion != null) {\n await this.components.getPeerStore().metadataBook.setValue(id, 'ProtocolVersion', uint8ArrayFromString(protocolVersion))\n }\n\n log('identify completed for peer %p and protocols %o', id, protocols)\n\n // TODO: Add and score our observed addr\n log('received observed address of %s', cleanObservedAddr?.toString())\n // this.components.getAddressManager().addObservedAddr(observedAddr)\n }\n\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async _handleIdentify (data: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n try {\n const publicKey = this.components.getPeerId().publicKey ?? new Uint8Array(0)\n const peerData = await this.components.getPeerStore().get(this.components.getPeerId())\n const multiaddrs = this.components.getAddressManager().getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n let signedPeerRecord = peerData.peerRecordEnvelope\n\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.components.getPeerId(),\n multiaddrs\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.getPeerId())\n await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)\n signedPeerRecord = envelope.marshal().subarray()\n }\n\n const message = Identify.encode({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr: connection.remoteAddr.bytes,\n protocols: peerData.protocols\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n await pipe(\n [message],\n lp.encode(),\n source,\n drain\n )\n } catch (err: any) {\n log.error('could not respond to identify request', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n }\n\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush (data: IncomingStreamData) {\n const { connection, stream } = data\n const timeoutController = new TimeoutController(this.init.timeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n\n let message: Identify | undefined\n try {\n // make stream abortable\n const source = abortableDuplex(stream, timeoutController.signal)\n\n const data = await pipe(\n [],\n source,\n lp.decode({\n maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }),\n async (source) => await first(source)\n )\n\n if (data != null) {\n message = Identify.decode(data)\n }\n } catch (err: any) {\n return log.error('received invalid message', err)\n } finally {\n stream.close()\n timeoutController.clear()\n }\n\n if (message == null) {\n return log.error('received invalid message')\n }\n\n const id = connection.remotePeer\n\n if (this.components.getPeerId().equals(id)) {\n log('received push from ourselves?')\n return\n }\n\n log('received push from %p', id)\n\n if (message.signedPeerRecord != null) {\n log('received signedPeerRecord in push')\n\n try {\n const envelope = await RecordEnvelope.openAndCertify(message.signedPeerRecord, PeerRecord.DOMAIN)\n\n if (await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)) {\n log('consumed signedPeerRecord sent in push')\n\n await this.components.getPeerStore().protoBook.set(id, message.protocols)\n return\n } else {\n log('failed to consume signedPeerRecord sent in push')\n }\n } catch (err: any) {\n log('received invalid envelope, discard it and fallback to listenAddrs is available', err)\n }\n } else {\n log('did not receive signedPeerRecord in push')\n }\n\n // LEGACY: Update peers data in PeerStore\n try {\n await this.components.getPeerStore().addressBook.set(id,\n message.listenAddrs.map((addr) => new Multiaddr(addr)))\n } catch (err: any) {\n log.error('received invalid addrs', err)\n }\n\n // Update the protocols\n try {\n await this.components.getPeerStore().protoBook.set(id, message.protocols)\n } catch (err: any) {\n log.error('received invalid protocols', err)\n }\n\n log('handled push from %p', id)\n }\n\n /**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\n static getCleanMultiaddr (addr: Uint8Array | string | null | undefined) {\n if (addr != null && addr.length > 0) {\n try {\n return new Multiaddr(addr)\n } catch {\n\n }\n }\n }\n}\n\n/**\n * The protocols the IdentifyService supports\n */\nexport const multicodecs = {\n IDENTIFY: MULTICODEC_IDENTIFY,\n IDENTIFY_PUSH: MULTICODEC_IDENTIFY_PUSH\n}\n\nexport const Message = { Identify }\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message, enumeration } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface FetchRequest {\n identifier: string\n}\n\nexport namespace FetchRequest {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.identifier != null) {\n writer.uint32(10)\n writer.string(obj.identifier)\n } else {\n throw new Error('Protocol error: required field \"identifier\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.identifier = reader.string()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.identifier == null) {\n throw new Error('Protocol error: value for required field \"identifier\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchRequest): Uint8Array => {\n return encodeMessage(obj, FetchRequest.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchRequest => {\n return decodeMessage(buf, FetchRequest.codec())\n }\n}\n\nexport interface FetchResponse {\n status: FetchResponse.StatusCode\n data: Uint8Array\n}\n\nexport namespace FetchResponse {\n export enum StatusCode {\n OK = 'OK',\n NOT_FOUND = 'NOT_FOUND',\n ERROR = 'ERROR'\n }\n\n enum __StatusCodeValues {\n OK = 0,\n NOT_FOUND = 1,\n ERROR = 2\n }\n\n export namespace StatusCode {\n export const codec = () => {\n return enumeration(__StatusCodeValues)\n }\n }\n\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.status != null) {\n writer.uint32(8)\n FetchResponse.StatusCode.codec().encode(obj.status, writer)\n } else {\n throw new Error('Protocol error: required field \"status\" was not found in object')\n }\n\n if (obj.data != null) {\n writer.uint32(18)\n writer.bytes(obj.data)\n } else {\n throw new Error('Protocol error: required field \"data\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.status = FetchResponse.StatusCode.codec().decode(reader)\n break\n case 2:\n obj.data = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.status == null) {\n throw new Error('Protocol error: value for required field \"status\" was not found in protobuf')\n }\n\n if (obj.data == null) {\n throw new Error('Protocol error: value for required field \"data\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: FetchResponse): Uint8Array => {\n return encodeMessage(obj, FetchResponse.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): FetchResponse => {\n return decodeMessage(buf, FetchResponse.codec())\n }\n}\n","\n// https://github.com/libp2p/specs/tree/master/fetch#wire-protocol\nexport const PROTOCOL_VERSION = '0.0.1'\nexport const PROTOCOL_NAME = 'fetch'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport * as lp from 'it-length-prefixed'\nimport { FetchRequest, FetchResponse } from './pb/proto.js'\nimport { PROTOCOL_NAME, PROTOCOL_VERSION } from './constants.js'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Stream } from '@libp2p/interface-connection'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { Components } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:fetch')\n\nexport interface FetchServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a remote peer to send any data\n */\n timeout: number\n}\n\nexport interface HandleMessageOptions {\n stream: Stream\n protocol: string\n}\n\nexport interface LookupFunction {\n (key: string): Promise\n}\n\n/**\n * A simple libp2p protocol for requesting a value corresponding to a key from a peer.\n * Developers can register one or more lookup function for retrieving the value corresponding to\n * a given key. Each lookup function must act on a distinct part of the overall key space, defined\n * by a fixed prefix that all keys that should be routed to that lookup function will start with.\n */\nexport class FetchService implements Startable {\n public readonly protocol: string\n private readonly components: Components\n private readonly lookupFunctions: Map\n private started: boolean\n private readonly init: FetchServiceInit\n\n constructor (components: Components, init: FetchServiceInit) {\n this.started = false\n this.components = components\n this.protocol = `/${init.protocolPrefix ?? 'libp2p'}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.lookupFunctions = new Map() // Maps key prefix to value lookup function\n this.handleMessage = this.handleMessage.bind(this)\n this.init = init\n }\n\n async start () {\n await this.components.getRegistrar().handle(this.protocol, (data) => {\n void this.handleMessage(data)\n .catch(err => {\n log.error(err)\n })\n .finally(() => {\n data.stream.close()\n })\n }, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * Sends a request to fetch the value associated with the given key from the given peer\n */\n async fetch (peer: PeerId, key: string, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const connection = await this.components.getConnectionManager().openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.protocol], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const result = await pipe(\n [FetchRequest.encode({ identifier: key })],\n lp.encode(),\n source,\n lp.decode(),\n async function (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n const response = FetchResponse.decode(buf)\n\n switch (response.status) {\n case (FetchResponse.StatusCode.OK): {\n return response.data\n }\n case (FetchResponse.StatusCode.NOT_FOUND): {\n return null\n }\n case (FetchResponse.StatusCode.ERROR): {\n const errmsg = (new TextDecoder()).decode(response.data)\n throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)\n }\n default: {\n throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)\n }\n }\n }\n )\n\n return result ?? null\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n\n /**\n * Invoked when a fetch request is received. Reads the request message off the given stream and\n * responds based on looking up the key in the request via the lookup callback that corresponds\n * to the key's prefix.\n */\n async handleMessage (data: IncomingStreamData) {\n const { stream } = data\n const self = this\n\n await pipe(\n stream,\n lp.decode(),\n async function * (source) {\n const buf = await first(source)\n\n if (buf == null) {\n throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)\n }\n\n // for await (const buf of source) {\n const request = FetchRequest.decode(buf)\n\n let response: FetchResponse\n const lookup = self._getLookupFunction(request.identifier)\n if (lookup != null) {\n const data = await lookup(request.identifier)\n if (data != null) {\n response = { status: FetchResponse.StatusCode.OK, data }\n } else {\n response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }\n }\n } else {\n const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier)\n response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }\n }\n\n yield FetchResponse.encode(response)\n },\n lp.encode(),\n stream\n )\n }\n\n /**\n * Given a key, finds the appropriate function for looking up its corresponding value, based on\n * the key's prefix.\n */\n _getLookupFunction (key: string) {\n for (const prefix of this.lookupFunctions.keys()) {\n if (key.startsWith(prefix)) {\n return this.lookupFunctions.get(prefix)\n }\n }\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix\n */\n registerLookupFunction (prefix: string, lookup: LookupFunction) {\n if (this.lookupFunctions.has(prefix)) {\n throw errCode(new Error(\"Fetch protocol handler for key prefix '\" + prefix + \"' already registered\"), codes.ERR_KEY_ALREADY_EXISTS)\n }\n\n this.lookupFunctions.set(prefix, lookup)\n }\n\n /**\n * Registers a new lookup callback that can map keys to values, for a given set of keys that\n * share the same prefix.\n */\n unregisterLookupFunction (prefix: string, lookup?: LookupFunction) {\n if (lookup != null) {\n const existingLookup = this.lookupFunctions.get(prefix)\n\n if (existingLookup !== lookup) {\n return\n }\n }\n\n this.lookupFunctions.delete(prefix)\n }\n}\n","\nexport const PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\n","import { logger } from '@libp2p/logger'\nimport errCode from 'err-code'\nimport { codes } from '../errors.js'\nimport { randomBytes } from '@libp2p/crypto'\nimport { pipe } from 'it-pipe'\nimport first from 'it-first'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION } from './constants.js'\nimport type { IncomingStreamData } from '@libp2p/interface-registrar'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { abortableDuplex } from 'abortable-iterator'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport type { Stream } from '@libp2p/interface-connection'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:ping')\n\nexport interface PingServiceInit {\n protocolPrefix: string\n maxInboundStreams: number\n maxOutboundStreams: number\n\n /**\n * How long we should wait for a ping response\n */\n timeout: number\n}\n\nexport class PingService implements Startable {\n public readonly protocol: string\n private readonly components: Components\n private started: boolean\n private readonly init: PingServiceInit\n\n constructor (components: Components, init: PingServiceInit) {\n this.components = components\n this.started = false\n this.protocol = `/${init.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.init = init\n }\n\n async start () {\n await this.components.getRegistrar().handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.init.maxInboundStreams,\n maxOutboundStreams: this.init.maxOutboundStreams\n })\n this.started = true\n }\n\n async stop () {\n await this.components.getRegistrar().unhandle(this.protocol)\n this.started = false\n }\n\n isStarted () {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage (data: IncomingStreamData) {\n const { stream } = data\n\n void pipe(stream, stream)\n .catch(err => {\n log.error(err)\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n *\n * @param {PeerId|Multiaddr} peer\n * @returns {Promise}\n */\n async ping (peer: PeerId, options: AbortOptions = {}): Promise {\n log('dialing %s to %p', this.protocol, peer)\n\n const start = Date.now()\n const data = randomBytes(PING_LENGTH)\n const connection = await this.components.getConnectionManager().openConnection(peer, options)\n let timeoutController\n let signal = options.signal\n let stream: Stream | undefined\n\n // create a timeout if no abort signal passed\n if (signal == null) {\n timeoutController = new TimeoutController(this.init.timeout)\n signal = timeoutController.signal\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, timeoutController.signal)\n } catch {}\n }\n\n try {\n stream = await connection.newStream([this.protocol], {\n signal\n })\n\n // make stream abortable\n const source = abortableDuplex(stream, signal)\n\n const result = await pipe(\n [data],\n source,\n async (source) => await first(source)\n )\n const end = Date.now()\n\n if (result == null || !uint8ArrayEquals(data, result.subarray())) {\n throw errCode(new Error('Received wrong ping ack'), codes.ERR_WRONG_PING_ACK)\n }\n\n return end - start\n } finally {\n if (timeoutController != null) {\n timeoutController.clear()\n }\n\n if (stream != null) {\n stream.close()\n }\n }\n }\n}\n","import { isLoopbackAddr } from 'is-loopback-addr'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Check if a given multiaddr is a loopback address.\n */\nexport function isLoopback (ma: Multiaddr) {\n const { address } = ma.nodeAddress()\n\n return isLoopbackAddr(address)\n}\n","/**\n * Check if a given ip address is a loopback address\n */\nexport function isLoopbackAddr (ip: string) {\n return /^127\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n /^::1$/.test(ip)\n}\n","import { upnpNat, NatAPI } from '@achingbrain/nat-port-mapper'\nimport { logger } from '@libp2p/logger'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { isBrowser } from 'wherearewe'\nimport isPrivateIp from 'private-ip'\nimport * as pkg from './version.js'\nimport errCode from 'err-code'\nimport { codes } from './errors.js'\nimport { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:nat')\nconst DEFAULT_TTL = 7200\n\nfunction highPort (min = 1024, max = 65535) {\n return Math.floor(Math.random() * (max - min + 1) + min)\n}\n\nexport interface PMPOptions {\n /**\n * Whether to enable PMP as well as UPnP\n */\n enabled?: boolean\n}\n\nexport interface NatManagerInit {\n /**\n * Whether to enable the NAT manager\n */\n enabled: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n externalAddress?: string\n\n /**\n * Pass a value to use instead of auto-detection\n */\n localAddress?: string\n\n /**\n * A string value to use for the port mapping description on the gateway\n */\n description?: string\n\n /**\n * How long UPnP port mappings should last for in seconds (minimum 1200)\n */\n ttl?: number\n\n /**\n * Whether to automatically refresh UPnP port mappings when their TTL is reached\n */\n keepAlive: boolean\n\n /**\n * Pass a value to use instead of auto-detection\n */\n gateway?: string\n}\n\nexport class NatManager implements Startable {\n private readonly components: Components\n private readonly enabled: boolean\n private readonly externalAddress?: string\n private readonly localAddress?: string\n private readonly description: string\n private readonly ttl: number\n private readonly keepAlive: boolean\n private readonly gateway?: string\n private started: boolean\n private client?: NatAPI\n\n constructor (components: Components, init: NatManagerInit) {\n this.components = components\n\n this.started = false\n this.enabled = init.enabled\n this.externalAddress = init.externalAddress\n this.localAddress = init.localAddress\n this.description = init.description ?? `${pkg.name}@${pkg.version} ${this.components.getPeerId().toString()}`\n this.ttl = init.ttl ?? DEFAULT_TTL\n this.keepAlive = init.keepAlive ?? true\n this.gateway = init.gateway\n\n if (this.ttl < DEFAULT_TTL) {\n throw errCode(new Error(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`), codes.ERR_INVALID_PARAMETERS)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n start () {}\n\n /**\n * Attempt to use uPnP to configure port mapping using the current gateway.\n *\n * Run after start to ensure the transport manager has all addresses configured.\n */\n afterStart () {\n if (isBrowser || !this.enabled || this.started) {\n return\n }\n\n this.started = true\n\n // done async to not slow down startup\n void this._start().catch((err) => {\n // hole punching errors are non-fatal\n log.error(err)\n })\n }\n\n async _start () {\n const addrs = this.components.getTransportManager().getAddrs()\n\n for (const addr of addrs) {\n // try to open uPnP ports for each thin waist address\n const { family, host, port, transport } = addr.toOptions()\n\n if (!addr.isThinWaistAddress() || transport !== 'tcp') {\n // only bare tcp addresses\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (isLoopback(addr)) {\n // eslint-disable-next-line no-continue\n continue\n }\n\n if (family !== 4) {\n // ignore ipv6\n // eslint-disable-next-line no-continue\n continue\n }\n\n const client = await this._getClient()\n const publicIp = this.externalAddress ?? await client.externalIp()\n\n if (isPrivateIp(publicIp)) {\n throw new Error(`${publicIp} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`)\n }\n\n const publicPort = highPort()\n\n log(`opening uPnP connection from ${publicIp}:${publicPort} to ${host}:${port}`)\n\n await client.map({\n publicPort,\n localPort: port,\n localAddress: this.localAddress,\n protocol: transport.toUpperCase() === 'TCP' ? 'TCP' : 'UDP'\n })\n\n this.components.getAddressManager().addObservedAddr(Multiaddr.fromNodeAddress({\n family: 4,\n address: publicIp,\n port: publicPort\n }, transport))\n }\n }\n\n async _getClient () {\n if (this.client != null) {\n return this.client\n }\n\n this.client = await upnpNat({\n description: this.description,\n ttl: this.ttl,\n keepAlive: this.keepAlive,\n gateway: this.gateway\n })\n\n return this.client\n }\n\n /**\n * Stops the NAT manager\n */\n async stop () {\n if (isBrowser || this.client == null) {\n return\n }\n\n try {\n await this.client.close()\n this.client = undefined\n } catch (err: any) {\n log.error(err)\n }\n }\n}\n","\nexport async function upnpNat () {\n throw new Error('Not supported in browsers')\n}\n\nexport async function pmpNat () {\n throw new Error('Not supported in browsers')\n}\n","import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport type { Components } from '@libp2p/components'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport { logger } from '@libp2p/logger'\nimport { protocols } from '@multiformats/multiaddr'\n\nconst log = logger('libp2p:peer-record-updater')\n\nexport class PeerRecordUpdater implements Startable {\n private readonly components: Components\n private started: boolean\n\n constructor (components: Components) {\n this.components = components\n this.started = false\n this.update = this.update.bind(this)\n }\n\n isStarted () {\n return this.started\n }\n\n async start () {\n this.started = true\n this.components.getTransportManager().addEventListener('listener:listening', this.update)\n this.components.getTransportManager().addEventListener('listener:close', this.update)\n this.components.getAddressManager().addEventListener('change:addresses', this.update)\n }\n\n async stop () {\n this.started = false\n this.components.getTransportManager().removeEventListener('listener:listening', this.update)\n this.components.getTransportManager().removeEventListener('listener:close', this.update)\n this.components.getAddressManager().removeEventListener('change:addresses', this.update)\n }\n\n /**\n * Create (or update if existing) self peer record and store it in the AddressBook.\n */\n update () {\n Promise.resolve()\n .then(async () => {\n const peerRecord = new PeerRecord({\n peerId: this.components.getPeerId(),\n multiaddrs: this.components.getAddressManager().getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))\n })\n\n const envelope = await RecordEnvelope.seal(peerRecord, this.components.getPeerId())\n await this.components.getPeerStore().addressBook.consumePeerRecord(envelope)\n })\n .catch(err => {\n log.error('Could not update self peer record: %o', err)\n })\n }\n}\n","import errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTPeerRouting implements PeerRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async findPeer (peerId: PeerId, options: AbortOptions = {}) {\n for await (const event of this.dht.findPeer(peerId, options)) {\n if (event.name === 'FINAL_PEER') {\n return event.peer\n }\n }\n\n throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)\n }\n\n async * getClosestPeers (key: Uint8Array, options: AbortOptions = {}) {\n for await (const event of this.dht.getClosestPeers(key, options)) {\n if (event.name === 'PEER_RESPONSE') {\n yield * event.closer\n }\n }\n }\n}\n","\nexport const codes = {\n ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS',\n ERR_NOT_FOUND: 'ERR_NOT_FOUND'\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { codes } from './errors.js'\nimport { PeerRecord, RecordEnvelope } from '@libp2p/peer-record'\nimport { pipe } from 'it-pipe'\nimport all from 'it-all'\nimport filter from 'it-filter'\nimport map from 'it-map'\nimport each from 'it-foreach'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { AddressFilter, Peer, PeerMultiaddrsChangeData, PeerStore } from '@libp2p/interface-peer-store'\nimport type { Store } from './store.js'\nimport type { Envelope } from '@libp2p/interface-record'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\n\nconst log = logger('libp2p:peer-store:address-book')\nconst EVENT_NAME = 'change:multiaddrs'\n\nasync function allowAll () {\n return true\n}\n\nexport class PeerStoreAddressBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n private readonly addressFilter: AddressFilter\n\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store, addressFilter?: AddressFilter) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n this.addressFilter = addressFilter ?? allowAll\n }\n\n /**\n * ConsumePeerRecord adds addresses from a signed peer record contained in a record envelope.\n * This will return a boolean that indicates if the record was successfully processed and added\n * into the AddressBook.\n */\n async consumePeerRecord (envelope: Envelope) {\n log.trace('consumePeerRecord await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('consumePeerRecord got write lock')\n\n let peerId\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n let peerRecord\n try {\n peerRecord = PeerRecord.createFromProtobuf(envelope.payload)\n } catch (err: any) {\n log.error('invalid peer record received')\n return false\n }\n\n peerId = peerRecord.peerId\n const multiaddrs = peerRecord.multiaddrs\n\n // Verify peerId\n if (!peerId.equals(envelope.peerId)) {\n log('signing key does not match PeerId in the PeerRecord')\n return false\n }\n\n // ensure the record has multiaddrs\n if (multiaddrs == null || multiaddrs.length === 0) {\n return false\n }\n\n if (await this.store.has(peerId)) {\n peer = await this.store.load(peerId)\n\n if (peer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope)\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)\n\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber)\n return false\n }\n }\n }\n\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter, true)\n\n // Replace unsigned addresses by the new ones from the record\n // TODO: Once we have ttls for the addresses, we should merge these in\n updatedPeer = await this.store.patchOrCreate(peerId, {\n addresses,\n peerRecordEnvelope: envelope.marshal().subarray()\n })\n\n log('stored provided peer record for %p', peerRecord.peerId)\n } finally {\n log.trace('consumePeerRecord release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(({ multiaddr }) => multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n return true\n }\n\n async getRawEnvelope (peerId: PeerId) {\n log.trace('getRawEnvelope await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getRawEnvelope got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.peerRecordEnvelope\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getRawEnvelope release read lock')\n release()\n }\n }\n\n /**\n * Get an Envelope containing a PeerRecord for the given peer.\n * Returns undefined if no record exists.\n */\n async getPeerRecord (peerId: PeerId) {\n const raw = await this.getRawEnvelope(peerId)\n\n if (raw == null) {\n return undefined\n }\n\n return await RecordEnvelope.createFromProtobuf(raw)\n }\n\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.addresses\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let hasPeer = false\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length && addresses.length === peer.addresses.length) {\n // not changing anything, no need to update\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, { addresses })\n\n log('set multiaddrs for %p', peerId)\n } finally {\n log.trace('set multiaddrs for %p', peerId)\n log('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (!hasPeer) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async add (peerId: PeerId, multiaddrs: Multiaddr[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(multiaddrs)) {\n log.error('multiaddrs must be an array of Multiaddrs')\n throw errcode(new Error('multiaddrs must be an array of Multiaddrs'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let hasPeer\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n const addresses = await filterMultiaddrs(peerId, multiaddrs, this.addressFilter)\n\n // No valid addresses found\n if (addresses.length === 0) {\n return\n }\n\n try {\n peer = await this.store.load(peerId)\n hasPeer = true\n\n if (new Set([\n ...addresses.map(({ multiaddr }) => multiaddr.toString()),\n ...peer.addresses.map(({ multiaddr }) => multiaddr.toString())\n ]).size === peer.addresses.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, { addresses })\n\n log('added multiaddrs for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n\n // Notify the existence of a new peer\n if (hasPeer === true) {\n this.dispatchEvent(new CustomEvent('peer', {\n detail: {\n id: peerId,\n multiaddrs: updatedPeer.addresses.map(addr => addr.multiaddr),\n protocols: updatedPeer.protocols\n }\n }))\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n addresses: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n multiaddrs: [],\n oldMultiaddrs: peer == null ? [] : peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }))\n }\n }\n}\n\nasync function filterMultiaddrs (peerId: PeerId, multiaddrs: Multiaddr[], addressFilter: AddressFilter, isCertified: boolean = false) {\n return await pipe(\n multiaddrs,\n (source) => each(source, (multiaddr) => {\n if (!Multiaddr.isMultiaddr(multiaddr)) {\n log.error('multiaddr must be an instance of Multiaddr')\n throw errcode(new Error('multiaddr must be an instance of Multiaddr'), codes.ERR_INVALID_PARAMETERS)\n }\n }),\n (source) => filter(source, async (multiaddr) => await addressFilter(peerId, multiaddr)),\n (source) => map(source, (multiaddr) => {\n return {\n multiaddr: new Multiaddr(multiaddr.toString()),\n isCertified\n }\n }),\n async (source) => await all(source)\n )\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, KeyBook, PeerPublicKeyChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:key-book')\n\nconst EVENT_NAME = 'change:pubkey'\n\nexport class PeerStoreKeyBook implements KeyBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The KeyBook is responsible for keeping the known public keys of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Set the Peer public key\n */\n async set (peerId: PeerId, publicKey: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(publicKey instanceof Uint8Array)) {\n log.error('publicKey must be an instance of Uint8Array to store data')\n throw errcode(new Error('publicKey must be an instance of PublicKey'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let updatedKey = false\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if ((peer.pubKey != null) && uint8arrayEquals(peer.pubKey, publicKey)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: publicKey\n })\n updatedKey = true\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n if (updatedKey) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: publicKey,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n }\n\n /**\n * Get Public key of the given PeerId, if stored\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await write lock')\n const release = await this.store.lock.readLock()\n log.trace('get got write lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.pubKey\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log('get release write lock')\n release()\n }\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n pubKey: undefined\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n publicKey: undefined,\n oldPublicKey: peer == null ? undefined : peer.pubKey\n }\n }))\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { PeerStore, MetadataBook, PeerMetadataChangeData, Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:metadata-book')\n\nconst EVENT_NAME = 'change:metadata'\n\nexport class PeerStoreMetadataBook implements MetadataBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The MetadataBook is responsible for keeping metadata\n * about known peers\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n /**\n * Get the known data of a provided peer\n */\n async get (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return new Map()\n }\n\n /**\n * Get specific metadata value, if it exists\n */\n async getValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('getValue await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getValue got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.metadata.get(key)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('getValue release write lock')\n release()\n }\n }\n\n async set (peerId: PeerId, metadata: Map) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!(metadata instanceof Map)) {\n log.error('valid metadata must be provided to store data')\n throw errcode(new Error('valid metadata must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.mergeOrCreate(peerId, {\n metadata\n })\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n /**\n * Set metadata key and value of a provided peer\n */\n async setValue (peerId: PeerId, key: string, value: Uint8Array) {\n peerId = peerIdFromPeerId(peerId)\n\n if (typeof key !== 'string' || !(value instanceof Uint8Array)) {\n log.error('valid key and value must be provided to store data')\n throw errcode(new Error('valid key and value must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('setValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('setValue got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const existingValue = peer.metadata.get(key)\n\n if (existingValue != null && uint8ArrayEquals(value, existingValue)) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n metadata: new Map([[key, value]])\n })\n } finally {\n log.trace('setValue release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: updatedPeer.metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n if (peer != null) {\n await this.store.patch(peerId, {\n metadata: new Map()\n })\n }\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata: new Map(),\n oldMetadata: peer.metadata\n }\n }))\n }\n }\n\n async deleteValue (peerId: PeerId, key: string) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('deleteValue await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('deleteValue got write lock')\n\n let metadata\n let peer: Peer | undefined\n\n try {\n peer = await this.store.load(peerId)\n metadata = peer.metadata\n\n metadata.delete(key)\n\n await this.store.patch(peerId, {\n metadata\n })\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('deleteValue release write lock')\n release()\n }\n\n if (metadata != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n metadata,\n oldMetadata: peer == null ? new Map() : peer.metadata\n }\n }))\n }\n }\n}\n","import { logger } from '@libp2p/logger'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { peerIdFromPeerId } from '@libp2p/peer-id'\nimport { CustomEvent } from '@libp2p/interfaces/events'\nimport type { Store } from './store.js'\nimport type { Peer, PeerProtocolsChangeData, PeerStore, ProtoBook } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\n\nconst log = logger('libp2p:peer-store:proto-book')\n\nconst EVENT_NAME = 'change:protocols'\n\nexport class PeerStoreProtoBook implements ProtoBook {\n private readonly dispatchEvent: PeerStore['dispatchEvent']\n private readonly store: Store\n\n /**\n * The ProtoBook is responsible for keeping the known supported\n * protocols of a peer\n */\n constructor (dispatchEvent: PeerStore['dispatchEvent'], store: Store) {\n this.dispatchEvent = dispatchEvent\n this.store = store\n }\n\n async get (peerId: PeerId) {\n log.trace('get wait for read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n const peer = await this.store.load(peerId)\n\n return peer.protocols\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n } finally {\n log.trace('get release read lock')\n release()\n }\n\n return []\n }\n\n async set (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('set await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('set got write lock')\n\n let peer\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n\n log('stored provided protocols for %p', peerId)\n } finally {\n log.trace('set release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async add (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('add await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('add got write lock')\n\n let peer: Peer | undefined\n let updatedPeer\n\n try {\n try {\n peer = await this.store.load(peerId)\n\n if (new Set([\n ...peer.protocols,\n ...protocols\n ]).size === peer.protocols.length) {\n return\n }\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.mergeOrCreate(peerId, {\n protocols\n })\n\n log('added provided protocols for %p', peerId)\n } finally {\n log.trace('add release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async remove (peerId: PeerId, protocols: string[]) {\n peerId = peerIdFromPeerId(peerId)\n\n if (!Array.isArray(protocols)) {\n log.error('protocols must be provided to store data')\n throw errcode(new Error('protocols must be provided'), codes.ERR_INVALID_PARAMETERS)\n }\n\n log.trace('remove await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('remove got write lock')\n\n let peer: Peer | undefined\n let updatedPeer: Peer\n\n try {\n try {\n peer = await this.store.load(peerId)\n const protocolSet = new Set(peer.protocols)\n\n for (const protocol of protocols) {\n protocolSet.delete(protocol)\n }\n\n if (peer.protocols.length === protocolSet.size) {\n return\n }\n\n protocols = Array.from(protocolSet)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n updatedPeer = await this.store.patchOrCreate(peerId, {\n protocols\n })\n } finally {\n log.trace('remove release write lock')\n release()\n }\n\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: updatedPeer.protocols,\n oldProtocols: peer == null ? [] : peer.protocols\n }\n }))\n }\n\n async delete (peerId: PeerId) {\n peerId = peerIdFromPeerId(peerId)\n\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n let peer: Peer | undefined\n\n try {\n try {\n peer = await this.store.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n }\n\n await this.store.patchOrCreate(peerId, {\n protocols: []\n })\n } finally {\n log.trace('delete release write lock')\n release()\n }\n\n if (peer != null) {\n this.dispatchEvent(new CustomEvent(EVENT_NAME, {\n detail: {\n peerId,\n protocols: [],\n oldProtocols: peer.protocols\n }\n }))\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Peer {\n addresses: Address[]\n protocols: string[]\n metadata: Metadata[]\n pubKey?: Uint8Array\n peerRecordEnvelope?: Uint8Array\n}\n\nexport namespace Peer {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n writer.uint32(10)\n Address.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"addresses\" was not found in object')\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n writer.uint32(18)\n writer.string(value)\n }\n } else {\n throw new Error('Protocol error: required field \"protocols\" was not found in object')\n }\n\n if (obj.metadata != null) {\n for (const value of obj.metadata) {\n writer.uint32(26)\n Metadata.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"metadata\" was not found in object')\n }\n\n if (obj.pubKey != null) {\n writer.uint32(34)\n writer.bytes(obj.pubKey)\n }\n\n if (obj.peerRecordEnvelope != null) {\n writer.uint32(42)\n writer.bytes(obj.peerRecordEnvelope)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n addresses: [],\n protocols: [],\n metadata: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.addresses.push(Address.codec().decode(reader, reader.uint32()))\n break\n case 2:\n obj.protocols.push(reader.string())\n break\n case 3:\n obj.metadata.push(Metadata.codec().decode(reader, reader.uint32()))\n break\n case 4:\n obj.pubKey = reader.bytes()\n break\n case 5:\n obj.peerRecordEnvelope = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Peer): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {\n return decodeMessage(buf, Peer.codec())\n }\n}\n\nexport interface Address {\n multiaddr: Uint8Array\n isCertified?: boolean\n}\n\nexport namespace Address {\n let _codec: Codec
    \n\n export const codec = (): Codec
    => {\n if (_codec == null) {\n _codec = message
    ((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.multiaddr != null) {\n writer.uint32(10)\n writer.bytes(obj.multiaddr)\n } else {\n throw new Error('Protocol error: required field \"multiaddr\" was not found in object')\n }\n\n if (obj.isCertified != null) {\n writer.uint32(16)\n writer.bool(obj.isCertified)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n multiaddr: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes()\n break\n case 2:\n obj.isCertified = reader.bool()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.multiaddr == null) {\n throw new Error('Protocol error: value for required field \"multiaddr\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Address): Uint8Array => {\n return encodeMessage(obj, Address.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Address => {\n return decodeMessage(buf, Address.codec())\n }\n}\n\nexport interface Metadata {\n key: string\n value: Uint8Array\n}\n\nexport namespace Metadata {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.key != null) {\n writer.uint32(10)\n writer.string(obj.key)\n } else {\n throw new Error('Protocol error: required field \"key\" was not found in object')\n }\n\n if (obj.value != null) {\n writer.uint32(18)\n writer.bytes(obj.value)\n } else {\n throw new Error('Protocol error: required field \"value\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n key: '',\n value: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string()\n break\n case 2:\n obj.value = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.key == null) {\n throw new Error('Protocol error: value for required field \"key\" was not found in protobuf')\n }\n\n if (obj.value == null) {\n throw new Error('Protocol error: value for required field \"value\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Metadata): Uint8Array => {\n return encodeMessage(obj, Metadata.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Metadata => {\n return decodeMessage(buf, Metadata.codec())\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PriorityQueue_queue;\nimport lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n constructor() {\n _PriorityQueue_queue.set(this, []);\n }\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n run,\n };\n if (this.size && __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\")[this.size - 1].priority >= options.priority) {\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").push(element);\n return;\n }\n const index = lowerBound(__classPrivateFieldGet(this, _PriorityQueue_queue, \"f\"), element, (a, b) => b.priority - a.priority);\n __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").splice(index, 0, element);\n }\n dequeue() {\n const item = __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return __classPrivateFieldGet(this, _PriorityQueue_queue, \"f\").length;\n }\n}\n_PriorityQueue_queue = new WeakMap();\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pendingCount, _PQueue_concurrency, _PQueue_isPaused, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_emitEvents, _PQueue_onResumeInterval, _PQueue_isIntervalPaused_get, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, _PQueue_onEvent;\nimport EventEmitter from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\nconst timeoutError = new TimeoutError();\n/**\nThe error thrown by `queue.add()` when a job is aborted before it is run. See `signal`.\n*/\nexport class AbortError extends Error {\n}\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n _PQueue_instances.add(this);\n _PQueue_carryoverConcurrencyCount.set(this, void 0);\n _PQueue_isIntervalIgnored.set(this, void 0);\n _PQueue_intervalCount.set(this, 0);\n _PQueue_intervalCap.set(this, void 0);\n _PQueue_interval.set(this, void 0);\n _PQueue_intervalEnd.set(this, 0);\n _PQueue_intervalId.set(this, void 0);\n _PQueue_timeoutId.set(this, void 0);\n _PQueue_queue.set(this, void 0);\n _PQueue_queueClass.set(this, void 0);\n _PQueue_pendingCount.set(this, 0);\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n _PQueue_concurrency.set(this, void 0);\n _PQueue_isPaused.set(this, void 0);\n _PQueue_throwOnTimeout.set(this, void 0);\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n \n Applies to each future operation.\n */\n Object.defineProperty(this, \"timeout\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\\` (${typeof options.interval})`);\n }\n __classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, \"f\");\n __classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, \"f\");\n __classPrivateFieldSet(this, _PQueue_interval, options.interval, \"f\");\n __classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), \"f\");\n __classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, \"f\");\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n __classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, \"f\");\n __classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, \"f\");\n }\n get concurrency() {\n return __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n __classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n }\n /**\n Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options = {}) {\n return new Promise((resolve, reject) => {\n const run = async () => {\n var _a;\n var _b, _c;\n __classPrivateFieldSet(this, _PQueue_pendingCount, (_b = __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\"), _b++, _b), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\"), _c++, _c), \"f\");\n try {\n if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n // TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)\n reject(new AbortError('The task was aborted.'));\n return;\n }\n const operation = (this.timeout === undefined && options.timeout === undefined) ? fn({ signal: options.signal }) : pTimeout(Promise.resolve(fn({ signal: options.signal })), (options.timeout === undefined ? this.timeout : options.timeout), () => {\n if (options.throwOnTimeout === undefined ? __classPrivateFieldGet(this, _PQueue_throwOnTimeout, \"f\") : options.throwOnTimeout) {\n reject(timeoutError);\n }\n return undefined;\n });\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n reject(error);\n this.emit('error', error);\n }\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_next).call(this);\n };\n __classPrivateFieldGet(this, _PQueue_queue, \"f\").enqueue(run, options);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('add');\n });\n }\n /**\n Same as `.add()`, but accepts an array of sync or async functions.\n\n @returns A promise that resolves when all functions are resolved.\n */\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n return this;\n }\n __classPrivateFieldSet(this, _PQueue_isPaused, false, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n __classPrivateFieldSet(this, _PQueue_isPaused, true, \"f\");\n }\n /**\n Clear the queue.\n */\n clear() {\n __classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet(this, _PQueue_queueClass, \"f\"))(), \"f\");\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'next', () => __classPrivateFieldGet(this, _PQueue_queue, \"f\").size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (__classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n return;\n }\n await __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onEvent).call(this, 'idle');\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return __classPrivateFieldGet(this, _PQueue_queue, \"f\").filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\");\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return __classPrivateFieldGet(this, _PQueue_isPaused, \"f\");\n }\n}\n_PQueue_carryoverConcurrencyCount = new WeakMap(), _PQueue_isIntervalIgnored = new WeakMap(), _PQueue_intervalCount = new WeakMap(), _PQueue_intervalCap = new WeakMap(), _PQueue_interval = new WeakMap(), _PQueue_intervalEnd = new WeakMap(), _PQueue_intervalId = new WeakMap(), _PQueue_timeoutId = new WeakMap(), _PQueue_queue = new WeakMap(), _PQueue_queueClass = new WeakMap(), _PQueue_pendingCount = new WeakMap(), _PQueue_concurrency = new WeakMap(), _PQueue_isPaused = new WeakMap(), _PQueue_throwOnTimeout = new WeakMap(), _PQueue_instances = new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") < __classPrivateFieldGet(this, _PQueue_intervalCap, \"f\");\n}, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get() {\n return __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") < __classPrivateFieldGet(this, _PQueue_concurrency, \"f\");\n}, _PQueue_next = function _PQueue_next() {\n var _a;\n __classPrivateFieldSet(this, _PQueue_pendingCount, (_a = __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\"), _a--, _a), \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this);\n this.emit('next');\n}, _PQueue_emitEvents = function _PQueue_emitEvents() {\n this.emit('empty');\n if (__classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0) {\n this.emit('idle');\n }\n}, _PQueue_onResumeInterval = function _PQueue_onResumeInterval() {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n __classPrivateFieldSet(this, _PQueue_timeoutId, undefined, \"f\");\n}, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get() {\n const now = Date.now();\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\") === undefined) {\n const delay = __classPrivateFieldGet(this, _PQueue_intervalEnd, \"f\") - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n __classPrivateFieldSet(this, _PQueue_intervalCount, (__classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\")) ? __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") : 0, \"f\");\n }\n else {\n // Act as the interval is pending\n if (__classPrivateFieldGet(this, _PQueue_timeoutId, \"f\") === undefined) {\n __classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onResumeInterval).call(this);\n }, delay), \"f\");\n }\n return true;\n }\n }\n return false;\n}, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother() {\n if (__classPrivateFieldGet(this, _PQueue_queue, \"f\").size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (__classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_emitEvents).call(this);\n return false;\n }\n if (!__classPrivateFieldGet(this, _PQueue_isPaused, \"f\")) {\n const canInitializeInterval = !__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_isIntervalPaused_get);\n if (__classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet(this, _PQueue_instances, \"a\", _PQueue_doesConcurrentAllowAnother_get)) {\n const job = __classPrivateFieldGet(this, _PQueue_queue, \"f\").dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_initializeIntervalIfNeeded).call(this);\n }\n return true;\n }\n }\n return false;\n}, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded() {\n if (__classPrivateFieldGet(this, _PQueue_isIntervalIgnored, \"f\") || __classPrivateFieldGet(this, _PQueue_intervalId, \"f\") !== undefined) {\n return;\n }\n __classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_onInterval).call(this);\n }, __classPrivateFieldGet(this, _PQueue_interval, \"f\")), \"f\");\n __classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet(this, _PQueue_interval, \"f\"), \"f\");\n}, _PQueue_onInterval = function _PQueue_onInterval() {\n if (__classPrivateFieldGet(this, _PQueue_intervalCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") === 0 && __classPrivateFieldGet(this, _PQueue_intervalId, \"f\")) {\n clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, \"f\"));\n __classPrivateFieldSet(this, _PQueue_intervalId, undefined, \"f\");\n }\n __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, \"f\") ? __classPrivateFieldGet(this, _PQueue_pendingCount, \"f\") : 0, \"f\");\n __classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_processQueue).call(this);\n}, _PQueue_processQueue = function _PQueue_processQueue() {\n // eslint-disable-next-line no-empty\n while (__classPrivateFieldGet(this, _PQueue_instances, \"m\", _PQueue_tryToStartAnother).call(this)) { }\n}, _PQueue_onEvent = async function _PQueue_onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n};\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst cancelablePromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tresolve(promise);\n\t\t\treturn;\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst errorMessage = typeof message === 'string' ? message : `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\tconst timeoutError = message instanceof Error ? message : new TimeoutError(errorMessage);\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\treject(timeoutError);\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t} finally {\n\t\t\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\t\t}\n\t\t})();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","\nexport const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read'\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read'\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read'\n\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write'\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write'\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write'\n","export interface WebworkerEventListener {\n (worker: Worker, event: MessageEvent): void\n}\n\nconst events: Record = {}\n\nconst observable = (worker: Worker & { port?: any }) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event)\n })\n\n if (worker.port != null) {\n worker.port.addEventListener('message', (event: any) => {\n observable.dispatchEvent('message', worker, event)\n })\n }\n}\n\nobservable.addEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n events[type] = []\n }\n\n events[type].push(fn)\n}\n\nobservable.removeEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n return\n }\n\n events[type] = events[type]\n .filter(listener => listener === fn)\n}\n\nobservable.dispatchEvent = function (type: string, worker: Worker, event: MessageEvent) {\n if (events[type] == null) {\n return\n }\n\n events[type].forEach(fn => fn(worker, event))\n}\n\nexport default observable\n","import { nanoid } from 'nanoid'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport observer from 'observable-webworkers'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n return await new Promise((resolve) => {\n const releaseEventListener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return await new Promise((resolve) => {\n const listener = (event: MessageEvent) => {\n if (event == null || event.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK))\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK))\n\n return emitter\n }\n\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK)\n }\n}\n","export { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nexport let nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\n","import PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock: () => Promise\n writeLock: () => Promise\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock: (name: string, options: MorticeOptions) => Mortice['readLock']\n writeLock: (name: string, options: MorticeOptions) => Mortice['writeLock']\n}\n\nconst mutexes: Record = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required): Promise {\n let res: (release: Release) => void\n\n const p = new Promise((resolve) => {\n res = resolve\n })\n\n void queue.add(async () => await pTimeout((async () => {\n return await new Promise((resolve) => {\n res(() => {\n resolve()\n })\n })\n })(), {\n milliseconds: options.timeout\n }))\n\n return await p\n}\n\nconst createMutex = (name: string, options: Required): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\n return {\n async readLock () {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return await createReleaseable(readQueue, options)\n }\n\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start()\n\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n return await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return await readPromise\n },\n async writeLock () {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null\n\n return await createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler: () => Promise\n}\n\nexport default function createMortice (options?: MorticeOptions) {\n const opts: Required = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => await event.data.handler().finally(() => release()))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n","import { logger } from '@libp2p/logger'\nimport { peerIdFromBytes } from '@libp2p/peer-id'\nimport errcode from 'err-code'\nimport { codes } from './errors.js'\nimport { Key } from 'interface-datastore/key'\nimport { base32 } from 'multiformats/bases/base32'\nimport { Multiaddr } from '@multiformats/multiaddr'\nimport { Metadata, Peer as PeerPB } from './pb/peer.js'\nimport mortice from 'mortice'\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals'\nimport type { Peer } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { Components } from '@libp2p/components'\n\nconst log = logger('libp2p:peer-store:store')\n\nconst NAMESPACE_COMMON = '/peers/'\n\nexport interface Store {\n has: (peerId: PeerId) => Promise\n save: (peer: Peer) => Promise\n load: (peerId: PeerId) => Promise\n delete: (peerId: PeerId) => Promise\n merge: (peerId: PeerId, data: Partial) => Promise\n mergeOrCreate: (peerId: PeerId, data: Partial) => Promise\n patch: (peerId: PeerId, data: Partial) => Promise\n patchOrCreate: (peerId: PeerId, data: Partial) => Promise\n all: () => AsyncIterable\n\n lock: {\n readLock: () => Promise<() => void>\n writeLock: () => Promise<() => void>\n }\n}\n\nexport class PersistentStore {\n private components: Components = new Components()\n public lock: any\n\n constructor () {\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n })\n }\n\n init (components: Components) {\n this.components = components\n }\n\n _peerIdToDatastoreKey (peerId: PeerId) {\n if (peerId.type == null) {\n log.error('peerId must be an instance of peer-id to store data')\n throw errcode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)\n }\n\n const b32key = peerId.toCID().toString()\n return new Key(`${NAMESPACE_COMMON}${b32key}`)\n }\n\n async has (peerId: PeerId) {\n return await this.components.getDatastore().has(this._peerIdToDatastoreKey(peerId))\n }\n\n async delete (peerId: PeerId) {\n await this.components.getDatastore().delete(this._peerIdToDatastoreKey(peerId))\n }\n\n async load (peerId: PeerId): Promise {\n const buf = await this.components.getDatastore().get(this._peerIdToDatastoreKey(peerId))\n const peer = PeerPB.decode(buf)\n const metadata = new Map()\n\n for (const meta of peer.metadata) {\n metadata.set(meta.key, meta.value)\n }\n\n return {\n ...peer,\n id: peerId,\n addresses: peer.addresses.map(({ multiaddr, isCertified }) => {\n return {\n multiaddr: new Multiaddr(multiaddr),\n isCertified: isCertified ?? false\n }\n }),\n metadata,\n pubKey: peer.pubKey ?? undefined,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined\n }\n }\n\n async save (peer: Peer) {\n if (peer.pubKey != null && peer.id.publicKey != null && !uint8arrayEquals(peer.pubKey, peer.id.publicKey)) {\n log.error('peer publicKey bytes do not match peer id publicKey bytes')\n throw errcode(new Error('publicKey bytes do not match peer id publicKey bytes'), codes.ERR_INVALID_PARAMETERS)\n }\n\n // dedupe addresses\n const addressSet = new Set()\n const addresses = peer.addresses\n .filter(address => {\n if (addressSet.has(address.multiaddr.toString())) {\n return false\n }\n\n addressSet.add(address.multiaddr.toString())\n return true\n })\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString())\n })\n .map(({ multiaddr, isCertified }) => ({\n multiaddr: multiaddr.bytes,\n isCertified\n }))\n\n const metadata: Metadata[] = []\n\n ;[...peer.metadata.keys()].sort().forEach(key => {\n const value = peer.metadata.get(key)\n\n if (value != null) {\n metadata.push({ key, value })\n }\n })\n\n const buf = PeerPB.encode({\n addresses,\n protocols: peer.protocols.sort(),\n pubKey: peer.pubKey,\n metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope\n })\n\n await this.components.getDatastore().put(this._peerIdToDatastoreKey(peer.id), buf.subarray())\n\n return await this.load(peer.id)\n }\n\n async patch (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._patch(peerId, data, peer)\n }\n\n async patchOrCreate (peerId: PeerId, data: Partial) {\n let peer: Peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._patch(peerId, data, peer)\n }\n\n async _patch (peerId: PeerId, data: Partial, peer: Peer) {\n return await this.save({\n ...peer,\n ...data,\n id: peerId\n })\n }\n\n async merge (peerId: PeerId, data: Partial) {\n const peer = await this.load(peerId)\n\n return await this._merge(peerId, data, peer)\n }\n\n async mergeOrCreate (peerId: PeerId, data: Partial) {\n /** @type {Peer} */\n let peer\n\n try {\n peer = await this.load(peerId)\n } catch (err: any) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err\n }\n\n peer = { id: peerId, addresses: [], protocols: [], metadata: new Map() }\n }\n\n return await this._merge(peerId, data, peer)\n }\n\n async _merge (peerId: PeerId, data: Partial, peer: Peer) {\n // if the peer has certified addresses, use those in\n // favour of the supplied versions\n const addresses = new Map()\n\n peer.addresses.forEach((addr) => {\n addresses.set(addr.multiaddr.toString(), addr.isCertified)\n })\n\n ;(data.addresses ?? []).forEach(addr => {\n const addrString = addr.multiaddr.toString()\n const isAlreadyCertified = Boolean(addresses.get(addrString))\n\n const isCertified = isAlreadyCertified || addr.isCertified\n\n addresses.set(addrString, isCertified)\n })\n\n return await this.save({\n id: peerId,\n addresses: Array.from(addresses.entries()).map(([addrStr, isCertified]) => {\n return {\n multiaddr: new Multiaddr(addrStr),\n isCertified\n }\n }),\n protocols: Array.from(new Set([\n ...(peer.protocols ?? []),\n ...(data.protocols ?? [])\n ])),\n metadata: new Map([\n ...(peer.metadata?.entries() ?? []),\n ...(data.metadata?.entries() ?? [])\n ]),\n pubKey: data.pubKey ?? (peer != null ? peer.pubKey : undefined),\n peerRecordEnvelope: data.peerRecordEnvelope ?? (peer != null ? peer.peerRecordEnvelope : undefined)\n })\n }\n\n async * all () {\n for await (const key of this.components.getDatastore().queryKeys({\n prefix: NAMESPACE_COMMON\n })) {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2]\n const buf = base32.decode(base32Str)\n\n yield this.load(peerIdFromBytes(buf))\n }\n }\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface Tags {\n tags: Tag[]\n}\n\nexport namespace Tags {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.tags != null) {\n for (const value of obj.tags) {\n writer.uint32(10)\n Tag.codec().encode(value, writer)\n }\n } else {\n throw new Error('Protocol error: required field \"tags\" was not found in object')\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n tags: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.tags.push(Tag.codec().decode(reader, reader.uint32()))\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tags): Uint8Array => {\n return encodeMessage(obj, Tags.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tags => {\n return decodeMessage(buf, Tags.codec())\n }\n}\n\nexport interface Tag {\n name: string\n value?: number\n expiry?: bigint\n}\n\nexport namespace Tag {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.name != null) {\n writer.uint32(10)\n writer.string(obj.name)\n } else {\n throw new Error('Protocol error: required field \"name\" was not found in object')\n }\n\n if (obj.value != null) {\n writer.uint32(16)\n writer.uint32(obj.value)\n }\n\n if (obj.expiry != null) {\n writer.uint32(24)\n writer.uint64(obj.expiry)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n name: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.name = reader.string()\n break\n case 2:\n obj.value = reader.uint32()\n break\n case 3:\n obj.expiry = reader.uint64()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.name == null) {\n throw new Error('Protocol error: value for required field \"name\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Tag): Uint8Array => {\n return encodeMessage(obj, Tag.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): Tag => {\n return decodeMessage(buf, Tag.codec())\n }\n}\n","import { logger } from '@libp2p/logger'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { PeerStoreAddressBook } from './address-book.js'\nimport { PeerStoreKeyBook } from './key-book.js'\nimport { PeerStoreMetadataBook } from './metadata-book.js'\nimport { PeerStoreProtoBook } from './proto-book.js'\nimport { PersistentStore, Store } from './store.js'\nimport type { PeerStore, AddressBook, KeyBook, MetadataBook, ProtoBook, PeerStoreEvents, PeerStoreInit, Peer, TagOptions } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport { Components, Initializable } from '@libp2p/components'\nimport errCode from 'err-code'\nimport { Tag, Tags } from './pb/tags.js'\n\nconst log = logger('libp2p:peer-store')\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nexport class PersistentPeerStore extends EventEmitter implements PeerStore, Initializable {\n public addressBook: AddressBook\n public keyBook: KeyBook\n public metadataBook: MetadataBook\n public protoBook: ProtoBook\n\n private components: Components = new Components()\n private readonly store: Store\n\n constructor (init: PeerStoreInit = {}) {\n super()\n\n this.store = new PersistentStore()\n this.addressBook = new PeerStoreAddressBook(this.dispatchEvent.bind(this), this.store, init.addressFilter)\n this.keyBook = new PeerStoreKeyBook(this.dispatchEvent.bind(this), this.store)\n this.metadataBook = new PeerStoreMetadataBook(this.dispatchEvent.bind(this), this.store)\n this.protoBook = new PeerStoreProtoBook(this.dispatchEvent.bind(this), this.store)\n }\n\n init (components: Components) {\n this.components = components\n ;(this.store as PersistentStore).init(components)\n }\n\n async forEach (fn: (peer: Peer) => void) {\n log.trace('getPeers await read lock')\n const release = await this.store.lock.readLock()\n log.trace('getPeers got read lock')\n\n try {\n for await (const peer of this.store.all()) {\n if (peer.id.equals(this.components.getPeerId())) {\n // Skip self peer if present\n continue\n }\n\n fn(peer)\n }\n } finally {\n log.trace('getPeers release read lock')\n release()\n }\n }\n\n async all (): Promise {\n const output: Peer[] = []\n\n await this.forEach(peer => {\n output.push(peer)\n })\n\n return output\n }\n\n /**\n * Delete the information of the given peer in every book\n */\n async delete (peerId: PeerId) {\n log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n log.trace('delete got write lock')\n\n try {\n await this.store.delete(peerId)\n } finally {\n log.trace('delete release write lock')\n release()\n }\n }\n\n /**\n * Get the stored information of a given peer\n */\n async get (peerId: PeerId) {\n log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n log.trace('get got read lock')\n\n try {\n return await this.store.load(peerId)\n } finally {\n log.trace('get release read lock')\n release()\n }\n }\n\n /**\n * Returns true if we have a record of the peer\n */\n async has (peerId: PeerId) {\n log.trace('has await read lock')\n const release = await this.store.lock.readLock()\n log.trace('has got read lock')\n\n try {\n return await this.store.has(peerId)\n } finally {\n log.trace('has release read lock')\n release()\n }\n }\n\n async tagPeer (peerId: PeerId, tag: string, options: TagOptions = {}) {\n const providedValue = options.value ?? 0\n const value = Math.round(providedValue)\n const ttl = options.ttl ?? undefined\n\n if (value !== providedValue || value < 0 || value > 100) {\n throw errCode(new Error('Tag value must be between 0-100'), 'ERR_TAG_VALUE_OUT_OF_BOUNDS')\n }\n\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n for (const t of tags) {\n if (t.name === tag) {\n throw errCode(new Error('Peer already tagged'), 'ERR_DUPLICATE_TAG')\n }\n }\n\n tags.push({\n name: tag,\n value,\n expiry: ttl == null ? undefined : BigInt(Date.now() + ttl)\n })\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async unTagPeer (peerId: PeerId, tag: string) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n tags = tags.filter(t => t.name !== tag)\n\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags }).subarray())\n }\n\n async getTags (peerId: PeerId) {\n const buf = await this.metadataBook.getValue(peerId, 'tags')\n let tags: Tag[] = []\n\n if (buf != null) {\n tags = Tags.decode(buf).tags\n }\n\n const now = BigInt(Date.now())\n const unexpiredTags = tags.filter(tag => tag.expiry == null || tag.expiry > now)\n\n if (unexpiredTags.length !== tags.length) {\n // remove any expired tags\n await this.metadataBook.setValue(peerId, 'tags', Tags.encode({ tags: unexpiredTags }).subarray())\n }\n\n return unexpiredTags.map(t => ({\n name: t.name,\n value: t.value ?? 0\n }))\n }\n}\n","import drain from 'it-drain'\nimport errCode from 'err-code'\nimport type { DHT } from '@libp2p/interface-dht'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { CID } from 'multiformats/cid'\nimport type { AbortOptions } from '@libp2p/interfaces'\n\n/**\n * Wrapper class to convert events into returned values\n */\nexport class DHTContentRouting implements ContentRouting {\n private readonly dht: DHT\n\n constructor (dht: DHT) {\n this.dht = dht\n }\n\n async provide (cid: CID) {\n await drain(this.dht.provide(cid))\n }\n\n async * findProviders (cid: CID, options: AbortOptions = {}) {\n for await (const event of this.dht.findProviders(cid, options)) {\n if (event.name === 'PROVIDER') {\n yield * event.providers\n }\n }\n }\n\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise {\n await drain(this.dht.put(key, value, options))\n }\n\n async get (key: Uint8Array, options?: AbortOptions): Promise {\n for await (const event of this.dht.get(key, options)) {\n if (event.name === 'VALUE') {\n return event.value\n }\n }\n\n throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')\n }\n}\n","import type { PeerInfo } from '@libp2p/interface-peer-info'\nimport { logger } from '@libp2p/logger'\nimport type { Components } from '@libp2p/components'\nimport { TimeoutController } from 'timeout-abort-controller'\nimport { setMaxListeners } from 'events'\n\nconst log = logger('libp2p:dialer:auto-dialer')\n\nexport interface AutoDialerInit {\n enabled: boolean\n minConnections: number\n dialTimeout: number\n}\n\nexport class AutoDialer {\n private readonly components: Components\n private readonly enabled: boolean\n private readonly minConnections: number\n private readonly dialTimeout: number\n\n constructor (components: Components, init: AutoDialerInit) {\n this.components = components\n this.enabled = init.enabled\n this.minConnections = init.minConnections\n this.dialTimeout = init.dialTimeout\n }\n\n public handle (evt: CustomEvent) {\n const { detail: peer } = evt\n\n if (!this.enabled) {\n return\n }\n\n const connections = this.components.getConnectionManager().getConnections(peer.id)\n\n // If auto dialing is on and we have no connection to the peer, check if we should dial\n if (connections.length === 0) {\n const minConnections = this.minConnections ?? 0\n\n const allConnections = this.components.getConnectionManager().getConnections()\n\n if (minConnections > allConnections.length) {\n log('auto-dialing discovered peer %p with timeout %d', peer.id, this.dialTimeout)\n\n const controller = new TimeoutController(this.dialTimeout)\n\n try {\n // fails on node < 15.4\n setMaxListeners?.(Infinity, controller.signal)\n } catch {}\n\n void this.components.getConnectionManager().openConnection(peer.id, {\n signal: controller.signal\n })\n .catch(err => {\n log.error('could not connect to discovered peer %p with %o', peer.id, err)\n })\n .finally(() => {\n controller.clear()\n })\n }\n }\n }\n}\n","const globalFetch = globalThis.fetch;\nconst globalHeaders = globalThis.Headers;\nconst globalRequest = globalThis.Request;\nconst globalResponse = globalThis.Response;\nexport {\n globalFetch as fetch\n};\nexport {\n globalHeaders as Headers\n};\nexport {\n globalRequest as Request\n};\nexport {\n globalResponse as Response\n};","import { fetch as nativeFetch, Headers } from 'native-fetch'\n\n/**\n * Build fetch resource for request\n */\nexport function buildResource (serverResolver: string, hostname: string, recordType: string) {\n return `${serverResolver}?name=${hostname}&type=${recordType}`\n}\n\nexport interface DNSJSON {\n Question: Question[]\n Answer: Answer[]\n}\n\ninterface Question {\n name: string\n type: number\n}\n\ninterface Answer {\n name: string\n type: number\n data: string\n TTL: number\n}\n\n/**\n * Use fetch to find the record\n */\nexport async function request (resource: string, signal: AbortSignal) {\n const req = await nativeFetch(resource, {\n headers: new Headers({\n accept: 'application/dns-json'\n }),\n signal\n })\n const res = await req.json()\n\n return res as DNSJSON\n}\n\n/**\n * Creates cache key composed by recordType and hostname\n *\n * @param {string} hostname\n * @param {string} recordType\n */\nexport function getCacheKey (hostname: string, recordType: string) {\n return `${recordType}_${hostname}`\n}\n","import debug from 'debug'\nimport Receptacle from 'receptacle'\nimport * as utils from './utils.js'\nimport type { DNSJSON } from './utils'\n\nconst log = Object.assign(debug('dns-over-http-resolver'), {\n error: debug('dns-over-http-resolver:error')\n})\n\nexport interface Request { (resource: string, signal: AbortSignal): Promise }\n\ninterface ResolverOptions {\n maxCache?: number\n request?: Request\n}\n\n/**\n * DNS over HTTP resolver.\n * Uses a list of servers to resolve DNS records with HTTP requests.\n */\nclass Resolver {\n private readonly _cache: Receptacle\n private readonly _TXTcache: Receptacle\n private _servers: string[]\n private readonly _request: Request\n private _abortControllers: AbortController[]\n\n /**\n * @class\n * @param {object} [options]\n * @param {number} [options.maxCache = 100] - maximum number of cached dns records\n * @param {Request} [options.request] - function to return DNSJSON\n */\n constructor (options: ResolverOptions = {}) {\n this._cache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._TXTcache = new Receptacle({ max: options?.maxCache ?? 100 })\n this._servers = [\n 'https://cloudflare-dns.com/dns-query',\n 'https://dns.google/resolve'\n ]\n this._request = options.request ?? utils.request\n this._abortControllers = []\n }\n\n /**\n * Cancel all outstanding DNS queries made by this resolver. Any outstanding\n * requests will be aborted and promises rejected.\n */\n cancel () {\n this._abortControllers.forEach(controller => controller.abort())\n }\n\n /**\n * Get an array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n getServers () {\n return this._servers\n }\n\n /**\n * Get a shuffled array of the IP addresses currently configured for DNS resolution.\n * These addresses are formatted according to RFC 5952. It can include a custom port.\n */\n _getShuffledServers () {\n const newServers = [...this._servers]\n\n for (let i = newServers.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i)\n const temp = newServers[i]\n newServers[i] = newServers[j]\n newServers[j] = temp\n }\n\n return newServers\n }\n\n /**\n * Sets the IP address and port of servers to be used when performing DNS resolution.\n *\n * @param {string[]} servers - array of RFC 5952 formatted addresses.\n */\n setServers (servers: string[]) {\n this._servers = servers\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into the appropriate DNS record\n *\n * @param {string} hostname - host name to resolve\n * @param {string} [rrType = 'A'] - resource record type\n */\n async resolve (hostname: string, rrType = 'A') {\n switch (rrType) {\n case 'A':\n return await this.resolve4(hostname)\n case 'AAAA':\n return await this.resolve6(hostname)\n case 'TXT':\n return await this.resolveTxt(hostname)\n default:\n throw new Error(`${rrType} is not supported`)\n }\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv4 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve4 (hostname: string) {\n const recordType = 'A'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryA ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into IPv6 addresses\n *\n * @param {string} hostname - host name to resolve\n */\n async resolve6 (hostname: string) {\n const recordType = 'AAAA'\n const cached = this._cache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => a.data)\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._cache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryAaaa ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n /**\n * Uses the DNS protocol to resolve the given host name into a Text record\n *\n * @param {string} hostname - host name to resolve\n */\n async resolveTxt (hostname: string) {\n const recordType = 'TXT'\n const cached = this._TXTcache.get(utils.getCacheKey(hostname, recordType))\n if (cached != null) {\n return cached\n }\n let aborted = false\n\n for (const server of this._getShuffledServers()) {\n const controller = new AbortController()\n this._abortControllers.push(controller)\n\n try {\n const response = await this._request(utils.buildResource(\n server,\n hostname,\n recordType\n ), controller.signal)\n\n const data = response.Answer.map(a => [a.data.replace(/['\"]+/g, '')])\n const ttl = Math.min(...response.Answer.map(a => a.TTL))\n\n this._TXTcache.set(utils.getCacheKey(hostname, recordType), data, { ttl })\n\n return data\n } catch (err) {\n if (controller.signal.aborted) {\n aborted = true\n }\n\n log.error(`${server} could not resolve ${hostname} record ${recordType}`)\n } finally {\n this._abortControllers = this._abortControllers.filter(c => c !== controller)\n }\n }\n\n if (aborted) {\n throw Object.assign(new Error('queryTxt ECANCELLED'), {\n code: 'ECANCELLED'\n })\n }\n\n throw new Error(`Could not resolve ${hostname} record ${recordType}`)\n }\n\n clearCache () {\n this._cache.clear()\n this._TXTcache.clear()\n }\n}\n\nexport default Resolver\n","import dns from 'dns-over-http-resolver'\n\nexport default dns\n","import { getProtocol } from '../protocols-table.js'\nimport Resolver from './dns.js'\nimport type { AbortOptions, Multiaddr } from '../index.js'\n\nconst { code: dnsaddrCode } = getProtocol('dnsaddr')\n\n/**\n * Resolver for dnsaddr addresses.\n */\nexport async function dnsaddrResolver (addr: Multiaddr, options: AbortOptions = {}) {\n const resolver = new Resolver()\n\n if (options.signal != null) {\n options.signal.addEventListener('abort', () => {\n resolver.cancel()\n })\n }\n\n const peerId = addr.getPeerId()\n const [, hostname] = addr.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? []\n\n if (hostname == null) {\n throw new Error('No hostname found in multiaddr')\n }\n\n const records = await resolver.resolveTxt(`_dnsaddr.${hostname}`)\n\n let addresses = records.flat().map((a) => a.split('=')[1])\n\n if (peerId != null) {\n addresses = addresses.filter((entry) => entry.includes(peerId))\n }\n\n return addresses\n}\n","import mergeOptions from 'merge-options'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport * as Constants from './constants.js'\nimport { AGENT_VERSION } from './identify/consts.js'\nimport * as RelayConstants from './circuit/constants.js'\nimport { publicAddressesFirst } from '@libp2p/utils/address-sort'\nimport { FaultTolerance } from './transport-manager.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Libp2pInit } from './index.js'\nimport { codes, messages } from './errors.js'\nimport errCode from 'err-code'\nimport type { RecursivePartial } from '@libp2p/interfaces'\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'\n\nconst DefaultConfig: Partial = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs: Multiaddr[]) => multiaddrs\n },\n connectionManager: {\n maxConnections: 300,\n minConnections: 50,\n autoDial: true,\n autoDialInterval: 10000,\n maxParallelDials: Constants.MAX_PARALLEL_DIALS,\n maxDialsPerPeer: Constants.MAX_PER_PEER_DIALS,\n dialTimeout: Constants.DIAL_TIMEOUT,\n inboundUpgradeTimeout: Constants.INBOUND_UPGRADE_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n },\n addressSorter: publicAddressesFirst\n },\n connectionGater: {},\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n },\n metrics: {\n enabled: false,\n computeThrottleMaxQueueSize: 1000,\n computeThrottleTimeout: 2000,\n movingAverageIntervals: [\n 60 * 1000, // 1 minute\n 5 * 60 * 1000, // 5 minutes\n 15 * 60 * 1000 // 15 minutes\n ],\n maxOldPeersRetention: 50\n },\n peerRouting: {\n refreshManager: {\n enabled: true,\n interval: 6e5,\n bootDelay: 10e3\n }\n },\n nat: {\n enabled: true,\n ttl: 7200,\n keepAlive: true\n },\n relay: {\n enabled: true,\n advertise: {\n bootDelay: RelayConstants.ADVERTISE_BOOT_DELAY,\n enabled: false,\n ttl: RelayConstants.ADVERTISE_TTL\n },\n hop: {\n enabled: false,\n active: false,\n timeout: 30000\n },\n autoRelay: {\n enabled: false,\n maxListeners: 2\n }\n },\n identify: {\n protocolPrefix: 'ipfs',\n host: {\n agentVersion: AGENT_VERSION\n },\n // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48\n timeout: 60000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxPushIncomingStreams: 1,\n maxPushOutgoingStreams: 1\n },\n ping: {\n protocolPrefix: 'ipfs',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n },\n fetch: {\n protocolPrefix: 'libp2p',\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n timeout: 10000\n }\n}\n\nexport function validateConfig (opts: RecursivePartial): Libp2pInit {\n const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts)\n\n if (resultingOptions.transports == null || resultingOptions.transports.length < 1) {\n throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED)\n }\n\n if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) {\n throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED)\n }\n\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED)\n }\n\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (resultingOptions.identify.host.agentVersion === AGENT_VERSION) {\n if (isNode || isElectronMain) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.process.version}`\n } else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`\n }\n }\n\n return resultingOptions\n}\n","/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\nimport type { Codec } from 'protons-runtime'\n\nexport interface PeerIdProto {\n id: Uint8Array\n pubKey?: Uint8Array\n privKey?: Uint8Array\n}\n\nexport namespace PeerIdProto {\n let _codec: Codec\n\n export const codec = (): Codec => {\n if (_codec == null) {\n _codec = message((obj, writer, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n writer.fork()\n }\n\n if (obj.id != null) {\n writer.uint32(10)\n writer.bytes(obj.id)\n } else {\n throw new Error('Protocol error: required field \"id\" was not found in object')\n }\n\n if (obj.pubKey != null) {\n writer.uint32(18)\n writer.bytes(obj.pubKey)\n }\n\n if (obj.privKey != null) {\n writer.uint32(26)\n writer.bytes(obj.privKey)\n }\n\n if (opts.lengthDelimited !== false) {\n writer.ldelim()\n }\n }, (reader, length) => {\n const obj: any = {\n id: new Uint8Array(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1:\n obj.id = reader.bytes()\n break\n case 2:\n obj.pubKey = reader.bytes()\n break\n case 3:\n obj.privKey = reader.bytes()\n break\n default:\n reader.skipType(tag & 7)\n break\n }\n }\n\n if (obj.id == null) {\n throw new Error('Protocol error: value for required field \"id\" was not found in protobuf')\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: PeerIdProto): Uint8Array => {\n return encodeMessage(obj, PeerIdProto.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList): PeerIdProto => {\n return decodeMessage(buf, PeerIdProto.codec())\n }\n}\n","import { generateKeyPair, marshalPrivateKey, unmarshalPrivateKey, marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { peerIdFromKeys, peerIdFromBytes } from '@libp2p/peer-id'\nimport { PeerIdProto } from './proto.js'\nimport type { PublicKey, PrivateKey } from '@libp2p/interface-keys'\nimport type { RSAPeerId, Ed25519PeerId, Secp256k1PeerId, PeerId } from '@libp2p/interface-peer-id'\n\nexport const createEd25519PeerId = async (): Promise => {\n const key = await generateKeyPair('Ed25519')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'Ed25519') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createSecp256k1PeerId = async (): Promise => {\n const key = await generateKeyPair('secp256k1')\n const id = await createFromPrivKey(key)\n\n if (id.type === 'secp256k1') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport const createRSAPeerId = async (opts?: { bits: number }): Promise => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048)\n const id = await createFromPrivKey(key)\n\n if (id.type === 'RSA') {\n return id\n }\n\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`)\n}\n\nexport async function createFromPubKey (publicKey: PublicKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(publicKey))\n}\n\nexport async function createFromPrivKey (privateKey: PrivateKey): Promise {\n return await peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey))\n}\n\nexport function exportToProtobuf (peerId: RSAPeerId | Ed25519PeerId | Secp256k1PeerId, excludePrivateKey?: boolean): Uint8Array {\n return PeerIdProto.encode({\n id: peerId.multihash.bytes,\n pubKey: peerId.publicKey,\n privKey: excludePrivateKey === true || peerId.privateKey == null ? undefined : peerId.privateKey\n })\n}\n\nexport async function createFromProtobuf (buf: Uint8Array) {\n const {\n id,\n privKey,\n pubKey\n } = PeerIdProto.decode(buf)\n\n return await createFromParts(\n id,\n privKey,\n pubKey\n )\n}\n\nexport async function createFromJSON (obj: { id: string, privKey?: string, pubKey?: string }) {\n return await createFromParts(\n uint8ArrayFromString(obj.id, 'base58btc'),\n obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined,\n obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined\n )\n}\n\nasync function createFromParts (multihash: Uint8Array, privKey?: Uint8Array, pubKey?: Uint8Array) {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey)\n\n return await createFromPrivKey(key)\n } else if (pubKey != null) {\n const key = await unmarshalPublicKey(pubKey)\n\n return await createFromPubKey(key)\n }\n\n return peerIdFromBytes(multihash)\n}\n","import type { DualDHT, QueryEvent, SingleDHT } from '@libp2p/interface-dht'\nimport type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\nimport { EventEmitter } from '@libp2p/interfaces/events'\nimport { symbol } from '@libp2p/interface-peer-discovery'\n\nexport class DummyDHT extends EventEmitter implements DualDHT {\n get [symbol] (): true {\n return true\n }\n\n get [Symbol.toStringTag] () {\n return '@libp2p/dummy-dht'\n }\n\n get wan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get lan (): SingleDHT {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n get (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findProviders (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n findPeer (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n getClosestPeers (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n provide (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n put (): AsyncIterable {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async getMode (): Promise<'client' | 'server'> {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async setMode (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n\n async refreshRoutingTable (): Promise {\n throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED)\n }\n}\n","import { EventEmitter } from '@libp2p/interfaces/events'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign } from '@libp2p/interface-pubsub'\nimport errCode from 'err-code'\nimport { messages, codes } from '../errors.js'\n\nexport class DummyPubSub extends EventEmitter implements PubSub {\n isStarted (): boolean {\n return false\n }\n\n start (): void | Promise {\n\n }\n\n stop (): void | Promise {\n\n }\n\n get globalSignaturePolicy (): typeof StrictSign | typeof StrictNoSign {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n get multicodecs (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getPeers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getTopics (): string[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n subscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n unsubscribe (): void {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n getSubscribers (): PeerId[] {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n\n async publish (): Promise {\n throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED)\n }\n}\n","import { logger } from '@libp2p/logger'\nimport type { AbortOptions } from '@libp2p/interfaces'\nimport { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'\nimport { Startable, isStartable } from '@libp2p/interfaces/startable'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport { MemoryDatastore } from 'datastore-core/memory'\nimport { DefaultPeerRouting } from './peer-routing.js'\nimport { CompoundContentRouting } from './content-routing/index.js'\nimport { getPeer } from './get-peer.js'\nimport { codes } from './errors.js'\nimport { DefaultAddressManager } from './address-manager/index.js'\nimport { DefaultConnectionManager } from './connection-manager/index.js'\nimport { AutoDialler } from './connection-manager/auto-dialler.js'\nimport { Circuit } from './circuit/transport.js'\nimport { Relay } from './circuit/index.js'\nimport { KeyChain } from './keychain/index.js'\nimport { DefaultMetrics } from './metrics/index.js'\nimport { DefaultTransportManager } from './transport-manager.js'\nimport { DefaultUpgrader } from './upgrader.js'\nimport { DefaultRegistrar } from './registrar.js'\nimport { IdentifyService } from './identify/index.js'\nimport { FetchService } from './fetch/index.js'\nimport { PingService } from './ping/index.js'\nimport { NatManager } from './nat-manager.js'\nimport { PeerRecordUpdater } from './peer-record-updater.js'\nimport { DHTPeerRouting } from './dht/dht-peer-routing.js'\nimport { PersistentPeerStore } from '@libp2p/peer-store'\nimport { DHTContentRouting } from './dht/dht-content-routing.js'\nimport { AutoDialer } from './connection-manager/dialer/auto-dialer.js'\nimport { Initializable, Components, isInitializable } from '@libp2p/components'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { Connection } from '@libp2p/interface-connection'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { Libp2p, Libp2pEvents, Libp2pInit, Libp2pOptions } from './index.js'\nimport { validateConfig } from './config.js'\nimport { createEd25519PeerId } from '@libp2p/peer-id-factory'\nimport type { PeerStore } from '@libp2p/interface-peer-store'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport errCode from 'err-code'\nimport { unmarshalPublicKey } from '@libp2p/crypto/keys'\nimport type { Metrics } from '@libp2p/interface-metrics'\nimport { DummyDHT } from './dht/dummy-dht.js'\nimport { DummyPubSub } from './pubsub/dummy-pubsub.js'\nimport { PeerSet } from '@libp2p/peer-collections'\n\nconst log = logger('libp2p')\n\nexport class Libp2pNode extends EventEmitter implements Libp2p {\n public peerId: PeerId\n public dht: DualDHT\n public pubsub: PubSub\n public identifyService?: IdentifyService\n public fetchService: FetchService\n public pingService: PingService\n public components: Components\n public peerStore: PeerStore\n public contentRouting: ContentRouting\n public peerRouting: PeerRouting\n public keychain: KeyChain\n public connectionManager: ConnectionManager\n public registrar: Registrar\n public metrics?: Metrics\n\n private started: boolean\n private readonly services: Startable[]\n private readonly initializables: Initializable[]\n\n constructor (init: Libp2pInit) {\n super()\n\n this.initializables = []\n this.started = false\n this.peerId = init.peerId\n this.components = new Components({\n peerId: init.peerId,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: {\n denyDialPeer: async () => await Promise.resolve(false),\n denyDialMultiaddr: async () => await Promise.resolve(false),\n denyInboundConnection: async () => await Promise.resolve(false),\n denyOutboundConnection: async () => await Promise.resolve(false),\n denyInboundEncryptedConnection: async () => await Promise.resolve(false),\n denyOutboundEncryptedConnection: async () => await Promise.resolve(false),\n denyInboundUpgradedConnection: async () => await Promise.resolve(false),\n denyOutboundUpgradedConnection: async () => await Promise.resolve(false),\n filterMultiaddrForPeer: async () => await Promise.resolve(true),\n ...init.connectionGater\n }\n })\n this.components.setPeerStore(new PersistentPeerStore({\n addressFilter: this.components.getConnectionGater().filterMultiaddrForPeer,\n ...init.peerStore\n }))\n\n this.services = [\n this.components\n ]\n\n // Create Metrics\n if (init.metrics.enabled) {\n this.metrics = this.components.setMetrics(new DefaultMetrics(init.metrics))\n }\n\n this.peerStore = this.components.getPeerStore()\n\n this.peerStore.addEventListener('peer', evt => {\n const { detail: peerData } = evt\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peerData }))\n })\n\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.components.setConnectionProtector(init.connectionProtector)\n }\n\n // Set up the Upgrader\n this.components.setUpgrader(new DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map(component => this.configureComponent(component)),\n muxers: (init.streamMuxers ?? []).map(component => this.configureComponent(component)),\n inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout\n }))\n\n // Create the Connection Manager\n this.connectionManager = this.components.setConnectionManager(new DefaultConnectionManager(init.connectionManager))\n\n // Create the Registrar\n this.registrar = this.components.setRegistrar(new DefaultRegistrar(this.components))\n\n // Setup the transport manager\n this.components.setTransportManager(new DefaultTransportManager(this.components, init.transportManager))\n\n // Addresses {listen, announce, noAnnounce}\n this.components.setAddressManager(new DefaultAddressManager(this.components, init.addresses))\n\n // update our peer record when addresses change\n this.configureComponent(new PeerRecordUpdater(this.components))\n\n this.configureComponent(new AutoDialler(this.components, {\n enabled: init.connectionManager.autoDial,\n minConnections: init.connectionManager.minConnections,\n autoDialInterval: init.connectionManager.autoDialInterval\n }))\n\n // Create keychain\n const keychainOpts = KeyChain.generateOptions()\n this.keychain = this.configureComponent(new KeyChain(this.components, {\n ...keychainOpts,\n ...init.keychain\n }))\n\n // Create the Nat Manager\n this.services.push(new NatManager(this.components, init.nat))\n\n init.transports.forEach((transport) => {\n this.components.getTransportManager().add(this.configureComponent(transport))\n })\n\n // Attach stream multiplexers\n if (init.streamMuxers != null && init.streamMuxers.length > 0) {\n // Add the identify service since we can multiplex\n this.identifyService = new IdentifyService(this.components, {\n ...init.identify\n })\n this.configureComponent(this.identifyService)\n }\n\n // dht provided components (peerRouting, contentRouting, dht)\n if (init.dht != null) {\n this.dht = this.components.setDHT(init.dht)\n } else {\n this.dht = new DummyDHT()\n }\n\n // Create pubsub if provided\n if (init.pubsub != null) {\n this.pubsub = this.components.setPubSub(init.pubsub)\n } else {\n this.pubsub = new DummyPubSub()\n }\n\n // Attach remaining APIs\n // peer and content routing will automatically get modules from _modules and _dht\n\n const peerRouters: PeerRouting[] = (init.peerRouters ?? []).map(component => this.configureComponent(component))\n\n if (init.dht != null) {\n // add dht to routers\n peerRouters.push(this.configureComponent(new DHTPeerRouting(this.dht)))\n\n // use dht for peer discovery\n this.dht.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n\n this.peerRouting = this.components.setPeerRouting(this.configureComponent(new DefaultPeerRouting(this.components, {\n ...init.peerRouting,\n routers: peerRouters\n })))\n\n const contentRouters: ContentRouting[] = (init.contentRouters ?? []).map(component => this.configureComponent(component))\n\n if (init.dht != null) {\n // add dht to routers\n contentRouters.push(this.configureComponent(new DHTContentRouting(this.dht)))\n }\n\n this.contentRouting = this.components.setContentRouting(this.configureComponent(new CompoundContentRouting(this.components, {\n routers: contentRouters\n })))\n\n if (init.relay.enabled) {\n this.components.getTransportManager().add(this.configureComponent(new Circuit(init.relay)))\n\n this.configureComponent(new Relay(this.components, {\n addressSorter: init.connectionManager.addressSorter,\n ...init.relay\n }))\n }\n\n this.fetchService = this.configureComponent(new FetchService(this.components, {\n ...init.fetch\n }))\n\n this.pingService = this.configureComponent(new PingService(this.components, {\n ...init.ping\n }))\n\n const autoDialer = this.configureComponent(new AutoDialer(this.components, {\n enabled: init.connectionManager.autoDial !== false,\n minConnections: init.connectionManager.minConnections,\n dialTimeout: init.connectionManager.dialTimeout ?? 30000\n }))\n\n this.addEventListener('peer:discovery', evt => {\n if (!this.isStarted()) {\n return\n }\n\n autoDialer.handle(evt)\n })\n\n // Discovery modules\n for (const service of init.peerDiscovery ?? []) {\n this.configureComponent(service)\n\n service.addEventListener('peer', (evt) => {\n this.onDiscoveryPeer(evt)\n })\n }\n }\n\n private configureComponent (component: T): T {\n if (isStartable(component)) {\n this.services.push(component)\n }\n\n if (isInitializable(component)) {\n this.initializables.push(component)\n }\n\n return component\n }\n\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start () {\n if (this.started) {\n return\n }\n\n this.started = true\n\n log('libp2p is starting')\n\n try {\n // Set available components on all modules interested in components\n this.initializables.forEach(obj => {\n obj.init(this.components)\n })\n\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStart != null) {\n await service.beforeStart()\n }\n })\n )\n\n // start any startables\n await Promise.all(\n this.services.map(service => service.start())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStart != null) {\n await service.afterStart()\n }\n })\n )\n\n log('libp2p has started')\n } catch (err: any) {\n log.error('An error occurred starting libp2p', err)\n await this.stop()\n throw err\n }\n }\n\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop () {\n if (!this.started) {\n return\n }\n\n log('libp2p is stopping')\n\n this.started = false\n\n await Promise.all(\n this.services.map(async service => {\n if (service.beforeStop != null) {\n await service.beforeStop()\n }\n })\n )\n\n await Promise.all(\n this.services.map(servce => servce.stop())\n )\n\n await Promise.all(\n this.services.map(async service => {\n if (service.afterStop != null) {\n await service.afterStop()\n }\n })\n )\n\n log('libp2p has stopped')\n }\n\n /**\n * Load keychain keys from the datastore.\n * Imports the private key as 'self', if needed.\n */\n async loadKeychain () {\n if (this.keychain == null) {\n return\n }\n\n try {\n await this.keychain.findKeyByName('self')\n } catch (err: any) {\n await this.keychain.importPeer('self', this.peerId)\n }\n }\n\n isStarted () {\n return this.started\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n return this.components.getConnectionManager().getConnections(peerId)\n }\n\n getPeers (): PeerId[] {\n const peerSet = new PeerSet()\n\n for (const conn of this.components.getConnectionManager().getConnections()) {\n peerSet.add(conn.remotePeer)\n }\n\n return Array.from(peerSet)\n }\n\n async dial (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n\n return await this.components.getConnectionManager().openConnection(id, options)\n }\n\n async dialProtocol (peer: PeerId | Multiaddr, protocols: string | string[], options: AbortOptions = {}) {\n if (protocols == null) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n\n if (protocols.length === 0) {\n throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)\n }\n\n const connection = await this.dial(peer, options)\n\n return await connection.newStream(protocols, options)\n }\n\n getMultiaddrs (): Multiaddr[] {\n return this.components.getAddressManager().getAddresses()\n }\n\n async hangUp (peer: PeerId | Multiaddr | string): Promise {\n const { id } = getPeer(peer)\n\n await this.components.getConnectionManager().closeConnections(id)\n }\n\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise {\n log('getPublicKey %p', peer)\n\n if (peer.publicKey != null) {\n return peer.publicKey\n }\n\n const peerInfo = await this.peerStore.get(peer)\n\n if (peerInfo.pubKey != null) {\n return peerInfo.pubKey\n }\n\n if (this.dht == null) {\n throw errCode(new Error('Public key was not in the peer store and the DHT is not enabled'), codes.ERR_NO_ROUTERS_AVAILABLE)\n }\n\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.multihash.digest\n ])\n\n // search the dht\n for await (const event of this.dht.get(peerKey, options)) {\n if (event.name === 'VALUE') {\n const key = unmarshalPublicKey(event.value)\n\n await this.peerStore.keyBook.set(peer, event.value)\n\n return key.bytes\n }\n }\n\n throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD)\n }\n\n async fetch (peer: PeerId | Multiaddr | string, key: string, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (multiaddrs != null) {\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n return await this.fetchService.fetch(id, key, options)\n }\n\n async ping (peer: PeerId | Multiaddr | string, options: AbortOptions = {}): Promise {\n const { id, multiaddrs } = getPeer(peer)\n\n if (multiaddrs.length > 0) {\n await this.components.getPeerStore().addressBook.add(id, multiaddrs)\n }\n\n return await this.pingService.ping(id, options)\n }\n\n async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.getRegistrar().handle(protocol, handler, options)\n })\n )\n }\n\n async unhandle (protocols: string[] | string): Promise {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.getRegistrar().unhandle(protocol)\n })\n )\n }\n\n /**\n * Called whenever peer discovery services emit `peer` events.\n * Known peers may be emitted.\n */\n onDiscoveryPeer (evt: CustomEvent) {\n const { detail: peer } = evt\n\n if (peer.id.toString() === this.peerId.toString()) {\n log.error(new Error(codes.ERR_DISCOVERED_SELF))\n return\n }\n\n if (peer.multiaddrs.length > 0) {\n void this.components.getPeerStore().addressBook.add(peer.id, peer.multiaddrs).catch(err => log.error(err))\n }\n\n if (peer.protocols.length > 0) {\n void this.components.getPeerStore().protoBook.set(peer.id, peer.protocols).catch(err => log.error(err))\n }\n\n this.dispatchEvent(new CustomEvent('peer:discovery', { detail: peer }))\n }\n}\n\n/**\n * Returns a new Libp2pNode instance - this exposes more of the internals than the\n * libp2p interface and is useful for testing and debugging.\n */\nexport async function createLibp2pNode (options: Libp2pOptions): Promise {\n if (options.peerId == null) {\n options.peerId = await createEd25519PeerId()\n }\n\n return new Libp2pNode(validateConfig(options))\n}\n","import { Noise } from \"@chainsafe/libp2p-noise\";\nimport type { PeerDiscovery } from \"@libp2p/interface-peer-discovery\";\nimport { Mplex } from \"@libp2p/mplex\";\nimport { WebSockets } from \"@libp2p/websockets\";\nimport { all as filterAll } from \"@libp2p/websockets/filters\";\nimport { createLibp2p, Libp2pOptions } from \"libp2p\";\nimport type { Libp2p } from \"libp2p\";\n\nimport { PeerDiscoveryStaticPeers } from \"./peer_discovery_static_list\";\nimport { getPredefinedBootstrapNodes } from \"./predefined_bootstrap_nodes\";\nimport { Waku, WakuOptions } from \"./waku\";\nimport { WakuFilter } from \"./waku_filter\";\nimport { WakuLightPush } from \"./waku_light_push\";\nimport { WakuRelay } from \"./waku_relay\";\nimport { WakuStore } from \"./waku_store\";\n\nexport interface CreateOptions {\n /**\n * The PubSub Topic to use.\n *\n * One and only one pubsub topic is used by Waku. This is used by:\n * - WakuRelay to receive, route and send messages,\n * - WakuLightPush to send messages,\n * - WakuStore to retrieve messages.\n *\n * The usage of the default pubsub topic is recommended.\n * See [Waku v2 Topic Usage Recommendations](https://rfc.vac.dev/spec/23/) for details.\n *\n * @default {@link index.DefaultPubSubTopic}\n */\n pubSubTopic?: string;\n /**\n * You can pass options to the `Libp2p` instance used by {@link index.waku.Waku} using the {@link CreateOptions.libp2p} property.\n * This property is the same type than the one passed to [`Libp2p.create`](https://github.com/libp2p/js-libp2p/blob/master/doc/API.md#create)\n * apart that we made the `modules` property optional and partial,\n * allowing its omission and letting Waku set good defaults.\n * Notes that some values are overridden by {@link index.waku.Waku} to ensure it implements the Waku protocol.\n */\n libp2p?: Partial;\n /**\n * Byte array used as key for the noise protocol used for connection encryption\n * by [`Libp2p.create`](https://github.com/libp2p/js-libp2p/blob/master/doc/API.md#create)\n * This is only used for test purposes to not run out of entropy during CI runs.\n */\n staticNoiseKey?: Uint8Array;\n /**\n * Use recommended bootstrap method to discovery and connect to new nodes.\n */\n defaultBootstrap?: boolean;\n}\n\nexport async function createWaku(\n options?: CreateOptions & WakuOptions\n): Promise {\n const libp2pOptions = options?.libp2p ?? {};\n const peerDiscovery = libp2pOptions.peerDiscovery ?? [];\n if (options?.defaultBootstrap) {\n peerDiscovery.push(defaultPeerDiscovery());\n Object.assign(libp2pOptions, { peerDiscovery });\n }\n\n const libp2p = await defaultLibp2p(new WakuRelay(options), libp2pOptions);\n\n const wakuStore = new WakuStore(libp2p, options);\n const wakuLightPush = new WakuLightPush(libp2p, options);\n const wakuFilter = new WakuFilter(libp2p, options);\n\n return new Waku(options ?? {}, libp2p, wakuStore, wakuLightPush, wakuFilter);\n}\n\nexport function defaultPeerDiscovery(): PeerDiscovery {\n return new PeerDiscoveryStaticPeers(getPredefinedBootstrapNodes());\n}\n\nexport async function defaultLibp2p(\n wakuRelay: WakuRelay,\n options?: Partial\n): Promise {\n const libp2pOpts = Object.assign(\n {\n transports: [new WebSockets({ filter: filterAll })],\n streamMuxers: [new Mplex()],\n connectionEncryption: [new Noise()],\n },\n { pubsub: wakuRelay },\n options ?? {}\n );\n\n return createLibp2p(libp2pOpts);\n}\n","import { createLibp2pNode } from './libp2p.js'\nimport type { AbortOptions, RecursivePartial } from '@libp2p/interfaces'\nimport type { EventEmitter } from '@libp2p/interfaces/events'\nimport type { Startable } from '@libp2p/interfaces/startable'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { FaultTolerance } from './transport-manager.js'\nimport type { IdentifyServiceInit } from './identify/index.js'\nimport type { DualDHT } from '@libp2p/interface-dht'\nimport type { Datastore } from 'interface-datastore'\nimport type { PeerStore, PeerStoreInit } from '@libp2p/interface-peer-store'\nimport type { PeerId } from '@libp2p/interface-peer-id'\nimport type { AutoRelayConfig, RelayAdvertiseConfig } from './circuit/index.js'\nimport type { PeerDiscovery } from '@libp2p/interface-peer-discovery'\nimport type { Connection, ConnectionGater, ConnectionProtector, Stream } from '@libp2p/interface-connection'\nimport type { Transport } from '@libp2p/interface-transport'\nimport type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'\nimport type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'\nimport type { PeerRouting } from '@libp2p/interface-peer-routing'\nimport type { ContentRouting } from '@libp2p/interface-content-routing'\nimport type { PubSub } from '@libp2p/interface-pubsub'\nimport type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'\nimport type { ConnectionManager } from '@libp2p/interface-connection-manager'\nimport type { Metrics, MetricsInit } from '@libp2p/interface-metrics'\nimport type { PeerInfo } from '@libp2p/interface-peer-info'\nimport type { KeyChain } from './keychain/index.js'\nimport type { ConnectionManagerInit } from './connection-manager/index.js'\nimport type { PingServiceInit } from './ping/index.js'\nimport type { FetchServiceInit } from './fetch/index.js'\n\nexport interface PersistentPeerStoreOptions {\n threshold?: number\n}\n\nexport interface DEKConfig {\n keyLength: number\n iterationCount: number\n salt: string\n hash: string\n}\n\nexport interface KeychainConfig {\n pass?: string\n dek?: DEKConfig\n}\n\nexport interface MetricsConfig {\n enabled?: boolean\n}\n\nexport interface HopConfig {\n enabled?: boolean\n active?: boolean\n timeout: number\n}\n\nexport interface RelayConfig {\n enabled: boolean\n advertise: RelayAdvertiseConfig\n hop: HopConfig\n autoRelay: AutoRelayConfig\n}\n\nexport interface NatManagerConfig {\n enabled: boolean\n externalAddress?: string\n localAddress?: string\n description?: string\n ttl?: number\n keepAlive: boolean\n gateway?: string\n}\n\nexport interface AddressesConfig {\n listen: string[]\n announce: string[]\n noAnnounce: string[]\n announceFilter: (multiaddrs: Multiaddr[]) => Multiaddr[]\n}\n\nexport interface TransportManagerConfig {\n faultTolerance?: FaultTolerance\n}\n\nexport interface PeerStoreConfig {\n persistence?: boolean\n threshold?: number\n}\n\nexport interface PeerRoutingConfig {\n refreshManager: RefreshManagerConfig\n}\n\nexport interface RefreshManagerConfig {\n enabled?: boolean\n interval: number\n bootDelay: number\n}\n\nexport interface Libp2pInit {\n peerId: PeerId\n addresses: AddressesConfig\n connectionManager: ConnectionManagerInit\n connectionGater: Partial\n transportManager: TransportManagerConfig\n datastore: Datastore\n metrics: MetricsInit\n peerStore: PeerStoreInit\n peerRouting: PeerRoutingConfig\n keychain: KeychainConfig\n nat: NatManagerConfig\n relay: RelayConfig\n identify: IdentifyServiceInit\n ping: PingServiceInit\n fetch: FetchServiceInit\n\n transports: Transport[]\n streamMuxers?: StreamMuxerFactory[]\n connectionEncryption?: ConnectionEncrypter[]\n peerDiscovery?: PeerDiscovery[]\n peerRouters?: PeerRouting[]\n contentRouters?: ContentRouting[]\n dht?: DualDHT\n pubsub?: PubSub\n connectionProtector?: ConnectionProtector\n}\n\nexport interface Libp2pEvents {\n 'peer:discovery': CustomEvent\n}\n\nexport interface Libp2p extends Startable, EventEmitter {\n peerId: PeerId\n peerStore: PeerStore\n peerRouting: PeerRouting\n contentRouting: ContentRouting\n keychain: KeyChain\n connectionManager: ConnectionManager\n registrar: Registrar\n metrics?: Metrics\n pubsub: PubSub\n dht: DualDHT\n\n /**\n * Load keychain keys from the datastore.\n * Imports the private key as 'self', if needed.\n */\n loadKeychain: () => Promise\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n */\n getMultiaddrs: () => Multiaddr[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n */\n getConnections: (peerId?: PeerId) => Connection[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers: () => PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`\n */\n dial: (peer: PeerId | Multiaddr, options?: AbortOptions) => Promise\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n */\n dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise\n\n /**\n * Disconnects all connections to the given `peer`\n */\n hangUp: (peer: PeerId | Multiaddr | string) => Promise\n\n /**\n * Registers the `handler` for each protocol\n */\n handle: (protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions) => Promise\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n unhandle: (protocols: string[] | string) => Promise\n\n /**\n * Pings the given peer in order to obtain the operation latency\n */\n ping: (peer: Multiaddr | PeerId, options?: AbortOptions) => Promise\n\n /**\n * Sends a request to fetch the value associated with the given key from the given peer.\n */\n fetch: (peer: PeerId | Multiaddr | string, key: string, options?: AbortOptions) => Promise\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA' type\n * this may mean searching the DHT if the key is not present in the KeyStore.\n */\n getPublicKey: (peer: PeerId, options?: AbortOptions) => Promise\n}\n\nexport type Libp2pOptions = RecursivePartial\n\n/**\n * Returns a new instance of the Libp2p interface, generating a new PeerId\n * if one is not passed as part of the options.\n */\nexport async function createLibp2p (options: Libp2pOptions): Promise {\n return await createLibp2pNode(options)\n}\n","import { useEffect, useReducer, useState } from \"react\";\nimport \"./App.css\";\nimport {\n PageDirection,\n Protocols,\n Waku,\n WakuFilter,\n WakuLightPush,\n WakuMessage,\n WakuRelay,\n WakuStore,\n} from \"js-waku\";\nimport handleCommand from \"./command\";\nimport Room from \"./Room\";\nimport { WakuContext } from \"./WakuContext\";\nimport { ThemeProvider } from \"@livechat/ui-kit\";\nimport { generate } from \"server-name-generator\";\nimport { Message } from \"./Message\";\nimport {\n Fleet,\n getPredefinedBootstrapNodes,\n} from \"js-waku/lib/predefined_bootstrap_nodes\";\nimport { waitForRemotePeer } from \"js-waku/lib/wait_for_remote_peer\";\nimport { PeerDiscoveryStaticPeers } from \"js-waku/lib/peer_discovery_static_list\";\nimport { defaultLibp2p } from \"js-waku/lib/create_waku\";\nimport process from \"process\";\n\nconst themes = {\n AuthorName: {\n css: {\n fontSize: \"1.1em\",\n },\n },\n Message: {\n css: {\n margin: \"0em\",\n padding: \"0em\",\n fontSize: \"0.83em\",\n },\n },\n MessageText: {\n css: {\n margin: \"0em\",\n padding: \"0.1em\",\n paddingLeft: \"1em\",\n fontSize: \"1.1em\",\n },\n },\n MessageGroup: {\n css: {\n margin: \"0em\",\n padding: \"0.2em\",\n },\n },\n};\n\nexport const ChatContentTopic = \"/toy-chat/2/huilong/proto\";\n\nasync function retrieveStoreMessages(\n waku: Waku,\n setArchivedMessages: (value: Message[]) => void\n): Promise {\n const callback = (wakuMessages: WakuMessage[]): void => {\n const messages: Message[] = [];\n wakuMessages\n .map((wakuMsg) => Message.fromWakuMessage(wakuMsg))\n .forEach((message) => {\n if (message) {\n messages.push(message);\n }\n });\n setArchivedMessages(messages);\n };\n\n const startTime = new Date();\n // Only retrieve a week of history\n startTime.setTime(Date.now() - 1000 * 60 * 60 * 24 * 7);\n\n const endTime = new Date();\n\n try {\n const res = await waku.store.queryHistory([ChatContentTopic], {\n pageSize: 5,\n pageDirection: PageDirection.FORWARD,\n timeFilter: {\n startTime,\n endTime,\n },\n callback,\n });\n\n return res.length;\n } catch (e) {\n console.log(\"Failed to retrieve messages\", e);\n return 0;\n }\n}\n\nexport default function App() {\n const [messages, dispatchMessages] = useReducer(reduceMessages, []);\n const [waku, setWaku] = useState(undefined);\n const [nick, setNick] = useState(() => {\n const persistedNick = window.localStorage.getItem(\"nick\");\n return persistedNick !== null ? persistedNick : generate();\n });\n const [historicalMessagesRetrieved, setHistoricalMessagesRetrieved] =\n useState(false);\n\n useEffect(() => {\n localStorage.setItem(\"nick\", nick);\n }, [nick]);\n\n useEffect(() => {\n initWaku(setWaku)\n .then(() => console.log(\"Waku init done\"))\n .catch((e) => console.log(\"Waku init failed \", e));\n }, []);\n\n useEffect(() => {\n if (!waku) return;\n // Let's retrieve previous messages before listening to new messages\n if (!historicalMessagesRetrieved) return;\n\n const handleIncomingMessage = (wakuMsg: WakuMessage) => {\n console.log(\"Message received: \", wakuMsg);\n const msg = Message.fromWakuMessage(wakuMsg);\n if (msg) {\n dispatchMessages([msg]);\n }\n };\n\n let unsubscribe: undefined | (() => Promise);\n waku.filter.subscribe(handleIncomingMessage, [ChatContentTopic]).then(\n (_unsubscribe) => {\n console.log(\"subscribed to \", ChatContentTopic);\n unsubscribe = _unsubscribe;\n },\n (e) => {\n console.error(\"Failed to subscribe\", e);\n }\n );\n\n return function cleanUp() {\n if (!waku) return;\n if (typeof unsubscribe === \"undefined\") return;\n unsubscribe().then(\n () => {\n console.log(\"unsubscribed to \", ChatContentTopic);\n },\n (e) => console.error(\"Failed to unsubscribe\", e)\n );\n };\n }, [waku, historicalMessagesRetrieved]);\n\n useEffect(() => {\n if (!waku) return;\n if (historicalMessagesRetrieved) return;\n\n const retrieveMessages = async () => {\n await waitForRemotePeer(waku, [\n Protocols.Store,\n Protocols.Filter,\n Protocols.LightPush,\n ]);\n console.log(`Retrieving archived messages`);\n\n try {\n retrieveStoreMessages(waku, dispatchMessages).then((length) => {\n console.log(`Messages retrieved:`, length);\n setHistoricalMessagesRetrieved(true);\n });\n } catch (e) {\n console.log(`Error encountered when retrieving archived messages`, e);\n }\n };\n\n retrieveMessages();\n }, [waku, historicalMessagesRetrieved]);\n\n return (\n \n \n \n {\n handleCommand(input, waku, setNick).then(\n ({ command, response }) => {\n const commandMessages = response.map((msg) => {\n return Message.fromUtf8String(command, msg);\n });\n dispatchMessages(commandMessages);\n }\n );\n }}\n />\n \n \n
    \n );\n}\n\nasync function initWaku(setter: (waku: Waku) => void) {\n try {\n // TODO: Remove this declaration once there are optional in js-waku\n const wakuRelay = new WakuRelay({ emitSelf: true });\n\n const libp2p = await defaultLibp2p(wakuRelay, {\n peerDiscovery: [\n new PeerDiscoveryStaticPeers(\n getPredefinedBootstrapNodes(selectFleetEnv())\n ),\n ],\n });\n const wakuStore = new WakuStore(libp2p);\n\n const wakuLightPush = new WakuLightPush(libp2p);\n const wakuFilter = new WakuFilter(libp2p);\n\n const waku = new Waku({}, libp2p, wakuStore, wakuLightPush, wakuFilter);\n await waku.start();\n\n setter(waku);\n } catch (e) {\n console.log(\"Issue starting waku \", e);\n }\n}\n\nfunction selectFleetEnv() {\n // Works with react-scripts\n // TODO: Re-enable the switch once nwaku v0.12 is deployed\n if (true || process?.env?.NODE_ENV === \"development\") {\n return Fleet.Test;\n } else {\n return Fleet.Prod;\n }\n}\n\nfunction reduceMessages(state: Message[], newMessages: Message[]) {\n return state.concat(newMessages);\n}\n","import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport \"./index.css\";\nimport App from \"./App\";\n\nReactDOM.render(\n \n \n ,\n document.getElementById(\"root\")\n);\n"],"names":["reactIs","require","REACT_STATICS","childContextTypes","contextType","contextTypes","defaultProps","displayName","getDefaultProps","getDerivedStateFromError","getDerivedStateFromProps","mixins","propTypes","type","KNOWN_STATICS","name","length","prototype","caller","callee","arguments","arity","MEMO_STATICS","compare","TYPE_STATICS","getStatics","component","isMemo","ForwardRef","render","Memo","defineProperty","Object","getOwnPropertyNames","getOwnPropertySymbols","getOwnPropertyDescriptor","getPrototypeOf","objectPrototype","module","exports","hoistNonReactStatics","targetComponent","sourceComponent","blacklist","inheritedComponent","keys","concat","targetStatics","sourceStatics","i","key","descriptor","e","fn","ctx","params","Array","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","charAt","Math","ceil","b64","s64","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","undefined","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","on","evt","off","listeners","splice","emit","args","fetch","asPromise","fs","inquire","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","Float32Array","f32","f8b","le","writeFloat_f32_cpy","val","buf","pos","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","writeFloat_ieee754","writeUint","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","moduleName","mod","eval","path","isAbsolute","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","call","utf8","len","read","write","c1","c2","writeUint16BE","out","writeUint16LE","readInt32BE","array","readUint32BE","readInt32LE","readUint32LE","writeUint32BE","writeUint32LE","writeUint64BE","writeUint64LE","bitLength","result","mul","int_1","div","DataView","byteOffset","byteLength","getFloat32","getFloat64","setFloat32","setFloat64","core","input","j0","j1","j2","j3","j4","j5","j6","j7","j8","j9","j10","j11","j12","j13","j14","j15","x0","x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13","x14","x15","binary_1","streamXOR","nonce","src","dst","nonceInplaceCounterLength","nc","counterLength","set","block","incrementCounter","wipe_1","counter","carry","ZEROS","nonceLength","tagLength","_key","ChaCha20Poly1305","plaintext","associatedData","authKey","chacha_1","resultLength","_authenticate","subarray","sealed","calculatedTag","constant_time_1","tagOut","ciphertext","h","poly1305_1","update","tag","digest","clean","a","subject","resultIfOne","resultIfZero","saveState","restoreState","cleanSavedState","hash","salt","info","_counter","_hash","_info","okm","hmac_1","_hmac","_buffer","digestLength","_bufpos","HKDF","ctr","reset","finish","_fillBuffer","_finished","_inner","_outer","blockSize","pad","hash_1","_innerKeyedState","_outerKeyedState","HMAC","data","savedState","imul","al","bl","x","isInteger","isFinite","_r","Uint16Array","_h","_pad","_leftover","_fin","t0","t1","t2","t3","t4","t5","t6","t7","Poly1305","m","mpos","bytes","hibit","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","mac","macpos","mask","f","g","_blocks","want","randomBytes","prng","system_1","wipe","ALPHANUMERIC","randomString","charset","charsLen","maxByte","randomByte","bits","constructor","isAvailable","isInstantiated","browserCrypto","self","crypto","msCrypto","getRandomValues","_crypto","min","nodeCrypto","_source","browser_1","node_1","_state","Int32Array","_temp","_bufferLength","_bytesHashed","SHA256","_initState","dataLength","dataPos","hashBlocks","bytesHashed","left","bitLenHi","bitLenLo","padLength","state","bufferLength","K","w","v","d","u","gf","init","r","_9","_121665","car25519","o","sel25519","q","add","sub","t8","t9","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t30","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","square","scalarMult","z","unpack25519","x32","x16","inp","inv25519","pack25519","scalarMultBase","generateKeyPairFromSeed","seed","secretKey","publicKey","mySecretKey","theirPublicKey","rejectZero","zeros","anySignal","signals","controller","globalThis","AbortController","onAbort","abort","signal","removeEventListener","addEventListener","aborted","sink","sinks","indexOf","zinkz","s","y","plural","ms","msAbs","isPlural","str","match","exec","parseFloat","toLowerCase","parse","long","abs","fmtLong","fmtShort","formatArgs","useColors","namespace","humanize","diff","color","lastC","save","namespaces","storage","setItem","removeItem","error","load","getItem","process","DEBUG","window","__nwjs","navigator","userAgent","document","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","RegExp","localStorage","localstorage","destroy","warned","warn","colors","debug","formatters","message","env","createDebug","prevTime","namespacesCache","enabledCache","enableOverride","enabled","curr","Date","prev","coerce","unshift","format","formatter","logFn","selectColor","extend","enumerable","configurable","get","delimiter","newDebug","toNamespace","regexp","substring","default","stack","disable","names","map","skips","enable","forEach","Denque","_head","_tail","_capacity","capacity","_capacityMask","_list","isArray","_fromArray","peekAt","peek","peekFront","peekBack","item","_growArray","pop","head","_shrinkArray","tail","removeOne","k","remove","count","removed","del_count","toArray","clear","temp","arg_len","arguments_index","leng","isEmpty","_copyArray","fullCopy","newArray","list","assign","obj","props","code","TypeError","_","ErrClass","create","event_iterator_1","EventIterator","EventQueue","pullQueue","pushQueue","eventHandlers","isPaused","isStopped","resolution","done","placeholder","highWaterMark","highWater","stop","fail","rejection","catch","then","removeCallback","Symbol","asyncIterator","next","lowWaterMark","lowWater","return","listen","queue","event","freeze","has","hasOwnProperty","Events","EE","context","once","addListener","emitter","listener","_events","_eventsCount","clearEvent","__proto__","eventNames","events","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","removeAllListeners","prefixed","ReflectOwnKeys","R","Reflect","ReflectApply","target","receiver","ownKeys","NumberIsNaN","errorListener","resolver","eventTargetAgnosticAddListener","handler","flags","addErrorHandlerIfEventEmitter","_maxListeners","defaultMaxListeners","checkListener","_getMaxListeners","that","_addListener","prepend","existing","warning","newListener","onceWrapper","fired","wrapFn","_onceWrap","wrapped","unwrap","evlistener","arr","ret","unwrapListeners","arrayClone","copy","wrapListener","arg","RangeError","setMaxListeners","getMaxListeners","doError","er","prependListener","prependOnceListener","position","originalListener","spliceOne","rawListeners","hwm","top","btm","last","FixedFIFO","max","cache","_cache","word","includeBoundaries","v4","v6seg","v6","trim","v46Exact","v4exact","v6exact","ip","exact","root","ipv4Part","ipv4Regexes","fourOctet","threeOctet","twoOctet","longValue","octalRegex","hexRegex","zoneIndex","ipv6Part","ipv6Regexes","deprecatedTransitional","transitional","expandIPv6","lastIndexOf","replacement","replacementCount","colonCount","lastColon","zoneId","substr","ref","results","matchCIDR","first","second","partSize","cidrBits","part","parseIntAuto","padPart","ipaddr","IPv4","octets","octet","SpecialRanges","unspecified","broadcast","multicast","linkLocal","loopback","carrierGradeNat","reserved","kind","other","cidrRange","prefixLengthFromSubnetMask","cidr","zerotable","range","subnetMatch","toByteArray","toIPv4MappedAddress","IPv6","toNormalizedString","broadcastAddressFromCIDR","parseCIDR","ipInterfaceOctets","subnetMaskOctets","subnetMaskFromPrefixLength","isIPv4","parser","isValid","isValidFourPartDecimal","networkAddressFromCIDR","maskLength","parsed","reverse","filledOctetCount","uniqueLocal","ipv4Mapped","rfc6145","rfc6052","teredo","isIPv4MappedAddress","toFixedLengthString","addr","suffix","toIPv4Address","high","low","toRFC5952String","regex","bestMatchIndex","bestMatchLength","isIPv6","native","fromByteArray","e2","address","rangeList","defaultName","rangeName","rangeSubnets","subnet","versions","electron","URLWithLegacySupport","URLSearchParams","defaultBase","relative","URL","url","urlParsed","location","protocolMap","defaultProtocol","protocol","base","host","isReactNative","product","super","pathname","search","auth","username","password","query","startsWith","hostname","href","origin","port","searchParams","createObjectURL","revokeObjectURL","toJSON","userPass","async","entry","thing","func","pushable","sources","output","setTimeout","all","FIFO","onEnd","onNext","ended","bufferNext","bufferError","writev","values","throw","_pushable","sorter","sort","limit","items","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","node","global","COMMON_JS","JS_SHA3_NO_COMMON_JS","AMD","define","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","ArrayBuffer","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","BITS","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","isView","createOutputMethod","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","methods","createKmacOutputMethod","createOutputMethods","method","createMethod","algorithms","bytepad","Kmac","methodNames","algorithm","methodName","newMethodName","blocks","finalized","blockCount","byteCount","outputBlocks","extraBytes","notString","lastByteIndex","right","encodeString","strs","paddingBytes","finalize","hex","arrayBuffer","Uint32Array","c0","c3","c4","c5","c6","c7","c8","c9","b16","b17","b18","b19","b20","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b40","b41","b42","b43","b44","b45","b46","b47","b48","b49","isOptionObject","propertyIsEnumerable","object","writable","defaultMergeOptions","concatArrays","ignoreUndefined","getEnumerableOwnPropertyKeys","symbols","symbol","clone","cloneArray","cloneOptionObject","mergeKeys","merged","config","merge","resultIndex","indices","filter","includes","option","_toConsumableArray","arr2","from","defaultTarget","mutableHandler","mutableTarget","setTarget","setHandler","Proxy","property","_len","getTarget","getHandler","proxy","Netmask","atob","chr","chr0","chrA","chra","ip2long","long2ip","dmax","net","maskLong","error1","bitmask","netLong","hostmask","contains","lastLong","forge","registerAlgorithm","mode","cipher","aes","Algorithm","startEncrypting","iv","_createCipher","decrypt","createEncryptionCipher","startDecrypting","createDecryptionCipher","initialize","encrypt","inBlock","outBlock","_updateBlock","_w","_init","tmp","util","createBuffer","putByte","getInt32","encryptOp","_expandKey","modes","ecb","cbc","cfb","ofb","gcm","sbox","isbox","rcon","mix","imix","xtime","e4","e8","sx","sx2","me","ime","ei","iNk","Nk","m0","m1","m2","m3","wnew","wi","Nr","toUpperCase","createDecipher","createCipher","ByteBuffer","asn1","_checkBufferLength","remaining","available","requested","Class","UNIVERSAL","APPLICATION","CONTEXT_SPECIFIC","PRIVATE","Type","NONE","BOOLEAN","INTEGER","BITSTRING","OCTETSTRING","NULL","OID","ODESC","EXTERNAL","REAL","ENUMERATED","EMBEDDED","UTF8","ROID","SEQUENCE","SET","PRINTABLESTRING","IA5STRING","UTCTIME","GENERALIZEDTIME","BMPSTRING","tagClass","constructed","composed","bitStringContents","original","excludeBitStringContents","equals","obj1","obj2","equal","includeBitStringContents","getBerValueLength","getByte","getInt","_fromDer","depth","longFormBytes","_getValueLength","strict","getBytes","decodeBitStrings","savedRead","savedRemaining","unused","used","tc","ex","getInt16","asn1Options","fromDer","parseAllBytes","toDer","useBitStringContents","putBytes","putBuffer","putInt16","lenBytes","oidToDer","oid","valueBytes","derToOid","utcTimeToDate","utc","date","year","MM","DD","hh","mm","ss","setUTCFullYear","setUTCHours","setTime","generalizedTimeToDate","gentime","YYYY","fff","isUTC","setFullYear","setHours","dateToUtcTime","rval","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","dateToGeneralizedTime","integerToDer","putSignedInt","integer","derToInteger","getSignedInt","validate","capture","errors","optional","captureAsn1","captureBitStringContents","captureBitStringValue","_nonLatinRegex","prettyPrint","level","indentation","indent","IA5String","subvalues","pki","oids","bytesToHex","decodeUtf8","api","_reverseAlphabets","alphabet","maxline","digits","at","_encodeWithByteBuffer","Buffer","getAlgorithm","BlockCipher","_finish","_input","_op","_decrypt","opts","compact","unpad","overflow","afterFinish","transformIV","ints","inc32","from64To32","num","_ints","_inBlock","_outBlock","putInt32","fillWithByte","truncate","_prev","_iv","_partialBlock","_partialOutput","_partialBytes","inputLength","partialBytes","_R","additionalData","_cipherLength","_tagLength","_tag","_hashBlock","_hashSubkey","componentBits","_m","generateHashTable","ivLength","_j0","ghash","_aDataLength","_s","lengths","multiply","z_i","v_i","lsb","tableMultiply","x_i","ah","multiplier","perInt","shft","generateSubHashTable","mid","half","m_i","m_j","des","_keys","pc2bytes0","pc2bytes1","pc2bytes2","pc2bytes3","pc2bytes4","pc2bytes5","pc2bytes6","pc2bytes7","pc2bytes8","pc2bytes9","pc2bytes10","pc2bytes11","pc2bytes12","pc2bytes13","iterations","shifts","lefttmp","righttmp","_createKeys","spfunction1","spfunction2","spfunction3","spfunction4","spfunction5","spfunction6","spfunction7","spfunction8","looping","endloop","loopinc","right1","right2","usePureJavaScript","hmac","_md","_ipadding","_opadding","md","keylen","blockLength","inner","getMac","dbits","jsbn","BigInteger","fromNumber","fromString","nbi","am3","xl","xh","am","appName","DB","DM","DV","FV","F1","F2","rr","vv","BI_RC","int2char","intAt","nbv","fromInt","nbits","Classic","Montgomery","mp","invDigit","mpl","mph","um","mt2","op_and","op_or","op_xor","op_andnot","lbit","cbit","NullExp","nNop","Barrett","q3","ONE","dlShiftTo","mu","divide","convert","compareTo","revert","reduce","divRemTo","mulTo","multiplyTo","sqrTo","squareTo","ZERO","subTo","copyTo","u0","clamp","drShiftTo","fromRadix","mi","sh","lShiftTo","bs","cbs","bm","ds","rShiftTo","pm","pt","ts","nsh","ys","y0","yt","qd","isEven","exp","negate","toRadix","km","modPowInt","multiplyUpperTo","multiplyLowerTo","dAddOffset","lowprimes","lplim","chunkSize","signum","cs","intValue","dMultiply","testBit","bitwiseTo","shiftLeft","isProbablePrime","nextBytes","op","changeBit","addTo","modInt","millerRabin","n1","subtract","getLowestSetBit","shiftRight","random","modPow","byteValue","shortValue","and","or","xor","andNot","not","bitCount","setBit","clearBit","flipBit","remainder","divideAndRemainder","k1","g2","is1","modInverse","ac","gcd","mgf","mgf1","generate","maskLen","_IN","id","_I_","pbe","encryptedPrivateKeyValidator","PBES2AlgorithmsValidator","pkcs12PbeParamsValidator","prfOidToMessageDigest","prfOid","prfAlgorithm","supported","prfAlgorithmToMessageDigest","sha512","encryptPrivateKeyInfo","saltSize","dkLen","encryptionAlgorithm","encryptedData","getBytesSync","countBytes","ivLen","encOid","cipherFn","dk","pkcs5","pbkdf2","hexToBytes","createPbkdf2Params","saltBytes","generatePkcs12Key","decryptPrivateKeyInfo","encryptionOid","getCipher","encryptionParams","encrypted","encryptedPrivateKeyToPem","epki","msg","pem","encryptedPrivateKeyFromPem","headerType","procType","encryptRsaPrivateKey","rsaKey","legacy","wrapRsaPrivateKey","privateKeyToAsn1","opensslDeriveBytes","version","dekInfo","parameters","decryptRsaPrivateKey","rc2","privateKeyFromAsn1","iter","sha1","passBuf","D","Slen","S","Plen","P","I","B","Inew","setAt","getCipherForPBES2","getCipherForPKCS12PBE","supportedOids","kdfOid","kdfSalt","kdfIterationCount","encIv","dIvLen","md5","digests","isNodejs","pbkdf2Sync","hLen","prf","u_c","u_c1","int32ToBytes","xorBytes","outer","setImmediate","foldHeader","header","insertSpace","candidate","insert","ltrim","contentDomain","headers","encode64","rMessage","rHeader","rCRLF","decode64","lines","li","line","nl","vi","pkcs1","rsa_mgf1","encode_rsa_oaep","label","mgf1Md","keyLength","maxLength","lHash","PS","PS_length","seedLength","dbMask","maskedDB","seedMask","maskedSeed","decode_rsa_oaep","em","expectedLength","db","lHashPrime","in_ps","is_0","error_mask","p7","pkcs7","_recipientFromAsn1","recipientInfoValidator","issuer","RDNAttributesAsArray","serialNumber","serial","toHex","encryptedContent","encAlgorithm","parameter","encParameter","content","encKey","_recipientsToAsn1","recipients","distinguishedNameToAsn1","attributes","_signerToAsn1","digestAlgorithm","authenticatedAttributesAsn1","signatureAlgorithm","signature","unauthenticatedAttributes","attrsAsn1","attr","_attributeToAsn1","contentType","messageDigest","signingTime","jan_1_1950","jan_1_2050","timestamp","_fromAsn1","validator","rawCapture","_decryptContent","ciph","messageFromPem","messageFromAsn1","messageToPem","pemObj","toAsn1","contentInfoValidator","envelopedData","createEnvelopedData","createEncryptedData","signedData","createSignedData","fromAsn1","certificates","crls","signers","digestAlgorithmIdentifiers","contentInfo","signerInfos","signedDataValidator","certs","certificateFromAsn1","certificateToAsn1","addSigner","signer","certificate","cert","certificateFromPem","privateKeyFromPem","sha256","sha384","authenticatedAttributes","rsaEncryption","encodeUtf8","detached","detachedContent","mds","ai","_signersToAsn1","addSignerInfos","addDigestAlgorithmIds","verify","addCertificate","addCertificateRevokationList","crl","encryptedDataValidator","envelopedDataValidator","infos","_recipientsFromAsn1","recipientInfos","ec","findRecipient","sAttr","rAttr","recipient","privKey","desCBC","addRecipient","keyLen","ciphFn","p7v","pkcs7asn1","encryptedContentInfoValidator","signerValidator","prime","GCD_30_DELTA","THIRTY","generateProbablePrime","rng","Worker","primeincFindPrimeWithoutWorkers","generateRandom","numWorkers","workers","workLoad","workerScript","estimateCores","cores","workerMessage","found","terminate","postMessage","primeincFindPrimeWithWorkers","primeincFindPrime","mrTests","getMillerRabinTests","millerRabinTests","maxBlockTime","_primeinc","deltaIdx","bits1","plugin","time","reseeds","generated","keyBytes","pools","_reseedSync","messageLength","_seed","needed","collect","seedFileSync","_2powK","seedBytes","formatKey","formatSeed","defaultSeedFile","globalScope","entropy","QuotaExceededError","pool","generateSync","increment","nextTick","seedFile","_reseed","collectInt","registerWorker","worker","pss","saltLength","sLen","salt_","pssobj","modBits","emBits","emLen","mHash","m_","ps","checkLen","jQuery","prng_aes","_prng_aes_output","_prng_aes_buffer","spawnPrng","_ctx","_navBytes","mousemove","clientX","clientY","keypress","charCode","createInstance","piTable","rol","ror","expandKey","effKeyBits","L","T","T1","T8","TM","mixRound","mashRound","_output","getInt16Le","runPlan","plan","putInt16Le","ptr","rsa","privateKeyValidator","rsaPrivateKeyValidator","rsaPublicKeyValidator","publicKeyValidator","digestInfoValidator","emsaPkcs1v15encode","oidBytes","digestInfo","_modPow","pub","dP","dQ","qInv","xp","xq","_encodePkcs1_v1_5","bt","eb","padByte","padNum","numZeros","padBytes","_decodePkcs1_v1_5","ml","_generateKeyPair","getPrime","pBits","qBits","p1","q1","phi","privateKey","setPrivateKey","setPublicKey","_bnToBytes","_getMillerRabinTests","_detectNodeCrypto","_detectSubtleCrypto","subtle","_detectSubtleMsCrypto","_intToUint8Array","yhex","ed","expected","xhex","createKeyPairGenerationState","eInt","pqState","stepKeyPairGenerationState","total","generateKeyPair","modulusLength","publicExponent","publicKeyEncoding","privateKeyEncoding","priv","publicKeyFromPem","generateKey","pair","exportKey","pkcs8","setRsaPublicKey","genOp","oncomplete","exportOp","onerror","keypair","generateKeyPairSync","scheme","schemeOptions","_parseAllDigestBytes","algorithmIdentifier","md2","sha224","setRsaPrivateKey","privateKeyModulus","privateKeyPublicExponent","privateKeyPrivateExponent","privateKeyPrime1","privateKeyPrime2","privateKeyExponent1","privateKeyExponent2","privateKeyCoefficient","privateKeyToRSAPrivateKey","publicKeyFromAsn1","publicKeyOid","rsaPublicKey","publicKeyModulus","publicKeyExponent","publicKeyToAsn1","publicKeyToSubjectPublicKeyInfo","publicKeyToRSAPublicKey","_initialized","_padding","fillString","fullMessageLength","messageLengthSize","messageLength64","int32s","encoding","_update","finalBlock","s2","_k","s0","maj","_states","messageLength128","hlen","t1_hi","t1_lo","t2_hi","t2_lo","s0_hi","s0_lo","s1_hi","ch_hi","maj_hi","maj_lo","a_hi","a_lo","b_hi","b_lo","c_hi","c_lo","d_hi","d_lo","e_hi","e_lo","f_hi","f_lo","g_hi","g_lo","h_hi","h_lo","w2","w7","w15","w16","baseN","_checkBitsParam","ByteStringBuffer","isArrayBuffer","isArrayBufferView","_constructedStringLength","browser","callbacks","stopPropagation","MutationObserver","now","createElement","observe","oldSetImmediate","setAttribute","_optimizeConstructedString","putString","putInt24","putInt24Le","putInt32Le","putInt","getInt24","getInt24Le","getInt32Le","DataBuffer","readOffset","growSize","writeOffset","accommodate","amount","setUint8","view","raw","text","utf16","setInt16","setInt8","setInt32","getInt8","getUint8","s1","s3","_base64","_base64Idx","_base58","chr1","chr2","chr3","enc1","enc2","enc3","enc4","unescape","encodeURIComponent","decodeURIComponent","escape","base58","deflate","inflate","_setStorageObject","_getStorageObject","_setItem","_getItem","_removeItem","empty","prop","_clearItems","_callStorageFunction","idx","clearItems","re","argi","lastIndex","formatNumber","number","decimals","dec_point","thousands_sep","toFixed","formatSize","bytesFromIP","bytesFromIPv4","bytesFromIPv6","blanks","bytesToIP","bytesToIPv4","bytesToIPv6","zeroGroups","zeroMaxGroup","group","hardwareConcurrency","Blob","blobUrl","st","et","sample","samples","avg","overlaps","overlap","_shortNames","x509CertificateValidator","rsassaPssParameterValidator","certificationRequestInfoValidator","certificationRequestValidator","_getAttribute","shortName","rdn","si","valueTagClass","CRIAttributesAsArray","seq","extensionRequest","extensions","certificateExtensionFromAsn1","_readSignatureParameters","fillDefaults","algorithmOid","hashOid","maskGenOid","maskGenHashOid","_createSignatureDigest","signatureOid","_verifySignature","sha1WithRSAEncryption","sha1WithRSASignature","signatureParameters","_dnToAsn1","attrs","_fillMissingFields","attribute","valueConstructed","certificateExtensionToAsn1","_fillMissingExtensionFields","extension","digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly","cA","pathLenConstraint","client","server","email","objsign","sslCA","emailCA","objCA","altNames","altName","comment","ski","generateSubjectKeyIdentifier","subjectKeyIdentifier","keyIdentifier","authorityCertIssuer","subSeq","fullNameGeneralNames","_signatureParametersToAsn1","_CRIAttributesToAsn1","csr","computeHash","certificateToPem","publicKeyToPem","publicKeyToRSAPublicKeyPem","getPublicKeyFingerprint","certificationRequestFromPem","certificationRequestFromAsn1","certificationRequestToPem","certificationRequestToAsn1","createCertificate","siginfo","validity","notBefore","notAfter","getField","sn","addField","setSubject","uniqueId","setIssuer","setExtensions","exts","getExtension","ext","tbsCertificate","getTBSCertificate","child","issued","expectedIssuer","actualIssuer","isIssuer","parent","iattr","sattr","verifySubjectKeyIdentifier","certVersion","certSerialNumber","certSignatureOid","certSignatureParams","certinfoSignatureOid","certinfoSignatureParams","certSignature","certValidity1UTCTime","certValidity2GeneralizedTime","certValidity3UTCTime","certValidity4GeneralizedTime","imd","ibytes","certIssuer","certIssuerUniqueId","smd","sbytes","certSubject","certSubjectUniqueId","certExtensions","certificateExtensionsFromAsn1","subjectPublicKeyInfo","extseq","critical","ev","gn","createCertificationRequest","csrVersion","csrSignatureOid","csrSignatureParams","csrSignature","certificationRequestInfo","certificationRequestInfoSubject","getAttribute","addAttribute","certificationRequestInfoAttributes","setAttributes","getCertificationRequestInfo","cri","_dateToAsn1","tbs","certificateExtensionsToAsn1","dn","createCaStore","caStore","getBySubject","ensureSubjectHasHash","getIssuer","hasCertificate","der1","listAllCertificates","certList","removeCertificate","certificateError","bad_certificate","unsupported_certificate","certificate_revoked","certificate_expired","certificate_unknown","unknown_ca","verifyCertificateChain","chain","validityCheckDate","selfSigned","parents","verified","se","keyUsage","basicConstraints","bcExt","keyUsageExt","vfd","propIsEnumerable","toObject","test1","test2","test3","letter","shouldUseNative","to","Fifo","defer","_waitingConsumers","promise","_consume","nextConsumer","nextChunk","deferred","__importDefault","__esModule","netmask_1","ip_regex_1","is_ip_1","ipaddr_js_1","NETMASK_RANGES","ip_range","ipv6_check","ip_addr","ipv4_check","ipRegex","isIp","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","timeout","run","marker","runClearTimeout","Item","noop","title","argv","binding","cwd","chdir","dir","umask","ReactPropTypesSecret","emptyFunction","emptyFunctionWithReset","resetWarningCache","shim","propName","componentName","propFullName","secret","getShim","isRequired","ReactPropTypes","bigint","bool","any","arrayOf","element","elementType","instanceOf","objectOf","oneOf","oneOfType","shape","checkPropTypes","PropTypes","common","timeType","commonRe","json","nested","google","protobuf","Any","fields","type_url","Duration","seconds","nanos","Timestamp","Empty","Struct","keyType","Value","oneofs","oneof","nullValue","numberValue","stringValue","boolValue","structValue","listValue","NullValue","NULL_VALUE","ListValue","rule","DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue","FieldMask","paths","file","converter","Enum","genValuePartial_fromObject","gen","field","fieldIndex","resolvedType","typeDefault","repeated","fullName","isUnsigned","genValuePartial_toObject","fromObject","mtype","fieldsArray","safeProp","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","valuesById","unsigned","toNumber","arrayDefault","hasKs2","_fieldsArray","types","defaults","basic","packed","rfield","required","missing","wireType","mapKey","genTypePartial","ReflectionObject","className","Namespace","comments","valuesOptions","fromJSON","enm","toJSONOptions","keepComments","Boolean","isString","isReservedId","isReservedName","allow_alias","Field","ruleRe","isObject","defaultValue","Long","extensionField","declaringField","_packed","getOption","setOption","ifNotSet","resolved","lookupTypeOrEnum","proto3_optional","newBuffer","emptyObject","emptyArray","ctor","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","_configure","Type_","build","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","configure","Writer","BufferWriter","Reader","BufferReader","rpc","roots","tokenize","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","_nestedArray","clearCache","addJSON","nestedArray","nestedJson","getEnum","setOptions","onAdd","onRemove","resolveAll","lookup","filterTypes","parentAlreadyChecked","lookupEnum","lookupService","Service_","Enum_","defineProperties","_handleAdd","_handleRemove","setParsedOption","opt","find","newValue","setProperty","newOpt","Root_","fieldNames","addFieldsToParent","oneofName","oneOfGetter","oneOfSetter","keepCase","base10Re","base10NegRe","base16Re","base16NegRe","base8Re","base8NegRe","numberRe","nameRe","typeRefRe","fqTypeRefRe","pkg","imports","weakImports","syntax","token","preferTrailingComment","tn","alternateCommentMode","skip","cmnt","isProto3","applyCase","camelCase","illegal","insideTryCatch","readString","readValue","acceptTypeRef","parseNumber","readRanges","acceptStrings","parseId","acceptNegative","parsePackage","parseImport","whichImports","parseSyntax","parseCommon","parseOption","parseType","parseEnum","service","ifBlock","commentText","parseMethod","parseService","reference","parseField","parseExtension","fnIf","fnElse","trailingLine","valueType","parseInlineOptions","parseMapField","parseOneOf","lcFirst","ucFirst","parseGroup","dummy","parseEnumValue","isCustom","parseOptionValue","objectResult","lastValue","prevValue","simpleValue","LongBits","indexOutOfRange","writeLength","create_array","isBuffer","readLongVarint","readFixed32_end","readFixed64","_slice","uint32","int32","sint32","fixed32","sfixed32","float","double","skipType","BufferReader_","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","files","SYNC","resolvePath","sync","cb","getBundledFileName","altname","queued","weak","readFileSync","isNode","exposeRe","tryHandleExtension","extendedType","sisterField","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","requestCtor","responseCtor","request","endedByRPC","_methodsArray","inherited","methodsArray","rpcService","isReserved","delimRe","stringDoubleRe","stringSingleRe","setCommentRe","setCommentAltRe","setCommentSplitRe","whitespaceRe","unescapeRe","unescapeMap","lastCommentLine","stringDelim","setComment","isLeading","lineEmpty","leading","commentOffset","isDoubleSlashCommentLine","startOffset","endOffset","findEndOfLine","lineText","cursor","repeat","isDoc","isLeadingComment","actual","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","wrapper","originalThis","fork","ldelim","typeName","bake","safePropBackslashRe","safePropQuoteRe","camelCaseRe","decorateRoot","decorateEnumIndex","setProp","zero","zzEncode","zeroHash","toLong","fromHash","toHash","part0","part1","part2","newError","CustomError","captureStackTrace","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","allocUnsafe","seenFirstField","invalid","genVerifyKey","genVerifyValue","oneofProp","Op","State","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","BufferWriter_","writeStringBuffer","writeBytesBuffer","aa","ba","Set","ca","da","ea","fa","ha","ia","ja","ka","acceptsBooleans","attributeName","attributeNamespace","mustUseProperty","propertyName","sanitizeURL","removeEmptyString","oa","pa","qa","ma","na","la","removeAttribute","setAttributeNS","xlinkHref","ra","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","sa","ta","ua","wa","xa","ya","za","Aa","Ba","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","for","E","Ma","Ka","iterator","La","Na","Oa","Pa","prepareStackTrace","construct","Qa","_render","Ra","$$typeof","_context","_payload","Sa","Ta","nodeName","Va","_valueTracker","getValue","setValue","stopTracking","Ua","Wa","checked","Xa","activeElement","Ya","defaultChecked","_wrapperState","initialChecked","Za","initialValue","controlled","$a","ab","bb","ownerDocument","children","Children","fb","selected","defaultSelected","disabled","gb","dangerouslySetInnerHTML","hb","ib","jb","textContent","kb","lb","mb","nb","ob","namespaceURI","innerHTML","valueOf","firstChild","removeChild","appendChild","MSApp","execUnsafeLocalFunction","pb","lastChild","nodeType","nodeValue","qb","animationIterationCount","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","rb","sb","tb","ub","menuitem","area","br","col","embed","hr","img","keygen","link","meta","param","track","wbr","vb","wb","is","xb","srcElement","correspondingUseElement","parentNode","yb","zb","Ab","Bb","Cb","stateNode","Db","Eb","Fb","Gb","Hb","Ib","Jb","Kb","Lb","Mb","Ob","Pb","Qb","Rb","onError","Sb","Tb","Ub","Vb","Wb","Xb","Zb","alternate","$b","memoizedState","dehydrated","cc","sibling","current","bc","dc","fc","gc","hc","ic","jc","kc","lc","mc","Map","oc","pc","qc","rc","blockedOn","domEventName","eventSystemFlags","nativeEvent","targetContainers","sc","delete","pointerId","vc","wc","lanePriority","unstable_runWithPriority","priority","hydrate","containerInfo","xc","yc","zc","Ac","Bc","unstable_scheduleCallback","unstable_NormalPriority","Cc","Dc","Ec","animationend","animationiteration","animationstart","transitionend","Fc","Gc","Hc","animation","transition","Ic","Jc","Kc","Lc","Mc","Nc","Oc","Pc","Qc","unstable_now","F","Rc","Uc","pendingLanes","expiredLanes","suspendedLanes","pingedLanes","Vc","entangledLanes","entanglements","Wc","Xc","Yc","Zc","$c","eventTimes","clz32","bd","cd","dd","unstable_UserBlockingPriority","fd","gd","hd","uc","jd","kd","ld","nd","od","keyCode","pd","rd","_reactName","_targetInst","currentTarget","isDefaultPrevented","defaultPrevented","returnValue","isPropagationStopped","preventDefault","cancelBubble","persist","isPersistent","wd","xd","yd","sd","eventPhase","bubbles","cancelable","timeStamp","isTrusted","td","ud","detail","vd","Ad","screenX","screenY","pageX","pageY","ctrlKey","shiftKey","altKey","metaKey","getModifierState","zd","button","buttons","relatedTarget","fromElement","toElement","movementX","movementY","Bd","Dd","dataTransfer","Fd","Hd","animationName","elapsedTime","pseudoElement","Id","clipboardData","Jd","Ld","Md","Esc","Spacebar","Left","Up","Right","Down","Del","Win","Menu","Apps","Scroll","MozPrintableKey","Nd","Od","Alt","Control","Meta","Shift","Pd","Qd","locale","which","Rd","Td","width","height","pressure","tangentialPressure","tiltX","tiltY","twist","pointerType","isPrimary","Vd","touches","targetTouches","changedTouches","Xd","Yd","deltaX","wheelDeltaX","deltaY","wheelDeltaY","wheelDelta","deltaZ","deltaMode","Zd","$d","ae","be","documentMode","ce","de","fe","ge","he","ie","datetime","month","tel","week","ne","oe","pe","qe","te","ue","ve","we","xe","ye","ze","oninput","Ae","detachEvent","Be","Ce","attachEvent","De","Ee","Fe","He","Ie","Je","Ke","Le","nextSibling","Me","compareDocumentPosition","Ne","HTMLIFrameElement","contentWindow","Oe","contentEditable","Pe","Qe","Re","Se","Te","Ue","selectionStart","selectionEnd","anchorNode","defaultView","getSelection","anchorOffset","focusNode","focusOffset","Ve","We","Xe","Ye","Ze","Yb","instance","G","$e","af","bf","cf","df","passive","Nb","ef","ff","parentWindow","hf","J","Q","je","char","ke","jf","kf","lf","mf","autoFocus","nf","__html","of","pf","qf","rf","sf","previousSibling","tf","vf","wf","xf","yf","zf","Af","Bf","H","Cf","M","N","Df","Ef","__reactInternalMemoizedUnmaskedChildContext","__reactInternalMemoizedMaskedChildContext","Ff","Gf","Hf","If","getChildContext","Jf","__reactInternalMemoizedMergedChildContext","Kf","Lf","Mf","Nf","Of","Pf","unstable_cancelCallback","Qf","unstable_shouldYield","Rf","unstable_requestPaint","Sf","Tf","unstable_getCurrentPriorityLevel","Uf","unstable_ImmediatePriority","Vf","Wf","Xf","unstable_LowPriority","Yf","unstable_IdlePriority","Zf","$f","ag","bg","cg","dg","O","eg","fg","gg","hg","ig","jg","kg","ReactCurrentBatchConfig","lg","mg","ng","og","pg","qg","rg","_currentValue","sg","childLanes","tg","dependencies","firstContext","lanes","ug","vg","observedBits","responders","wg","xg","updateQueue","baseState","firstBaseUpdate","lastBaseUpdate","shared","effects","yg","zg","eventTime","lane","payload","Ag","Bg","Cg","A","C","Dg","Eg","Fg","Component","refs","Gg","Kg","isMounted","_reactInternals","enqueueSetState","Hg","Ig","Jg","enqueueReplaceState","enqueueForceUpdate","Lg","shouldComponentUpdate","isPureReactComponent","Mg","updater","Ng","componentWillReceiveProps","UNSAFE_componentWillReceiveProps","Og","getSnapshotBeforeUpdate","UNSAFE_componentWillMount","componentWillMount","componentDidMount","Pg","Qg","_owner","_stringRef","Rg","Sg","lastEffect","nextEffect","firstEffect","Tg","Ug","Vg","implementation","Wg","Xg","Yg","Zg","$g","bh","ch","dh","eh","tagName","fh","gh","ih","memoizedProps","revealOrder","jh","kh","lh","mh","nh","oh","pendingProps","ph","qh","rh","th","uh","_workInProgressVersionPrimary","vh","ReactCurrentDispatcher","wh","yh","zh","Ah","Bh","Ch","Dh","Eh","Fh","Gh","Hh","baseQueue","Ih","Jh","Kh","lastRenderedReducer","action","eagerReducer","eagerState","lastRenderedState","dispatch","Lh","Mh","_getVersion","mutableReadLanes","Nh","U","useState","getSnapshot","subscribe","useEffect","setSnapshot","Oh","Ph","Qh","Rh","deps","Sh","Th","Uh","Vh","Wh","Xh","Yh","Zh","$h","bi","ci","di","readContext","useCallback","useContext","useImperativeHandle","useLayoutEffect","useMemo","useReducer","useRef","useDebugValue","useDeferredValue","useTransition","useMutableSource","useOpaqueIdentifier","unstable_isNewReconciler","uf","ReactCurrentOwner","fi","gi","ii","ji","ki","baseLanes","ni","oi","pi","UNSAFE_componentWillUpdate","componentWillUpdate","componentDidUpdate","qi","ri","pendingContext","Bi","Di","Ei","retryLane","ti","fallback","unstable_avoidThisFallback","ui","unstable_expectedLoadTime","xi","yi","zi","isBackwards","rendering","renderingStartTime","tailMode","Ai","Fi","Gi","wasMultiple","multiple","onClick","onclick","createElementNS","createTextNode","V","Hi","Ii","W","Ji","Ki","Li","Mi","Ni","Oi","WeakMap","Pi","Qi","Ri","Si","componentDidCatch","Ti","componentStack","Ui","WeakSet","Vi","Wi","Xi","__reactInternalSnapshotBeforeUpdate","Yi","Zi","$i","focus","aj","display","bj","onCommitFiberUnmount","componentWillUnmount","cj","dj","ej","fj","gj","hj","insertBefore","_reactRootContainer","ij","jj","kj","lj","mj","nj","oj","pj","X","Y","qj","rj","sj","tj","uj","vj","wj","ck","Z","xj","yj","zj","Aj","Bj","Cj","Dj","Ej","Fj","Gj","Hj","Ij","Jj","Sc","Kj","Lj","Mj","callbackNode","expirationTimes","callbackPriority","Tc","Nj","Oj","Pj","Qj","Rj","Sj","Tj","finishedWork","finishedLanes","Uj","timeoutHandle","Wj","Xj","pingCache","Yj","Zj","va","ak","bk","rangeCount","focusedElem","selectionRange","ek","createRange","setStart","removeAllRanges","addRange","setEnd","scrollLeft","scrollTop","onCommitFiberRoot","fk","gk","ik","isReactComponent","pendingChildren","jk","mutableSourceEagerHydrationData","kk","lk","mk","nk","ok","qk","hydrationOptions","mutableSources","_internalRoot","rk","tk","hasAttribute","sk","uk","hk","_calculateChangedBits","unstable_observedBits","unmount","querySelectorAll","form","Vj","vk","wk","findFiberByHostInstance","bundleType","rendererPackageName","xk","rendererConfig","overrideHookState","overrideHookStateDeletePath","overrideHookStateRenamePath","overrideProps","overridePropsDeletePath","overridePropsRenamePath","setSuspenseHandler","scheduleUpdate","currentDispatcherRef","findHostInstanceByFiber","findHostInstancesForRefresh","scheduleRefresh","scheduleRoot","setRefreshHandler","getCurrentFiber","__REACT_DEVTOOLS_GLOBAL_HOOK__","yk","isDisabled","supportsFiber","inject","createPortal","findDOMNode","flushSync","unmountComponentAtNode","unstable_batchedUpdates","unstable_createPortal","unstable_renderSubtreeIntoContainer","checkDCE","_createClass","Constructor","protoProps","staticProps","_react","_propTypes2","_interopRequireDefault","_classCallCheck","_possibleConstructorReturn","ReferenceError","Content","_Component","subClass","superClass","setPrototypeOf","_inherits","contentDidMount","contentDidUpdate","only","FrameContextConsumer","FrameContextProvider","useFrame","FrameContext","_react2","doc","win","createContext","Provider","Consumer","Frame","_extends","_reactDom2","_Context","_Content2","_this","setRef","nodeRef","forwardedRef","handleLoad","setState","iframeLoaded","_isMounted","createRef","getDoc","forceUpdate","contentDocument","mountTarget","querySelector","parentView","getMountTarget","srcDoc","initialContent","onLoad","renderFrameContents","forwardRef","_Frame","AsyncMode","ConcurrentMode","ContextConsumer","ContextProvider","Element","Fragment","Lazy","Portal","Profiler","StrictMode","Suspense","isAsyncMode","isConcurrentMode","isContextConsumer","isContextProvider","isElement","isForwardRef","isFragment","isLazy","isPortal","isProfiler","isStrictMode","isSuspense","isValidElementType","typeOf","__self","__source","jsx","jsxs","_status","_result","IsSomeRendererActing","PureComponent","cloneElement","_currentValue2","_threadCount","createFactory","isValidElement","lazy","memo","Receptacle","toMS","_lookup","lastModified","ttl","expires","expire","record","refresh","oldRecord","getTime","Retimer","_started","_rescheduled","_scheduled","_args","_triggered","_timerWrapper","_schedule","_timer","reschedule","illegalRe","controlRe","reservedRe","windowsReservedRe","windowsTrailingRe","sanitize","sanitized","performance","MessageChannel","unstable_forceFrameRate","cancelAnimationFrame","requestAnimationFrame","port2","port1","onmessage","sortIndex","startTime","expirationTime","priorityLevel","unstable_Profiling","unstable_continueExecution","unstable_getFirstCallbackNode","unstable_next","unstable_pauseExecution","delay","unstable_wrapCallback","Nouns","Adjectives","data_1","generator_1","intervals","setDelayedInterval","task","interval","_timeout","_runPeriodically","clearDelayedInterval","retimer","TimeoutController","_ms","getLength","isHighSurrogate","codePoint","isLowSurrogate","segment","charLength","curByteLength","inst","useSyncExternalStore","prevCodePoint","res","MAX_SAFE_INTEGER","oldOffset","INT","encodingLength","N1","N2","N3","N4","N5","N6","N7","N8","N9","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","leafPrototypes","getProto","ns","def","definition","toStringTag","DefaultPubSubTopic","StoreCodecs","_0n","BigInt","_1n","_2n","_3n","_8n","POW_2_256","CURVE","Gx","Gy","beta","weistrass","USE_ENDOMORPHISM","JacobianPoint","Point","points","toInv","nums","scratch","lastMultiplied","acc","inverted","invert","reduceRight","invertBatch","toAffine","toAffineBatch","fromAffine","X1","Y1","Z1","X2","Y2","Z2","Z1Z1","Z2Z2","U1","U2","S1","S2","X3","Y3","Z3","HH","HHH","multiplyUnsafe","scalar","P0","normalizeScalar","k1neg","k2neg","k2","splitScalarEndo","k1p","k2p","precomputeWindow","windows","wNAF","affinePoint","BASE","_WINDOW_SIZE","precomputes","pointPrecomputes","normalizeZ","windowSize","maxNumber","shiftBy","wbits","pr","cached","point","fake","f1p","f2p","invZ","iz1","iz2","iz3","ax","ay","_setWindowSize","isShort","bytesToNumber","isValidFieldElement","_6n","_11n","_22n","_23n","_44n","_88n","pow2","b88","b176","b220","b223","sqrtMod","isYOdd","assertValidity","ensureBytes","fromCompressedHex","fromUncompressedHex","normalizePrivateKey","msgHash","recovery","truncateHash","normalizeSignature","fromHex","numTo32bStr","rinv","u1","u2","multiplyAndAddUnsafe","toRawBytes","isCompressed","toHexX","toRawX","aP","bQ","sum","sliceDER","parseDERInt","Signature","isUint8a","hexToNumber","sBytes","rBytesLeft","parseDERSignature","fromDER","isWithinCurveOrder","hasHighS","HALF","normalizeS","toDERRawBytes","toDERHex","sHex","numberToHexUnpadded","rHex","rLen","toCompactRawBytes","toCompactHex","concatBytes","arrays","every","hexes","padStart","uint8a","numTo32b","hexByte","byte","isSafeInteger","power","modulo","divNearest","POW_2_128","delta","HmacDrbg","fill","utils","hmacSha256","hmacSync","hmacSha256Sync","incr","reseedSync","kmdToSig","kBytes","sig","normalizePublicKey","fromCompact","getPublicKey","fromPrivateKey","isPub","bits2int","bits2octets","z1","z2","int2octets","initSigArgs","extraEntropy","seedArgs","finalizeSig","recSig","canonical","der","recovered","hashed","drbg","reseed","vopts","sinv","web","TAGGED_HASH_PREFIXES","isValidPrivateKey","privateAdd","tweak","privateNegate","pointAddScalar","pointMultiply","hashToPrivateKey","bytesLength","randomPrivateKey","messages","createHash","ckey","importKey","createHmac","sha256Sync","taggedHash","tagP","tagH","taggedHashSync","precompute","ALPHABET","BASE_MAP","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","it3","it4","vch","pbegin","pend","b58","it1","it2","Encoder","baseEncode","Decoder","baseDecode","codePointAt","prefixCodePoint","ComposedDecoder","decoders","Codec","baseX","basex","rfc4648","bitsPerChar","codes","written","SyntaxError","identity","TextDecoder","TextEncoder","base2","base8","base10","base16","base16upper","base32","base32upper","base32pad","base32padupper","base32hex","base32hexupper","base32hexpad","base32hexpadupper","base32z","base36","base36upper","base58btc","base58flickr","base64pad","base64url","base64urlpad","alphabetBytesToChars","alphabetCharsToBytes","base256emoji","byts","byt","encode_1","varint","encodeTo","int","sizeOffset","digestOffset","Digest","multihash","Hasher","sha","textEncoder","textDecoder","CID","asCID","_baseCache","hidden","readonly","toV0","DAG_PB_CODE","SHA_256_CODE","createV0","toV1","createV1","equalBytes","toStringV0","toStringV1","deprecate","IS_CID_DEPRECATION","cidSymbol","toBaseEncodedString","codec","multibaseName","encodeCID","cid","decodeFirst","specs","inspectBytes","prefixSize","multihashSize","multihashBytes","digestBytes","digestSize","multihashCode","initialBytes","parseCIDtoBytes","codeOffset","hashOffset","bases","identityBase","createCodec","ascii","latin1","bytesToUtf8","utf8ToBytes","byteArrays","totalLength","Symmetric","getSubtle","webcrypto","secp","keccak256","sha3","compressPublicKey","_permanentCensorErrors","_censorErrors","LogLevels","_logLevel","_globalLogger","_normalizeError","_checkNormalize","LogLevel","ErrorCode","HEX","Logger","_log","logLevel","throwArgumentError","levels","INFO","WARNING","makeError","UNKNOWN_ERROR","messageDetails","reason","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","condition","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","operation","checkSafeUint53","checkArgumentCount","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","checkAbstract","censorship","permanent","globalLogger","logger","isHexable","toHexString","addSlice","isBytesLike","isHexString","isBytes","arrayify","allowMissingPrefix","hexPad","HexCharacters","hexlify","arrayifyInteger","unarrayifyInteger","_encode","_decodeChildren","childOffset","decoded","_decode","consumed","BUFFER_OVERRUN","lengthLength","boundry","v6segment","functionTimeout","function_","wrappedFunction","isRegexp","flagMap","ignoreCase","multiline","dotAll","sticky","unicode","clonedRegexp","flag","isMatch","cloneRegexp","isIP","isV4","isV6","toBytes","sections","v4Buffer","uint8ArrayToString","getProtocol","proto","row","resolvable","createProtocol","convertToString","ipBuff","ipString","getUint16","bytes2ip","bytes2port","bytes2str","bytes2mh","bytes2onion","bytes2mb","convertToBytes","ip2bytes","port2bytes","uint8ArrayFromString","uint8ArrayConcat","str2bytes","mh2bytes","portBuf","onion2bytes","onion32bytes","mbstr","anybaseDecoder","mb2bytes","setUint16","addrBytes","portBytes","ERR_INVALID_ID","decodeMessage","encodeMessage","lengthDelimited","CODEC_TYPES","KeyType","__KeyTypeValues","PublicKey","PrivateKey","enumeration","findValue","VARINT","enumValue","LENGTH_DELIMITED","_codec","Data","RSA","nativeCrypto","bigIntegerToUintBase64url","base64urlToBigInteger","base64urlToBuffer","aesGcm","deriveParams","rawKey","cryptoKey","deriveKey","errcode","unmarshalPrivateKey","derivePublicFromPrivate","jwKey","kty","convertKey","handle","fkey","jwk2pub","jwk2priv","exporter","ciphers","encryptedKey","RsaPublicKey","marshal","jwk","pbm","uint8ArrayEquals","RsaPrivateKey","_publicKey","genSecret","public","dp","dq","unmarshalRsaPrivateKey","alg","unmarshalRsaPublicKey","fromJwk","_255n","CURVE_ORDER","MAX_256B","SQRT_M1","SQRT_AD_MINUS_ONE","INVSQRT_A_MINUS_D","ONE_MINUS_D_SQ","D_MINUS_ONE_SQ","ExtendedPoint","assertExtPoint","X1Z2","X2Z1","Y1Z2","Y2Z1","T3","T2","isSmallOrder","isTorsionFree","fromRistrettoBytes","legacyRist","toRistrettoBytes","fromRistrettoHash","assertRstPoint","RistrettoPoint","ep","Ns","Ns_D_is_sq","uvRatio","s_","edIsNegative","Nt","W0","W1","W2","W3","bytes255ToNumberLE","R1","calcElligatorRistrettoMap","R2","emsg","numberTo32BytesLE","u1_2","u2_2","invertSqrt","Dx","Dy","invsqrt","D1","D2","zInv","_x","_y","one","two","normed","bytesToNumberLE","y2","isXOdd","getExtendedPublicKey","toX25519","u8","numberTo32BytesBE","pow_2_252_3","_5n","_10n","_20n","_40n","_80n","b80","b160","b240","b250","pow_p_5_8","v3","v7","vx2","root1","root2","useRoot1","useRoot2","noRoot","modlLE","adjustBytes25519","checkPrivateKey","getKeyFromHash","pointBytes","_sha512Sync","prepareVerification","SB","finishVerification","kA","TORSION_SUBGROUP","hashToPrivateScalar","sha512Sync","PRIVATE_KEY_BYTE_LENGTH","hashAndSign","privateKeyRaw","hashAndVerify","concatKeys","Ed25519PublicKey","ensureKey","Ed25519PrivateKey","unmarshalEd25519PrivateKey","privateKeyBytes","publicKeyBytes","unmarshalEd25519PublicKey","validatePublicKey","Secp256k1PublicKey","keysProtobuf","Secp256k1PrivateKey","unmarshalSecp256k1PrivateKey","unmarshalSecp256k1PublicKey","supportedKeys","ed25519","Ed25519","secp256k1","Secp256k1","unsupportedKey","typeToKey","unmarshalPublicKey","keysPBM","marshalPublicKey","importer","isPeerId","baseDecoder","PeerIdImpl","toCID","peerIdFromString","RSAPeerIdImpl","Ed25519PeerIdImpl","Secp256k1PeerIdImpl","peerIdFromPeerId","peerIdFromBytes","peerIdFromCID","peerIdFromKeys","KeypairType","Secp256k1Keypair","_privateKey","privateKeyVerify","publicKeyVerify","hasPrivateKey","ERR_TYPE_NOT_IMPLEMENTED","createKeypair","tuplesToStringTuples","tuples","tup","protoFromTuple","tuplesToBytes","fromBytes","sizeForAddr","bytesToTuples","ParseError","bytesToString","cleanPath","stringTuplesToString","stringToBytes","stringToStringTuples","validateBytes","inspect","DNS_CODES","P2P_CODES","resolvers","Multiaddr","isMultiaddr","toOptions","protoCodes","transport","family","protos","protoNames","stringTuples","encapsulate","decapsulate","addrString","decapsulateCode","getPeerId","tuple","ipfs","peerIdStr","getPath","resolvableProto","errCode","nodeAddress","isThinWaistAddress","some","multiaddr","dbg","ENR","kvs","entries","enr","keypairType","peerId","createPeerIdFromKeypair","createKeypairFromPeerId","createV4","hexSeq","rlpEncodedBytes","RLP","encoded","decodeFromValues","RECORD_PREFIX","nodeId","pubKey","uncompressedPubkey","tcp","udp","ip6","tcp6","udp6","multiaddrs","multiaddrBytes","decodeMultiaddrs","multiaddrsBuf","dataView","encodeMultiaddrs","getLocationMultiaddr","isIpv6","endsWith","ipVal","isUdp","isTcp","protoName","protoVal","ipFamily","ipBytes","protocolBytes","multiaddrFromFields","setLocationMultiaddr","getFullMultiaddr","locationMultiaddr","getFullMultiaddrs","waku2","relay","store","lightPush","decodeWaku2","protocols","encodeWaku2","verifySignature","localeCompare","flat","encodeToValues","WakuMessage","contentTopic","timestampDeprecated","findBufAndOffset","bufs","bufEnd","isUint8ArrayList","Uint8ArrayList","appendAll","append","prependAll","consume","trunc","beginInclusive","endExclusive","_subList","sublist","bufStart","sliceStartInBuf","sliceEndsInBuf","littleEndian","getBigInt64","setBigInt64","getUint32","setUint32","getBigUint64","setBigUint64","accessor","TWO_32","toBigInt","access","negative","defaultEncoder","lengthBuf","encodeLength","lengthEncoder","single","ReadMode","defaultDecoder","LENGTH","lengthDecoder","maxLengthLength","maxDataLength","dataLengthLength","onLength","DATA","onData","fromReader","varByteSource","splitLimit","calculateSize","getNext","objectMode","readableLength","rawPipe","fns","isIterable","isDuplex","duplexPipelineFn","duplex","stream","sourceWrap","pipe","rest","selectRandomPeer","peers","getPeersForProtocol","libp2p","peerStore","peer","kdf","outputLength","willBeResult","counters","countersSecret","willBeHashResult","hashResult","_hashResult","derive","privateKeyA","publicKeyB","px","privateA","publicB","publicKeyTo","ephemPrivateKey","sharedPx","encryptionKey","cipherText","ivCipherText","macKey","hmacSha256Sign","ephemPublicKey","cipherTextLength","cipherAndIv","msgMac","hmacSha256Verify","clearEncode","messagePayload","sigPrivKey","envelope","fieldSize","computeSizeOfPayloadSizeField","addPayloadSizeField","rawSize","paddingSize","expectedSize","findIndex","validateDataIntegrity","bytesSignature","recoveryId","clearDecode","sizeOfPayloadSizeField","getSizeOfPayloadSizeField","payloadSize","payloadSizeBytes","getPayloadSize","payloadStart","isSigned","isMessageSigned","getSignature","getHash","messageHash","_signature","fromSignature","ecRecoverPubKey","decryptAsymmetric","ecies","encryptSymmetric","clearText","symmetric","decryptSymmetric","ivStart","OneMillion","DecryptionMethod","_signaturePublicKey","encPublicKey","symKey","enc","version_1","decryptionParams","protoBuf","decodeProto","signaturePublicKey","allResults","contentTopics","Asymmetric","isDefined","dec","decodedResults","payloadAsUtf8","rnds8","uuid","REGEX","byteToHex","rnds","FilterRequest","MessagePush","FilterRPC","ContentFilter","topic","contentFilters","requestId","FilterCodec","WakuFilter","subscriptions","decryptionKeys","pubSubTopic","onRequest","pubsubTopic","createRequest","getPeer","newStream","lp","addCallback","unsubscribe","streamData","pushMessages","unsubscribeRequest","connections","connectionManager","getConnections","randomPeer","addDecryptionKey","deleteDecryptionKey","PushRequest","PushResponse","PushRPC","isSuccess","LightPushCodec","WakuLightPush","RelayCodecs","Index","PagingInfo","HistoryQuery","HistoryResponse","HistoryRPC","receivedTime","senderTime","Direction","__DirectionValues","pageSize","direction","pagingInfo","endTime","HistoryError","__HistoryErrorValues","PageDirection","storeCodec","historyRpc","protoV2Beta3","protoV2Beta4","pageDirection","BACKWARD","FORWARD","directionToProto","WakuStore","timeFilter","queryOpts","historyRpcQuery","createQuery","remoteAddr","reply","ERROR_NONE_UNSPECIFIED","pageMessages","protoMsg","responsePageSize","queryPageSize","codecs","Protocols","Waku","pubsub","pingKeepAliveTimers","relayKeepAliveTimers","pingKeepAlive","relayKeepAlive","startKeepAlive","remotePeer","stopKeepAlive","_protocols","Relay","Store","LightPush","Filter","dialProtocol","addPeerToAddressBook","addresses","addressBook","stopAllKeepAlives","isStarted","getLocalMultiaddrWithID","localMultiaddr","getMultiaddrs","pingPeriodSecs","relayPeriodSecs","setInterval","ping","wakuMsg","clearInterval","timer","Envelope","payloadType","RecordEnvelope","marshaled","Protobuf","domain","signData","formatSignaturePayload","envelopeData","createFromProtobuf","domainUint8Array","uint8arraysFromString","domainLength","payloadTypeLength","payloadLength","PeerRecord","AddressInfo","ENVELOPE_PAYLOAD_TYPE_PEER_RECORD","DOMAIN","CODEC","seqNumber","arrayEquals","trace","peerRecord","topologySymbol","TopologyImpl","onConnect","onDisconnect","registrar","disconnect","EventTarget","_EventEmitter_listeners","__classPrivateFieldGet","dispatchEvent","CustomEventPolyfill","Event","CustomEvent","MessageCache","gossip","historyCapacity","msgIdToStrFn","history","msgs","put","messageId","validated","msgIdStr","originatingPeers","iwantCounts","observeDuplicate","msgId","fromPeerIdStr","getWithIWantCount","getGossipIDs","topics","msgIdsByTopic","msgIds","RPC","cjs","FloodsubID","GossipsubIDv10","GossipsubIDv11","GossipsubMaxIHaveLength","createGossipRpc","control","graft","prune","ihave","iwant","shuffle","messageIdToString","StrictSign","StrictNoSign","SignaturePolicy","PublishConfigType","MessageAcceptance","RejectReason","ValidateError","MessageStatus","rejectReasonFromAcceptance","acceptance","Ignore","Reject","ERR_INVALID_PEER_SCORE_PARAMS","defaultPeerScoreParams","topicScoreCap","appSpecificScore","appSpecificWeight","IPColocationFactorWeight","IPColocationFactorThreshold","IPColocationFactorWhitelist","behaviourPenaltyWeight","behaviourPenaltyThreshold","behaviourPenaltyDecay","decayInterval","decayToZero","retainScore","defaultTopicScoreParams","topicWeight","timeInMeshWeight","timeInMeshQuantum","timeInMeshCap","firstMessageDeliveriesWeight","firstMessageDeliveriesDecay","firstMessageDeliveriesCap","meshMessageDeliveriesWeight","meshMessageDeliveriesDecay","meshMessageDeliveriesCap","meshMessageDeliveriesThreshold","meshMessageDeliveriesWindow","meshMessageDeliveriesActivation","meshFailurePenaltyWeight","meshFailurePenaltyDecay","invalidMessageDeliveriesWeight","invalidMessageDeliveriesDecay","createPeerScoreParams","topicScoreParams","createTopicScoreParams","validateTopicScoreParams","defaultPeerScoreThresholds","gossipThreshold","publishThreshold","graylistThreshold","acceptPXThreshold","opportunisticGraftThreshold","createPeerScoreThresholds","computeScore","pstats","peerIPs","score","tstats","topicParams","topicScore","inMesh","meshTime","p2","firstMessageDeliveries","meshMessageDeliveriesActive","meshMessageDeliveries","deficit","meshFailurePenalty","invalidMessageDeliveries","p5","ips","peersInIP","numPeersInIP","surplus","behaviourPenalty","excess","DeliveryRecordStatus","MessageDeliveries","records","ensureRecord","drec","unknown","firstSeen","isStartable","isInitializable","Components","started","setPeerId","addressManager","setAddressManager","setPeerStore","upgrader","setUpgrader","metrics","setMetrics","setRegistrar","setConnectionManager","transportManager","setTransportManager","connectionGater","setConnectionGater","contentRouting","setContentRouting","peerRouting","setPeerRouting","datastore","setDatastore","connectionProtector","setConnectionProtector","dht","setDHT","setPubSub","startable","beforeStart","afterStart","beforeStop","afterStop","getMetrics","getAddressManager","getPeerStore","getUpgrader","getRegistrar","getConnectionManager","getTransportManager","getConnectionGater","getContentRouting","getPeerRouting","getDatastore","getConnectionProtector","getDHT","getPubSub","PeerScore","validatePeerScoreParams","scoreCacheValidityMs","components","peerStats","_backgroundInterval","background","deliveryRecords","refreshScores","updateIPs","dumpPeerScoreStats","fromEntries","stats","connected","tparams","graftTime","removeIPs","scoreCache","scoreFnCalls","inc","cacheEntry","cacheUntil","scoreFnRuns","scoreCachedDelta","addPenalty","penalty","penaltyLabel","onScorePenalty","addPeer","getIPs","setIPs","removePeer","threshold","getPtopicStats","validateMessage","deliverMessage","markFirstMessageDelivery","markDuplicateMessageDelivery","rejectInvalidMessage","markInvalidMessageDelivery","rejectMessage","duplicateMessage","cap","validatedTime","deliveryDelayMs","isLateDelivery","onDuplicateMsgDelivery","newIPs","oldIPs","addNewIPs","xip","removeOldIPs","topicStats","IWantTracer","gossipsubIWantFollowupMs","requestMsByMsgExpire","promises","requestMsByMsgSize","requestMsByMsg","addPromise","expireByPeer","iwantPromiseStarted","getBrokenPromises","brokenPromises","iwantPromiseBroken","trackMessage","iwantPromiseResolved","iwantPromiseResolvedPeers","maxMs","requestMs","iwantPromiseDeliveryTime","SimpleTimeCache","validityMs","validUntilMs","MessageSource","InclusionReason","ChurnReason","ScorePenalty","IHaveIgnoreReason","ScoreThreshold","hashName","keySize","dek","forgePbkdf2","forgeUtil","SignPrefix","msgIdFnStrictSign","sequenceNumber","seqno","seqnoBytes","msgIdFnStrictNoSign","computeScoreWeights","topicStrToLabel","byTopic","topicLabel","topicScores","p1w","p2w","p3w","p3bw","p4w","capF","ws","p5w","p6w","p7w","removeItemsFromSet","superSet","ineed","cond","subset","AbortError","abortableSource","getIterator","nextAbortHandler","abortHandler","abortMessage","abortCode","race","isKnownAborter","onReturnError","returnOnAbort","abortable","abortableSink","abortableDuplex","OutboundStream","rawStream","errCallback","closeController","maxBufferSize","stat","close","InboundStream","GossipStatusCode","GossipSub","constants","stopped","heartbeatDuration","startTimer","heartbeat","finally","heartbeatTimeout","msToNextHeartbeat","heartbeatInterval","hearbeatStartMs","heartbeatSkipped","runHeartbeat","fallbackToFloodsub","floodPublish","doPX","directPeers","Dlo","Dhi","Dscore","Dout","Dlazy","fanoutTTL","minute","mcacheLength","mcacheGossip","seenTTL","prunePeers","pruneBackoff","graftFloodThreshold","opportunisticGraftPeers","opportunisticGraftTicks","directConnectTicks","scoreParams","scoreThresholds","globalSignaturePolicy","multicodecs","debugName","direct","seenCache","publishedMessageIds","msgIdFn","fastMsgIdFn","fastMsgIdCache","mcache","messageCache","dataTransform","metricsRegister","metricsTopicStrToLabel","maxMeshMessageDeliveriesWindowMs","topicParam","register","protocolsEnabled","gauge","help","labelNames","topicSubscriptionStatus","topicPeersCount","meshPeerCounts","meshPeerInclusionEvents","meshPeerChurnEvents","peersPerProtocol","histogram","buckets","asyncValidationResult","asyncValidationMcacheHit","rpcRecvBytes","rpcRecvCount","rpcRecvSubscription","rpcRecvMessage","rpcRecvControl","rpcRecvIHave","rpcRecvIWant","rpcRecvGraft","rpcRecvPrune","rpcRecvNotAccepted","rpcSentBytes","rpcSentCount","rpcSentSubscription","rpcSentMessage","rpcSentControl","rpcSentIHave","rpcSentIWant","rpcSentGraft","rpcSentPrune","msgPublishCount","msgPublishPeers","msgPublishPeersByGroup","msgPublishBytes","msgForwardCount","msgForwardPeers","msgReceivedPreValidation","msgReceivedStatus","msgReceivedInvalid","duplicateMsgDeliveryDelay","maxMeshMessageDeliveriesWindowSec","duplicateMsgLateDelivery","peersByScoreThreshold","avgMinMax","scoreWeights","scorePerMesh","scoringPenalties","ihaveRcvIgnored","ihaveRcvMsgids","ihaveRcvNotSeenMsgids","iwantRcvMsgids","iwantRcvDonthaveMsgids","gossipPromiseExpireSec","cacheSize","mcacheSize","toTopic","topicStr","onJoin","onLeave","onAddToMesh","onRemoveFromMesh","onReportValidationMcacheHit","hit","onReportValidation","onIhaveRcv","idonthave","onIwantRcv","iwantByTopic","iwantDonthave","onForwardMsg","tosendCount","onPublishMsg","tosendGroupCount","dataLen","peerGroup","floodsub","mesh","fanout","onMsgRecvPreValidation","onMsgRecvResult","onMsgRecvInvalid","onRpcRecv","rpcBytes","onRpcSent","registerScores","scores","graylist","publish","registerScoreWeights","sw","wsTopic","registerScorePerMesh","scoreByPeer","peersPerTopicLabel","peersInMesh","meshScores","addCollect","onScrapeMetrics","gossipTracer","maxInboundStreams","maxOutboundStreams","getPeers","publishConfig","signaturePolicy","author","getPublishConfigFromPeerId","outboundInflightQueue","connection","createOutboundStream","addrs","multicodec","onIncomingStream","topology","onPeerConnected","onPeerDisconnected","registrarTopologyIds","directPeerInitial","connect","unregister","outboundStream","streamsOutbound","inboundStream","streamsInbound","heartbeatTimer","cancel","fanoutLastpub","peerhave","iasked","backoff","outbound","createInboundStream","maxOutboundBufferSize","floodsubPeers","sendSubscriptions","priorInboundStream","pipePeerReadStream","acceptFromWhitelist","getMeshPeers","peersInTopic","getSubscribers","getTopics","awaitRpcHandler","handleReceivedRpc","acceptFrom","subOpt","handleReceivedSubscription","handleReceivedMessagePromise","handleReceivedMessage","awaitRpcMessageHandler","handleControlMessage","topicSet","rpcMsg","validationResult","validateReceivedMessage","asyncValidation","emitSelf","propagationSource","forwardMessage","fastMsgIdStr","msgIdCached","valid","fromPeerId","rpcMsgPreSign","validateToRawMessage","inboundTransform","topicValidator","topicValidators","getScore","toPeer","sendRpc","controlMsg","handleIHave","handleIWant","handleGraft","handlePrune","messagesAccepted","acceptUntil","topicID","messageIDs","iask","iwantList","floodCutoff","addBackoff","makePrune","doAddBackoff","pxConnect","applyIwantPenalties","clearBackoff","heartbeatTicks","toconnect","peerID","signedPeerRecord","eid","consumePeerRecord","openConnection","getTopologies","wasSubscribed","leave","toAdd","fanoutPeers","fanoutCount","getRandomGossipPeers","sendGraft","meshPeers","sendPrune","selectPeersToForward","excludePeers","tosend","selectPeersToPublish","newFanoutPeers","rawMsg","transformedData","outboundTransform","originalData","buildRawMessage","willSendToSelf","allowPublishToZeroPeers","reportMessageValidationResult","rejectReason","ctrl","piggybackControl","piggybackGossip","outRpc","tograft","toprune","noPX","pruning","emitGossip","peersToGossipByTopic","gossipIDsByTopic","peersToGossip","doEmitGossip","candidateToGossip","factor","peerMessageIDs","pushGossip","flush","controlIHaveMsgs","xid","getRawEnvelope","directConnect","candidateMeshPeers","shuffledPeers","peerStreams","prunePeer","graftPeer","newMeshPeers","removeFirstNItemsFromSet","peersArray","rotate","peersList","medianIndex","medianScore","lastpb","topicPeers","candidateFanoutPeers","sendGraftPrune","backoffSize","peerIdStrs","swPeer","swPeerTopic","swTopic","computeAllPeersScoreWeights","WakuRelay","observers","addObserver","deleteObserver","callbackFn","handleCommand","waku","setNick","replaceAll","parseInput","command","nick","peerMultiaddr","strConnections","streams","reactPropsRegex","memoize","StyleSheet","_insertTag","before","tags","insertionPoint","container","isSpeedy","speedy","_proto","nodes","createStyleElement","sheet","styleSheets","ownerNode","sheetForTag","insertRule","cssRules","pattern","indexof","charat","begin","strlen","sizeof","column","character","characters","caret","dealloc","delimit","whitespace","escaping","commenter","identifier","MS","MOZ","WEBKIT","COMMENT","RULESET","DECLARATION","KEYFRAMES","serialize","compile","rules","rulesets","pseudo","declarations","atrule","previous","variable","scanning","ampersand","declaration","ruleset","post","identifierWithPointTracking","getRules","toRules","fixedElements","compat","isImplicitRule","parentRules","removeLabel","defaultStylisPlugins","combine","ssrStyles","stylisPlugins","_insert","inserted","nodesToHydrate","attrib","currentSheet","finalizingPlugins","serializer","collection","middleware","selector","serialized","shouldCache","styles","registered","getRegisteredStyles","registeredStyles","classNames","rawClassName","registerStyles","isStringTag","insertStyles","msGridRow","msGridRowSpan","msGridColumn","msGridColumnSpan","WebkitLineClamp","hyphenateRegex","animationRegex","isCustomProperty","isProcessableValue","processStyleName","styleName","processStyleValue","unitless","handleInterpolation","mergedProps","interpolation","__emotion_styles","anim","interpolated","_i","createStringFromObject","previousCursor","labelPattern","serializeStyles","stringMode","strings","identifierName","hashString","useInsertionEffect","React","useInsertionEffectAlwaysWithSyncFallback","EmotionCacheContext","HTMLElement","createCache","withEmotionCache","ThemeContext","useTheme","createCacheWithTheme","weakMemoize","outerTheme","theme","getTheme","ThemeProvider","typePropName","createEmotionProps","newProps","Insertion","_ref","Emotion","cssProp","css","WrappedComponent","testOmitPropsOnStringTag","isPropValid","testOmitPropsOnComponent","getDefaultShouldForwardProp","composeShouldForwardProps","isReal","shouldForwardProp","optionsShouldForwardProp","__emotion_forwardProp","createStyled","targetClassName","__emotion_real","baseTag","__emotion_base","defaultShouldForwardProp","shouldUseAs","Styled","FinalTag","as","classInterpolations","finalShouldForwardProp","withComponent","nextTag","nextOptions","newStyled","hasOwn","mapValues","mapper","predicate","forOwn","mapKeys$1","objA","objB","memoizeOne","memoized","cacheKey","called","omitByIndexed","pickByIndexed","trailingWhiteSpace","trimEnd","argsLength","createElementArgArray","classnames","cls","serializedArr","ClassNames","cx","_len2","_key2","ele","_objectWithoutPropertiesLoose","excluded","sourceKeys","_setPrototypeOf","_inheritsLoose","forceReflow","UNMOUNTED","EXITED","ENTERING","ENTERED","EXITING","Transition","_React$Component","initialStatus","appear","isMounting","enter","appearStatus","in","unmountOnExit","mountOnEnter","nextCallback","prevState","updateStatus","prevProps","nextStatus","cancelNextCallback","getTimeouts","exit","mounting","ReactDOM","performEnter","performExit","_this2","appearing","_ref2","maybeNode","maybeAppearing","timeouts","enterTimeout","safeSetState","onEntered","onEnter","onEntering","onTransitionEnd","_this3","onExit","onExiting","onExited","nextState","setNextCallback","_this4","active","doesNotHaveTimeoutOrListener","addEndListener","_ref3","maybeNextCallback","_this$props","childProps","TransitionGroupContext","replaceClassName","origClass","classToRemove","removeClass","classes","classList","baseVal","CSSTransition","appliedClasses","_this$resolveArgument","resolveArguments","removeClasses","addClass","_this$resolveArgument2","_this$resolveArgument3","getClassNames","isStringClassNames","baseClassName","activeClassName","doneClassName","phase","hasClass","_addClass","_this$appliedClasses$","_assertThisInitialized","getChildMapping","mapFn","getProp","getNextChildMapping","nextProps","prevChildMapping","nextChildMapping","getValueForKey","nextKeysPending","pendingKeys","prevKey","childMapping","nextKey","pendingNextKey","mergeChildMappings","hasPrev","hasNext","prevChild","isLeaving","TransitionGroup","handleExited","contextValue","firstRender","mounted","currentChildMapping","childFactory","$f0a04ccd8dbdd83b$export$e5c5a5f917a5871c","$12uGp$react","$bdb11010cef70236$var$idsUpdaterMap","$bdb11010cef70236$export$cd8c9cb68f842629","idA","idB","setIdA","setIdB","$ff5963eb1fccf552$export$e08e3b67e392101e","$3ef42575df84b30b$export$9d1611c77c2fe928","$12uGp$clsx","$65484d02dcb7eb3e$var$DOMPropNames","$65484d02dcb7eb3e$var$labelablePropNames","$65484d02dcb7eb3e$var$propRe","$7215afc6de606d6b$export$de79e2c695e052f3","$7215afc6de606d6b$var$supportsPreventScrollCached","preventScroll","$7215afc6de606d6b$var$supportsPreventScroll","scrollableElements","rootScrollingElement","scrollingElement","offsetHeight","scrollHeight","offsetWidth","scrollWidth","$7215afc6de606d6b$var$getScrollableElements","$7215afc6de606d6b$var$restoreScrollPosition","$bbed8b41f857bcc0$var$transitionsByElement","$bbed8b41f857bcc0$var$transitionCallbacks","$bbed8b41f857bcc0$var$setupGlobalEvents","transitions","$bbed8b41f857bcc0$export$24490316f764c430","$e7801be82b4b2a53$export$4debdb1a3f0fa79e","visualViewport","$c87311424ea30a05$var$testPlatform","platform","$c87311424ea30a05$export$9ac100e40613ea10","$c87311424ea30a05$export$fedb369cb70207f1","maxTouchPoints","$14c0b72509d70225$var$state","$14c0b72509d70225$var$savedUserSelect","$14c0b72509d70225$var$modifiedElementMap","$14c0b72509d70225$export$16a4697467175487","$bx7SL$isIOS","webkitUserSelect","SVGElement","userSelect","$14c0b72509d70225$export$b0d6fa1ab32e3295","$bx7SL$runAfterTransition","targetOldUserSelect","$8a9cb279dc87e130$export$60278871457622de","mozInputSource","$8a9cb279dc87e130$export$905e7fc544a71f36","$8a9cb279dc87e130$export$715c682d09d639cc","onBlur","stateRef","$bx7SL$useRef","isFocused","observer","$bx7SL$useLayoutEffect","$bx7SL$useCallback","e1","HTMLButtonElement","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","onBlurHandler","_current","FocusEvent","attributeFilter","$ae1eeba8b9eafd08$export$5165eccb35aaadb5","$bx7SL$react","$f6c31cce2adf654f$export$45712eceda6fad21","onPress","onPress1","onPressChange","onPressChange1","onPressStart","onPressStart1","onPressEnd","onPressEnd1","onPressUp","onPressUp1","isDisabled1","isPressed","isPressedProp","preventFocusOnPress","shouldCancelOnPointerExit","allowTextSelectionOnPress","domProps","$bx7SL$useContext","contextProps","$bx7SL$mergeProps","$bx7SL$useSyncRef","$f6c31cce2adf654f$var$usePressResponderContext","propsRef","setPressed","$bx7SL$useState","ignoreEmulatedMouseEvents","ignoreClickAfterPress","didFirePressStart","activePointerId","isOverTarget","addGlobalListener","removeAllGlobalListeners","globalListeners","$12uGp$useRef","$12uGp$useCallback","eventTarget","removeGlobalListener","$12uGp$useEffect","$bx7SL$useGlobalListeners","pressProps1","$bx7SL$useMemo","triggerPressStart","originalEvent","triggerPressEnd","wasPressed","triggerPressUp","$f6c31cce2adf654f$var$createEvent","pressProps","onKeyDown","$f6c31cce2adf654f$var$isValidKeyboardEvent","$f6c31cce2adf654f$var$shouldPreventDefaultKeyboard","onKeyUp","$f6c31cce2adf654f$var$isHTMLAnchorLink","$bx7SL$focusWithoutScrolling","click","PointerEvent","onPointerDown","$f6c31cce2adf654f$var$shouldPreventDefault","onPointerMove","onPointerUp","onPointerCancel","onMouseDown","$f6c31cce2adf654f$var$isOverTarget","onDragStart","onMouseUp","onMouseEnter","onMouseLeave","onTouchStart","touch","$f6c31cce2adf654f$var$getTouchFromEvent","onScroll","onTouchMove","$f6c31cce2adf654f$var$getTouchById","onTouchEnd","onTouchCancel","$bx7SL$useEffect","role","$f6c31cce2adf654f$var$isValidInputKey","isContentEditable","rect","getBoundingClientRect","pointRect","offsetX","radiusX","offsetY","radiusY","bottom","$f6c31cce2adf654f$var$getPointClientRect","$f6c31cce2adf654f$var$areRectanglesOverlapping","draggable","$f6c31cce2adf654f$var$nonTextInputTypes","$507fabe10e71c6fb$var$currentModality","$507fabe10e71c6fb$var$changeHandlers","$507fabe10e71c6fb$var$hasSetupGlobalListeners","$507fabe10e71c6fb$var$hasEventBeforeFocus","$507fabe10e71c6fb$var$hasBlurredWindowRecently","$507fabe10e71c6fb$var$FOCUS_VISIBLE_INPUT_KEYS","Tab","Escape","$507fabe10e71c6fb$var$triggerChangeHandlers","modality","$507fabe10e71c6fb$var$handleKeyboardEvent","$bx7SL$isMac","$507fabe10e71c6fb$var$isValidKey","$507fabe10e71c6fb$var$handlePointerEvent","$507fabe10e71c6fb$var$handleClickEvent","$507fabe10e71c6fb$var$handleFocusEvent","$507fabe10e71c6fb$var$handleWindowBlur","$507fabe10e71c6fb$var$setupGlobalFocusEvents","$507fabe10e71c6fb$export$b9b3dfddab17db27","$507fabe10e71c6fb$export$ffd9e5021c1fb2d6","isTextInput","isFocusVisibleState","setFocusVisible","$507fabe10e71c6fb$export$ec71b4b83ac08ec3","isFocusVisible","KeyboardEvent","$507fabe10e71c6fb$var$isKeyboardFocusEvent","$93925083ecbb358c$export$48d1ea6320830260","shouldStopPropagation","continuePropagation","updateRef","libRef","userRef","prevUserRef","useLatest","useIsomorphicLayoutEffect","__assign","singleColorRegex","transform","alpha","createUnitType","unit","percent","clampRgbUnit","isRgba","red","isHsla","hue","splitColorValues","terms","valuesArray","getValueFromFunctionString","rgbUnit","isColorString","colorType","rgba","_a","green","blue","_b","alpha$1","rgbaTemplate","curryRange","cv","clamp$1","springForce","alterDisplacement","constant","displacement","springModifiedDisplacement","sqrt","rangeSize","supportsPassiveEvents","isBrowser","arePassiveEventsSupported","Context","_getPrototypeOf","_isNativeReflectConstruct","sham","_construct","Parent","_wrapNativeSuper","Wrapper","PolishedError","_Error","colorToInt","convertToInt","hslToRgb","saturation","lightness","huePrime","chroma","secondComponent","lightnessModification","namedColorMap","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","hexRgbaRegex","reducedHexRegex","reducedRgbaHexRegex","rgbRegex","rgbaRegex","hslRegex","hslaRegex","parseToRgb","normalizedColor","normalizedColorName","nameToHex","_alpha","rgbMatched","rgbaMatched","hslMatched","rgbColorString","hslRgbMatched","hslaMatched","_rgbColorString","_hslRgbMatched","parseToHsl","rgbToHsl","reduceHexValue","numberToHex","colorToHex","convertToHex","hslToHex","hsl","hsla","rgb","firstValue","secondValue","thirdValue","fourthValue","rgbValue","toColorString","isRgb","isHsl","curried","combined","curry","guard","lowerBoundary","upperBoundary","darken","hslColor","curriedDarken","$6a99195332edec8b$export$80f3e147d781571c","lastFocusedElement","$6nfFC$runAfterTransition","$6nfFC$focusWithoutScrolling","$9bf71ea28793e738$var$focusableElements","$9bf71ea28793e738$var$isElementInScope","scope","$9bf71ea28793e738$var$Tree","fastMap","getTreeNode","addTreeNode","scopeRef","nodeToRestore","$9bf71ea28793e738$var$TreeNode","addChild","removeTreeNode","traverse","newTree","contain","$e6afbd83fe6ebbd2$var$FocusableContext","$6nfFC$react","$e6afbd83fe6ebbd2$export$4c014de7c8940b4c","domRef","focusProps","onFocus","onFocusProp","onBlurProp","onFocusChange","onSyntheticFocus","$6nfFC$useFocus","keyboardProps","$6nfFC$useKeyboard","interactions","$6nfFC$mergeProps","$6nfFC$useContext","$6nfFC$useSyncRef","otherProps","$e6afbd83fe6ebbd2$var$useFocusableContext","interactionProps","autoFocusRef","$6nfFC$useRef","$6nfFC$useEffect","focusableProps","tabIndex","excludeFromTabOrder","$701a24aa0da5b062$export$ea18c227d4417cc3","additionalProps","allowFocusWhenDisabled","deprecatedOnClick","rel","$cE0pI$usePress","$cE0pI$useFocusable","buttonProps","$cE0pI$mergeProps","labelable","propNames","filteredProps","$cE0pI$filterDOMProps","HIDDEN_TEXTAREA_STYLE","visibility","forceHiddenStyles","hiddenTextarea","SIZING_STYLE","isIE","currentStyle","TextareaAutosize","cacheMeasurements","maxRows","minRows","_ref$onChange","onChange","_ref$onHeightChange","onHeightChange","isControlled","useComposedRef","heightRef","measurementsCacheRef","resizeTextarea","nodeSizingData","getComputedStyle","sizingStyle","boxSizing","borderRightWidth","borderLeftWidth","paddingRight","paddingLeft","paddingBottom","paddingTop","borderSize","borderBottomWidth","borderTopWidth","getSizingData","_calculateNodeHeight","sizingData","getHeight","rowHeight","minHeight","maxHeight","calculateNodeHeight","latestListener","useWindowResizeListener","MapShim","getIndex","class_1","__entries__","global$1","requestAnimationFrame$1","transitionKeys","mutationObserverSupported","ResizeObserverController","connected_","mutationEventsAdded_","mutationsObserver_","observers_","onTransitionEnd_","leadingCall","trailingCall","lastCallTime","resolvePending","timeoutCallback","throttle","connect_","removeObserver","disconnect_","updateObservers_","activeObservers","gatherActive","hasActive","broadcastActive","childList","characterData","subtree","getInstance","instance_","defineConfigurable","getWindowOf","emptyRect","createRectInit","toFloat","getBordersSize","positions","getHTMLElementContentRect","clientWidth","clientHeight","paddings","positions_1","getPaddings","horizPad","vertPad","isDocumentElement","vertScrollbar","horizScrollbar","isSVGGraphicsElement","SVGGraphicsElement","getBBox","getContentRect","bbox","getSVGContentRect","ResizeObservation","broadcastWidth","broadcastHeight","contentRect_","isActive","broadcastRect","ResizeObserverEntry","rectInit","contentRect","Constr","DOMRectReadOnly","createReadOnlyRect","ResizeObserverSPI","callbackCtx","activeObservations_","observations_","callback_","controller_","callbackCtx_","observations","unobserve","clearActive","observation","ResizeObserver","grouped","groupKey","objs","iteratee","keyResolver","memoizeWith","insertable","trailingId","lastCall","invoke","_React$useState","ChatList","renderedMessages","authorName","formatDisplayDate","sentTimestamp","MessageList","containScrollInSubtree","AlwaysScrollToBottom","toLocaleString","day","hour","hour12","elementRef","scrollIntoView","WakuContext","useWaku","MessageInput","inputText","setInputText","activeButton","setActiveButton","sendMessage","TextComposer","onButtonClick","align","Fill","TextInput","Fit","SendButton","ChatMessage","timestampNumber","Room","storePeers","setStorePeers","filterPeers","setFilterPeers","lightPushPeers","setLightPushPeers","flexDirection","TitleBar","leftIcons","commandHandler","messageSender","chatMessage","fromUtf8String","ChatContentTopic","handleMessage","messageToSend","chatMsg","getPseudoRandomSubset","wantedNumber","randInt","Fleet","getPredefinedBootstrapNodes","fleet","Prod","fleets","Test","TimeoutError","getDOMException","errorMessage","DOMException","getAbortedReason","pTimeout","milliseconds","cancelablePromise","POSITIVE_INFINITY","customTimers","timeoutError","normalizeEmitter","pEvent","arrayPromise","rejectionEvents","multiArgs","resolveImmediately","onItem","arguments_","rejectHandler","rejectionEvent","pEventMultiple","waitForRemotePeer","timeoutMs","waitForGossipSubPeerInMesh","waitForConnectedPeer","awaitTimeout","rejectOnTimeout","_resolve","PeerDiscoveryStaticPeers","DefaultInterval","maxPeers","peerMas","peerInfo","_startTimer","_returnPeers","peerData","stablelib","hashSHA256","getHKDF","ikm","expand","generateX25519KeyPair","x25519","generateX25519KeyPairFromSeed","generateX25519SharedKey","chaCha20Poly1305Encrypt","ad","seal","chaCha20Poly1305Decrypt","pDefer","handshake","sourcePromise","sinkErr","sinkPromise","pbStream","shake","lpReader","readLP","readPB","writeLP","writePB","piped","NOISE_MSG_MAX_LENGTH_BYTES","DUMP_SESSION_KEYS","uint16BEEncode","uint16BEDecode","UnexpectedPeerError","InvalidCryptoExchangeError","InvalidCryptoTransmissionError","NoiseHandshakePayload","identityKey","identitySig","NoiseHandshakePayloadProto","getPayload","localPeer","staticPublicKey","earlyData","signedPayload","signPayload","getHandshakePayload","earlyDataPayload","libp2pPublicKey","createHandshakePayload","getPeerIdFromPayload","decodePayload","verifySignedPayload","noiseStaticKey","payloadPeerId","generatedPayload","isValidPublicKey","pk","keyLogger","logLocalEphemeralKeys","logRemoteEphemeralKey","Nonce","getUint64","assertValue","XX","encryptWithAd","decryptWithAd","hasKey","isEmptyKey","createEmptyKey","encryptAndHash","mixHash","encryptedMessage","decryptAndHash","derivedU8","mixKey","tempK","initializeKey","initializeSymmetric","protocolName","protocolNameBytes","hashProtocolName","tempk1","tempk2","cs1","cs2","writeMessageRegular","readMessageRegular","initializeInitiator","prologue","rs","psk","initializeResponder","writeMessageA","hs","writeMessageB","spk","writeMessageC","messageBuffer","readMessageA","readMessageB","valid1","valid2","readMessageC","initSession","initiator","session","ephemeral","resultingBuffer","recvMessage","resultingPlaintext","resultingValid","XXHandshake","isInitiator","staticKeypair","xx","remoteEarlyData","encode0","receivedMessageBuffer","decode0","decode1","decodedPayload","setRemoteEarlyData","encode1","encode2","decode2","getCS","getRemoteStaticKey","encryption","Noise","staticNoiseKey","prologueBytes","staticKeys","wrappedConnection","performHandshake","conn","createSecureConnection","performXXHandshake","propose","exchange","secure","user","duplexPair","network","encryptStream","decrypted","decryptStream","MessageTypes","MessageTypeNames","InitiatorMessageTypes","NEW_STREAM","MESSAGE","MESSAGE_INITIATOR","CLOSE","CLOSE_INITIATOR","RESET","RESET_INITIATOR","ReceiverMessageTypes","MESSAGE_RECEIVER","CLOSE_RECEIVER","RESET_RECEIVER","POOL_SIZE","_pool","_poolOffset","_headerInfo","_decodeHeader","readVarInt","REST","MAX_MSG_SIZE","ERR_STREAM_RESET","TrackedMap","system","metric","updateComponentMetric","deleted","trackedMap","printMessage","MplexStreamMuxer","_streamId","_streams","initiators","receivers","_createSink","_createSource","registry","_newStream","_newReceiverStream","maxMsgSize","abortController","resetController","Types","externalId","streamName","endErr","sourceEnded","sinkEnded","sinkSunk","timeline","onSinkEnd","closeRead","closeWrite","uint8ArrayList","toSend","metadata","createStream","onStreamEnd","abortSignals","maxSize","checkSize","restrictSize","_handleIncoming","pushableV","maxStreamBufferSize","Mplex","createStreamMuxer","socket","cleanup","handleOpen","handleErr","closeOnEnd","ready","wasClean","connectedSource","binaryType","isConnected","connError","cleanUp","cont","onOpen","onMessage","remoteAddress","remotePort","CONNECTING","OPEN","http","https","wsurl","WebSocket","websocket","reduceValue","Reducers","ip4","assumeHttp","explicitPort","tcpUri","dnsaddr","dns4","dns6","p2p","wss","isEnvWithDom","isElectron","detectElectron","isElectronMain","isElectronRenderer","release","isWebWorker","importScripts","WorkerGlobalScope","socketToMaConn","maConn","DNS4","DNS6","DNSADDR","DNS","IP","TCP","UDP","UTP","QUIC","WebSockets","WebSocketsSecure","HTTP","HTTPS","WebRTCStar","WebRTCDirect","Reliable","_P2P","_Circuit","CircuitRecursive","Circuit","makeMatchesFunction","partialMatch","matches","pnames","testMa","mafmt","_connect","upgradeOutbound","cOpts","errorPromise","errfn","rawSocket","toUri","createListener","filters","sortAll","iterable","pathSepS","pathSepB","pathSep","Key","_buf","uint8Array","nanoid","less","list1","list2","withNamespaces","baseNamespace","namespaceType","namespaceValue","isAncestorOf","isDecendantOf","isTopLevel","MemoryDatastore","batch","puts","dels","commit","drain","putMany","deleteMany","it","_all","orders","take","queryKeys","_allKeys","storeAddresses","uniquePeers","seen","requirePeers","DefaultPeerRouting","routers","refreshManagerInit","refreshManager","_findClosestPeersTask","timeoutId","bootDelay","getClosestPeers","router","findPeer","NOT_FOUND","CompoundContentRouting","findProviders","provide","NOT_STARTED_YET","nVals","gotValues","idStr","peerIdFromMultiaddr","defaultAddressFilter","DefaultAddressManager","announce","observed","announceFilter","getListenAddrs","getAnnounceAddrs","getObservedAddrs","addObservedAddr","getAddresses","getAddrs","addrSet","VisibilityChangeEmitter","visibilityChange","_initializeVisibilityVarNames","_addVisibilityChangeListener","mozHidden","msHidden","webkitHidden","_handleVisibilityChange","isVisible","visible","LatencyMonitor","latencyCheckIntervalMs","dataEmitIntervalMs","asyncTestFn","latencyRandomPercentage","latencyCheckMultiply","latencyCheckSubtract","hrtime","getDeltaMS","latencyData","initLatencyData","visibilityChangeEmitter","pageInFocus","_startTimers","_emitSummary","_stopTimers","checkLatencyID","checkLatency","emitIntervalID","unref","summary","getSummary","latency","minMs","avgMs","totalMs","lengthMs","randomness","localData","deltaOffset","deltaMS","NEGATIVE_INFINITY","CLOSING","CLOSED","DialRequest","dialAction","dialer","tokens","getTokens","tokenHolder","dialAbortControllers","completedDials","releaseToken","isPrivate","isIpPrivate","publicAddressesFirst","isAPrivate","isBPrivate","isCertified","METRICS","METRICS_COMPONENT","Dialer","addressSorter","maxAddrsToDial","dialTimeout","maxDialsPerPeer","maxParallelDials","pendingDials","pendingDialTargets","dial","pendingTarget","denyDialPeer","dialTarget","_createCancellableDialTarget","pendingDial","_createPendingDial","cancellablePromise","_createDialTarget","knownAddrs","denyDialMultiaddr","supportedAddrs","transportForMultiaddr","dialRequest","timeoutController","resolvedMultiaddrs","_resolveRecord","nm","newM","mapIterable","PeerMap","PeerSet","PeerList","peerIds","defaultOptions","maxConnections","minConnections","maxData","maxSentData","maxReceivedData","maxEventLoopDelay","pollInterval","autoDialInterval","movingAverageInterval","METRICS_SYSTEM","DefaultConnectionManager","mergeOptions","_checkMetrics","latencyMonitor","startupReconnectTimeout","inbound","conns","allStreams","counts","_onLatencyMeasure","keepAlivePeers","getTags","connectOnStartupController","_close","tasks","connectionList","movingAverages","getGlobal","getMovingAverages","received","dataReceived","movingAverage","_checkMaxLimit","sent","dataSent","_onConnect","storedConns","keyBook","numConnections","toPrune","storedConn","existingConnections","peerConnections","trackedConnection","getAll","STATUS","_maybePruneConnections","peerValues","sortedConnections","peerAValue","peerBValue","toClose","AutoDialler","running","_autoDial","autoDialTimeout","allPeers","CircuitRelay","Status","__StatusValues","__TypeValues","Peer","srcPeer","dstPeer","streamToMaConnection","mapSource","RELAY_CODEC","writeResponse","streamHandler","validateAddrs","HOP","HOP_DST_MULTIADDR_INVALID","STOP_DST_MULTIADDR_INVALID","HOP_SRC_MULTIADDR_INVALID","STOP_SRC_MULTIADDR_INVALID","StreamHandler","handleHop","hopRequest","circuit","hopEnabled","CircuitPB","destinationPeer","destinationConnections","hopActive","stopRequest","destinationStream","sourceStream","_onProtocol","hop","virtualConnection","canHop","handleCanHop","handleStop","localAddr","upgradeInbound","relayAddr","destinationAddr","relayId","destinationId","errMsg","relayPeer","disconnectOnFailure","relayConnection","Errors","listeningAddrs","relayPeerStr","relayPeerId","relayConn","relayedAddr","namespaceToCid","HOP_METADATA_KEY","HOP_METADATA_VALUE","RELAY_RENDEZVOUS_NS","AutoRelay","maxListeners","listenRelays","_onProtocolChange","_onPeerDisconnected","supportsHop","metadataBook","_addListenRelay","_removeListenRelay","remoteAddrs","_listenOnAvailableHopRelays","peersToIgnore","knownHopsToDial","_tryToListenOnRelay","provider","autoRelay","_advertiseService","advertise","privates","CMS","keychain","plain","findKeyByName","getPrivateKey","getFullYear","serverAuth","clientAuth","codeSigning","emailProtection","timeStamping","certificateForKey","cmsData","cms","keyId","asyncCompare","findAsync","findKeyById","missingKeys","infoPrefix","NIST","iterationCount","validateKeyName","randomDelay","DsName","DsInfoName","KeyChain","pass","dsname","keyInfo","kid","export","listKeys","oldName","newName","oldDsname","newDsname","oldInfoName","newInfoName","oldPass","newPass","oldDek","newDek","keyAsPEM","DefaultMovingAverage","timespan","variance","deviation","forecast","previousTime","createMovingAverage","DefaultStats","frequencyLastTime","frequencyAccumulators","computeThrottleMaxQueueSize","computeThrottleTimeout","movingAverageIntervals","initialCounters","_resetComputeTimeout","_nextTimeout","urgency","_applyOp","_updateFrequency","latestTime","timeDiff","_updateFrequencyFor","timeDiffMS","hz","directionToEvent","DefaultMetrics","statsInit","globalStats","protocolStats","oldPeers","LRU","maxOldPeersRetention","_onMessage","systems","getComponentMetrics","systemMetrics","componentMetrics","calculate","forPeer","idString","getProtocols","forProtocol","updatePlaceholder","placeholderString","placeholderStats","peerIdString","existingStats","mergedStats","trackStream","each","pReflect","isFulfilled","isRejected","_classPrivateFieldInitSpec","privateMap","privateCollection","_classExtractFieldDescriptor","_classPrivateFieldSet","_classPrivateFieldGet","_defineProperty","Node","Queue","enqueue","dequeue","pLimit","concurrency","activeCount","generator","pendingCount","clearQueue","pSettle","DefaultTransportManager","transports","faultTolerance","FaultTolerance","FATAL_ALL","getTransports","couldNotListen","isListening","NO_FATAL","PROTOCOL_ID","NewLine","writeAll","buffers","select","shakeStream","multistream","ConnectionImpl","getStreams","_getStreams","_closing","addStream","removeStream","DefaultRegistrar","topologies","_onDisconnect","protoBook","protocolList","peerProtocols","oldProtocols","added","findOutgoingStreamLimit","countStreams","streamCount","DefaultUpgrader","connectionEncryption","encrypter","muxers","muxer","inboundUpgradeTimeout","encryptedConn","upgradedConn","muxerFactory","cryptoProtocol","setPeer","proxyPeer","abortableStream","denyInboundConnection","mutableProxy","protectedConn","protector","protect","_encryptInbound","denyInboundEncryptedConnection","multiplexed","_multiplexInbound","denyInboundUpgradedConnection","_createConnection","remotePeerId","denyOutboundConnection","toB58String","_encryptOutbound","denyOutboundEncryptedConnection","_multiplexOutbound","denyOutboundUpgradedConnection","muxedStream","mss","incomingLimit","findIncomingStreamLimit","_onStream","outgoingLimit","_timeline","upgraded","errConnectionNotMultiplexed","multiplexer","secureInbound","secureOutbound","Identify","protocolVersion","agentVersion","listenAddrs","observedAddr","AGENT_VERSION","IdentifyService","identifyProtocolStr","protocolPrefix","identifyPushProtocolStr","identify","pushToPeerStore","_handleIdentify","_handlePush","maxPushIncomingStreams","maxPushOutgoingStreams","unhandle","pushes","maxIdentifyMessageSize","_identify","cleanObservedAddr","getCleanMultiaddr","openAndCertify","peerRecordEnvelope","FetchRequest","FetchResponse","StatusCode","__StatusCodeValues","FetchService","lookupFunctions","OK","ERROR","errmsg","_getLookupFunction","registerLookupFunction","unregisterLookupFunction","PingService","isLoopback","DEFAULT_TTL","highPort","NatManager","externalAddress","localAddress","description","keepAlive","gateway","_start","_getClient","publicIp","externalIp","isPrivateIp","publicPort","localPort","fromNodeAddress","upnpNat","PeerRecordUpdater","DHTPeerRouting","closer","EVENT_NAME","allowAll","PeerStoreAddressBook","addressFilter","lock","writeLock","updatedPeer","storedEnvelope","storedRecord","filterMultiaddrs","patchOrCreate","oldMultiaddrs","readLock","hasPeer","mergeOrCreate","PeerStoreKeyBook","updatedKey","uint8arrayEquals","oldPublicKey","PeerStoreMetadataBook","oldMetadata","existingValue","patch","PeerStoreProtoBook","protocolSet","Address","Metadata","_PriorityQueue_queue","PriorityQueue","comparator","step","lowerBound","_PQueue_instances","_PQueue_carryoverConcurrencyCount","_PQueue_isIntervalIgnored","_PQueue_intervalCount","_PQueue_intervalCap","_PQueue_interval","_PQueue_intervalEnd","_PQueue_intervalId","_PQueue_timeoutId","_PQueue_queue","_PQueue_queueClass","_PQueue_pendingCount","_PQueue_concurrency","_PQueue_isPaused","_PQueue_throwOnTimeout","_PQueue_doesIntervalAllowAnother_get","_PQueue_doesConcurrentAllowAnother_get","_PQueue_next","_PQueue_emitEvents","_PQueue_onResumeInterval","_PQueue_isIntervalPaused_get","_PQueue_tryToStartAnother","_PQueue_initializeIntervalIfNeeded","_PQueue_onInterval","_PQueue_processQueue","_PQueue_onEvent","__classPrivateFieldSet","PQueue","_c","_d","carryoverConcurrencyCount","intervalCap","autoStart","queueClass","throwOnTimeout","newConcurrency","functions","pause","sizeBy","canInitializeInterval","job","WORKER_REQUEST_READ_LOCK","WORKER_RELEASE_READ_LOCK","MASTER_GRANT_READ_LOCK","WORKER_REQUEST_WRITE_LOCK","WORKER_RELEASE_WRITE_LOCK","MASTER_GRANT_WRITE_LOCK","observable","handleWorkerLockRequest","masterEvent","releaseType","grantType","requestEvent","MessageEvent","releaseEventListener","releaseEvent","makeWorkerLockRequest","responseEvent","singleProcess","mutexes","createReleaseable","createMortice","isWorker","impl","masterQueue","readQueue","localReadQueue","readPromise","onIdle","createMutex","NAMESPACE_COMMON","PersistentStore","mortice","_peerIdToDatastoreKey","b32key","PeerPB","addressSet","_patch","_merge","addrStr","base32Str","Tags","Tag","expiry","PersistentPeerStore","providedValue","unexpiredTags","DHTContentRouting","providers","AutoDialer","globalFetch","globalHeaders","Headers","Request","Response","buildResource","serverResolver","recordType","resource","req","nativeFetch","accept","getCacheKey","maxCache","_TXTcache","_servers","_request","_abortControllers","getServers","_getShuffledServers","newServers","setServers","servers","rrType","resolve4","resolve6","resolveTxt","Answer","TTL","dnsaddrCode","DefaultConfig","noAnnounce","autoDial","Resolver","nat","PeerIdProto","createFromPrivKey","marshalPrivateKey","DummyDHT","wan","DHT_DISABLED","lan","DummyPubSub","PUBSUB_DISABLED","Libp2pNode","initializables","filterMultiaddrForPeer","services","configureComponent","streamMuxers","keychainOpts","generateOptions","identifyService","peerRouters","onDiscoveryPeer","contentRouters","fetchService","pingService","autoDialer","peerDiscovery","servce","importPeer","peerSet","closeConnections","peerKey","createLibp2pNode","createEd25519PeerId","resultingOptions","ERR_TRANSPORTS_REQUIRED","CONN_ENCRYPTION_REQUIRED","LIBP2P_FORCE_PNET","ERR_PROTECTOR_REQUIRED","validateConfig","defaultLibp2p","wakuRelay","createLibp2p","filterAll","themes","AuthorName","fontSize","margin","MessageText","MessageGroup","App","dispatchMessages","reduceMessages","setWaku","persistedNick","historicalMessagesRetrieved","setHistoricalMessagesRetrieved","setter","selectFleetEnv","wakuStore","wakuLightPush","wakuFilter","initWaku","_unsubscribe","setArchivedMessages","wakuMessages","queryHistory","retrieveStoreMessages","retrieveMessages","commandMessages","newMessages","getElementById"],"sourceRoot":""} \ No newline at end of file diff --git a/web-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs b/web-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs new file mode 100644 index 0000000..6e40160 --- /dev/null +++ b/web-chat/static/media/rpc.93e8f6196bd2c425bf03.cjs @@ -0,0 +1 @@ +"use strict";!function(e,t){"function"===typeof define&&define.amd?define(["protobufjs/minimal"],t):"function"===typeof require&&"object"===typeof module&&module&&module.exports&&(module.exports=t(require("protobufjs/minimal")))}(0,(function(e){var t=e.Reader,r=e.Writer,o=e.util,n=e.roots.default||(e.roots.default={});return n.RPC=function(){function s(e){if(this.subscriptions=[],this.messages=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:s.subscriptions&&s.subscriptions.length||(s.subscriptions=[]),s.subscriptions.push(n.RPC.SubOpts.decode(e,e.uint32()));break;case 2:s.messages&&s.messages.length||(s.messages=[]),s.messages.push(n.RPC.Message.decode(e,e.uint32()));break;case 3:s.control=n.RPC.ControlMessage.decode(e,e.uint32());break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC)return e;var t=new n.RPC;if(e.subscriptions){if(!Array.isArray(e.subscriptions))throw TypeError(".RPC.subscriptions: array expected");t.subscriptions=[];for(var r=0;r>>3){case 1:s.subscribe=e.bool();break;case 2:s.topic=e.string();break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.SubOpts)return e;var t=new n.RPC.SubOpts;return null!=e.subscribe&&(t.subscribe=Boolean(e.subscribe)),null!=e.topic&&(t.topic=String(e.topic)),t},s.toObject=function(e,t){t||(t={});var r={};return null!=e.subscribe&&e.hasOwnProperty("subscribe")&&(r.subscribe=e.subscribe,t.oneofs&&(r._subscribe="subscribe")),null!=e.topic&&e.hasOwnProperty("topic")&&(r.topic=e.topic,t.oneofs&&(r._topic="topic")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s.Message=function(){function s(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:a.from=e.bytes();break;case 2:a.data=e.bytes();break;case 3:a.seqno=e.bytes();break;case 4:a.topic=e.string();break;case 5:a.signature=e.bytes();break;case 6:a.key=e.bytes();break;default:e.skipType(7&i)}}if(!a.hasOwnProperty("topic"))throw o.ProtocolError("missing required 'topic'",{instance:a});return a},s.fromObject=function(e){if(e instanceof n.RPC.Message)return e;var t=new n.RPC.Message;return null!=e.from&&("string"===typeof e.from?o.base64.decode(e.from,t.from=o.newBuffer(o.base64.length(e.from)),0):e.from.length&&(t.from=e.from)),null!=e.data&&("string"===typeof e.data?o.base64.decode(e.data,t.data=o.newBuffer(o.base64.length(e.data)),0):e.data.length&&(t.data=e.data)),null!=e.seqno&&("string"===typeof e.seqno?o.base64.decode(e.seqno,t.seqno=o.newBuffer(o.base64.length(e.seqno)),0):e.seqno.length&&(t.seqno=e.seqno)),null!=e.topic&&(t.topic=String(e.topic)),null!=e.signature&&("string"===typeof e.signature?o.base64.decode(e.signature,t.signature=o.newBuffer(o.base64.length(e.signature)),0):e.signature.length&&(t.signature=e.signature)),null!=e.key&&("string"===typeof e.key?o.base64.decode(e.key,t.key=o.newBuffer(o.base64.length(e.key)),0):e.key.length&&(t.key=e.key)),t},s.toObject=function(e,t){t||(t={});var r={};return t.defaults&&(r.topic=""),null!=e.from&&e.hasOwnProperty("from")&&(r.from=t.bytes===String?o.base64.encode(e.from,0,e.from.length):t.bytes===Array?Array.prototype.slice.call(e.from):e.from,t.oneofs&&(r._from="from")),null!=e.data&&e.hasOwnProperty("data")&&(r.data=t.bytes===String?o.base64.encode(e.data,0,e.data.length):t.bytes===Array?Array.prototype.slice.call(e.data):e.data,t.oneofs&&(r._data="data")),null!=e.seqno&&e.hasOwnProperty("seqno")&&(r.seqno=t.bytes===String?o.base64.encode(e.seqno,0,e.seqno.length):t.bytes===Array?Array.prototype.slice.call(e.seqno):e.seqno,t.oneofs&&(r._seqno="seqno")),null!=e.topic&&e.hasOwnProperty("topic")&&(r.topic=e.topic),null!=e.signature&&e.hasOwnProperty("signature")&&(r.signature=t.bytes===String?o.base64.encode(e.signature,0,e.signature.length):t.bytes===Array?Array.prototype.slice.call(e.signature):e.signature,t.oneofs&&(r._signature="signature")),null!=e.key&&e.hasOwnProperty("key")&&(r.key=t.bytes===String?o.base64.encode(e.key,0,e.key.length):t.bytes===Array?Array.prototype.slice.call(e.key):e.key,t.oneofs&&(r._key="key")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s.ControlMessage=function(){function s(e){if(this.ihave=[],this.iwant=[],this.graft=[],this.prune=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:s.ihave&&s.ihave.length||(s.ihave=[]),s.ihave.push(n.RPC.ControlIHave.decode(e,e.uint32()));break;case 2:s.iwant&&s.iwant.length||(s.iwant=[]),s.iwant.push(n.RPC.ControlIWant.decode(e,e.uint32()));break;case 3:s.graft&&s.graft.length||(s.graft=[]),s.graft.push(n.RPC.ControlGraft.decode(e,e.uint32()));break;case 4:s.prune&&s.prune.length||(s.prune=[]),s.prune.push(n.RPC.ControlPrune.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlMessage)return e;var t=new n.RPC.ControlMessage;if(e.ihave){if(!Array.isArray(e.ihave))throw TypeError(".RPC.ControlMessage.ihave: array expected");t.ihave=[];for(var r=0;r>>3){case 1:s.topicID=e.string();break;case 2:s.messageIDs&&s.messageIDs.length||(s.messageIDs=[]),s.messageIDs.push(e.bytes());break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlIHave)return e;var t=new n.RPC.ControlIHave;if(null!=e.topicID&&(t.topicID=String(e.topicID)),e.messageIDs){if(!Array.isArray(e.messageIDs))throw TypeError(".RPC.ControlIHave.messageIDs: array expected");t.messageIDs=[];for(var r=0;r>>3===1)s.messageIDs&&s.messageIDs.length||(s.messageIDs=[]),s.messageIDs.push(e.bytes());else e.skipType(7&a)}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlIWant)return e;var t=new n.RPC.ControlIWant;if(e.messageIDs){if(!Array.isArray(e.messageIDs))throw TypeError(".RPC.ControlIWant.messageIDs: array expected");t.messageIDs=[];for(var r=0;r>>3===1)s.topicID=e.string();else e.skipType(7&a)}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlGraft)return e;var t=new n.RPC.ControlGraft;return null!=e.topicID&&(t.topicID=String(e.topicID)),t},s.toObject=function(e,t){t||(t={});var r={};return null!=e.topicID&&e.hasOwnProperty("topicID")&&(r.topicID=e.topicID,t.oneofs&&(r._topicID="topicID")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s.ControlPrune=function(){function s(e){if(this.peers=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:s.topicID=e.string();break;case 2:s.peers&&s.peers.length||(s.peers=[]),s.peers.push(n.RPC.PeerInfo.decode(e,e.uint32()));break;case 3:s.backoff=e.uint64();break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.ControlPrune)return e;var t=new n.RPC.ControlPrune;if(null!=e.topicID&&(t.topicID=String(e.topicID)),e.peers){if(!Array.isArray(e.peers))throw TypeError(".RPC.ControlPrune.peers: array expected");t.peers=[];for(var r=0;r>>0,e.backoff.high>>>0).toNumber(!0))),t},s.toObject=function(e,t){t||(t={});var r={};if((t.arrays||t.defaults)&&(r.peers=[]),null!=e.topicID&&e.hasOwnProperty("topicID")&&(r.topicID=e.topicID,t.oneofs&&(r._topicID="topicID")),e.peers&&e.peers.length){r.peers=[];for(var s=0;s>>0,e.backoff.high>>>0).toNumber(!0):e.backoff,t.oneofs&&(r._backoff="backoff")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s.PeerInfo=function(){function s(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:s.peerID=e.bytes();break;case 2:s.signedPeerRecord=e.bytes();break;default:e.skipType(7&a)}}return s},s.fromObject=function(e){if(e instanceof n.RPC.PeerInfo)return e;var t=new n.RPC.PeerInfo;return null!=e.peerID&&("string"===typeof e.peerID?o.base64.decode(e.peerID,t.peerID=o.newBuffer(o.base64.length(e.peerID)),0):e.peerID.length&&(t.peerID=e.peerID)),null!=e.signedPeerRecord&&("string"===typeof e.signedPeerRecord?o.base64.decode(e.signedPeerRecord,t.signedPeerRecord=o.newBuffer(o.base64.length(e.signedPeerRecord)),0):e.signedPeerRecord.length&&(t.signedPeerRecord=e.signedPeerRecord)),t},s.toObject=function(e,t){t||(t={});var r={};return null!=e.peerID&&e.hasOwnProperty("peerID")&&(r.peerID=t.bytes===String?o.base64.encode(e.peerID,0,e.peerID.length):t.bytes===Array?Array.prototype.slice.call(e.peerID):e.peerID,t.oneofs&&(r._peerID="peerID")),null!=e.signedPeerRecord&&e.hasOwnProperty("signedPeerRecord")&&(r.signedPeerRecord=t.bytes===String?o.base64.encode(e.signedPeerRecord,0,e.signedPeerRecord.length):t.bytes===Array?Array.prototype.slice.call(e.signedPeerRecord):e.signedPeerRecord,t.oneofs&&(r._signedPeerRecord="signedPeerRecord")),r},s.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},s}(),s}(),n})); \ No newline at end of file