diff --git a/dist/LICENSE b/dist/LICENSE index 0a26fa9..a5039df 100644 --- a/dist/LICENSE +++ b/dist/LICENSE @@ -100,47 +100,6 @@ MIT SOFTWARE -@js-joda/core -BSD-3-Clause -BSD License - -For js-joda software - -Copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - -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 js-joda 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. - - - -@tediousjs/connection-string -MIT - @vercel/ncc MIT Copyright 2018 ZEIT, Inc. @@ -406,6 +365,32 @@ Apache-2.0 limitations under the License. +ajv +MIT +The MIT License (MIT) + +Copyright (c) 2015-2017 Evgeny Poberezkin + +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. + + + ansi-regex MIT The MIT License (MIT) @@ -496,6 +481,32 @@ Permission to use, copy, modify, and/or distribute this software for any purpose 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. +asn1 +MIT +Copyright (c) 2011 Mark Cavage, All rights reserved. + +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 + + +assert-plus +MIT + async MIT Copyright (c) 2010-2018 Caolan McMahon @@ -544,6 +555,87 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +aws-sign2 +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: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +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 + +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 + +aws4 +MIT +Copyright 2013 Michael Hart (michael.hart.au@gmail.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. + + axios MIT Copyright (c) 2014-present Matt Zabriskie @@ -592,31 +684,74 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -bignumber.js -MIT -The MIT Licence. +bcrypt-pbkdf +BSD-3-Clause +The Blowfish portions are under the following license: -Copyright (c) 2019 Michael Mclaughlin +Blowfish block cipher for OpenBSD +Copyright 1997 Niels Provos +All rights reserved. -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: +Implementation advice by David Mazieres . + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. 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. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + + +The bcrypt_pbkdf portions are under the following license: + +Copyright (c) 2013 Ted Unangst + +Permission to use, copy, modify, and 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. -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. +Performance improvements (Javascript-specific): + +Copyright 2016, Joyent Inc +Author: Alex Wilson + +Permission to use, copy, modify, and 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. bl @@ -624,7 +759,7 @@ MIT The MIT License (MIT) ===================== -Copyright (c) 2013-2019 bl contributors +Copyright (c) 2013-2018 bl contributors ---------------------------------- *bl contributors listed at * @@ -677,6 +812,37 @@ Redistribution and use in source and binary forms, with or without modification, 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 HOLDER 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. +caseless +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: +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +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 +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 + chalk MIT MIT License @@ -709,31 +875,6 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -code-point-at -MIT -The MIT License (MIT) - -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. - - color-convert MIT Copyright (c) 2011-2016 Heather Arthur @@ -1234,15 +1375,39 @@ 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. -ecdsa-sig-formatter -Apache-2.0 -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ +ecc-jsbn +MIT +The MIT License (MIT) - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +Copyright (c) 2014 Jeremie Miller - 1. Definitions. +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. + +ecdsa-sig-formatter +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. @@ -1439,6 +1604,130 @@ Apache License limitations under the License. +emoji-regex +MIT +Copyright Mathias Bynens + +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. + + +extend +MIT +The MIT License (MIT) + +Copyright (c) 2014 Stefan Thomas + +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. + + + +extsprintf +MIT +Copyright (c) 2012, Joyent, Inc. All rights reserved. + +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-deep-equal +MIT +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +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-json-stable-stringify +MIT +This software is released under the MIT license: + +Copyright (c) 2017 Evgeny Poberezkin +Copyright (c) 2013 James Halliday + +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. + + follow-redirects MIT Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh @@ -1461,6 +1750,64 @@ 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. +forever-agent +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: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +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 + +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 + form-data MIT Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors @@ -1573,6 +1920,36 @@ under a Creative Commons Attribution-ShareAlike 4.0 International License https://creativecommons.org/licenses/by-sa/4.0/ +har-schema +ISC +Copyright (c) 2015, Ahmad Nassri + +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. + + +har-validator +MIT +MIT License + +Copyright (c) 2018 Ahmad Nassri + +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. + + has-flag MIT MIT License @@ -1637,29 +2014,26 @@ 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. -iconv-lite +http-signature MIT -Copyright (c) 2011 Alexander Shtuchkin - -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. +Copyright Joyent, Inc. All rights reserved. +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 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. +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. inflight @@ -1701,58 +2075,55 @@ PERFORMANCE OF THIS SOFTWARE. -ip-regex +is-fullwidth-code-point MIT -The MIT License (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: +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 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. +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-fullwidth-code-point +is-typedarray MIT -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) +This software is released under the MIT 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: +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 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. +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. -isarray +isstream MIT +The MIT License (MIT) +===================== + +Copyright (c) 2015 Rod Vagg +--------------------------- + +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-yaml MIT @@ -1959,6 +2330,119 @@ Apache-2.0 END OF TERMS AND CONDITIONS +jsbn +MIT +Licensing +--------- + +This software is covered under the following copyright: + +/* + * Copyright (c) 2003-2005 Tom Wu + * All Rights Reserved. + * + * 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" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, + * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF + * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * In addition, the following condition applies: + * + * All redistributions must retain an intact copy of this copyright notice + * and disclaimer. + */ + +Address all questions regarding this license to: + + Tom Wu + tjw@cs.Stanford.EDU + +json-schema +AFLv2.1 + +json-schema-traverse +MIT +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +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. + + +json-stringify-safe +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +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. + + +jsprim +MIT +Copyright (c) 2012, Joyent, Inc. All rights reserved. + +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 + + jwa MIT Copyright (c) 2013 Brian J. Brennan @@ -2198,57 +2682,6 @@ SOFTWARE. -node-abort-controller -MIT -MIT License - -Copyright (c) 2019 Steve Faulkner - -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. - - -node-fetch -MIT -The MIT License (MIT) - -Copyright (c) 2016 David Frank - -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. - - - node-pre-gyp BSD-3-Clause Copyright (c), Mapbox @@ -2318,30 +2751,63 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -number-is-nan -MIT -The MIT License (MIT) +oauth-sign +Apache-2.0 +Apache License -Copyright (c) Sindre Sorhus (sindresorhus.com) +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: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +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 + +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. -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: +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. -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +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. -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. +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 object-assign MIT @@ -2527,6 +2993,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +performance-now +MIT +Copyright (c) 2013 Braveg1rl + +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. + pg MIT MIT License @@ -2749,29 +3225,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -process-nextick-args -MIT -# Copyright (c) 2015 Calvin Metcalf - -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.** - - psl MIT The MIT License (MIT) @@ -2785,6 +3238,38 @@ The above copyright notice and this permission notice shall be included in all c 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. +qs +BSD-3-Clause +Copyright (c) 2014 Nathan LaFreniere and other contributors. +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. + * The names of any contributors may not 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 HOLDERS AND 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. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors + + readable-stream MIT Node.js is licensed for use as follows: @@ -2894,24 +3379,63 @@ If the Work includes a "NOTICE" text file as part of its distribution, then any END OF TERMS AND CONDITIONS -rfdc -MIT -Copyright 2019 "David Mark Clements " +request +Apache-2.0 +Apache 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: +Version 2.0, January 2004 -The above copyright notice and this permission notice shall be included in all copies or substantial portions -of the Software. +http://www.apache.org/licenses/ -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. +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: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +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 + +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 rimraf ISC @@ -3210,52 +3734,39 @@ 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. -sqlstring +sshpk MIT -Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and 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: +Copyright Joyent, Inc. All rights reserved. +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 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. +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. string-width MIT -The MIT License (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: +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 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. +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. string_decoder @@ -3455,6 +3966,92 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +tunnel-agent +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: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +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 + +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 + +tweetnacl +Unlicense +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. + +For more information, please refer to + + typeorm MIT @@ -3537,6 +4134,29 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +verror +MIT +Copyright (c) 2016, Joyent, Inc. All rights reserved. + +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 + + wide-align ISC Copyright (c) 2015, Rebecca Turner diff --git a/dist/index.js b/dist/index.js index eccd78a..a7b7f23 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,4 +1,5 @@ -require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap +require('./sourcemap-register.js');module.exports = +/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 53597: @@ -34,17 +35,22 @@ const fs_1 = __importDefault(__nccwpck_require__(35747)); const axios_1 = __importDefault(__nccwpck_require__(96545)); async function fetchHTTP(config) { core.info('Fetching: HTTP'); + // Authorization headers + const auth = { + headers: { + authorization: config.authorization, + } + }; + const headers = config.authorization ? auth : {}; + core.info(headers.toString()); try { const response = await axios_1.default.get(config.http_url, { method: 'get', responseType: 'stream', - headers: { - authorization: config.authorization, - }, + ...headers, }); const filename = config.downloaded_filename; const writer = fs_1.default.createWriteStream(filename); - let bytesWritten = 0; response.data.pipe(writer); await new Promise((resolve, reject) => { writer.on('finish', resolve); @@ -2256,7 +2262,7 @@ function copyFile(srcFile, destFile, force) { activeDirectoryGraphResourceId: "https://graph.windows.net/", batchResourceId: "https://batch.core.windows.net/", activeDirectoryGraphApiVersion: "2013-04-05", - storageEndpointSuffix: "core.windows.net", + storageEndpointSuffix: ".core.windows.net", keyVaultDnsSuffix: ".vault.azure.net", azureDataLakeStoreFileSystemEndpointSuffix: "azuredatalakestore.net", azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "azuredatalakeanalytics.net", @@ -2276,7 +2282,7 @@ function copyFile(srcFile, destFile, force) { activeDirectoryGraphResourceId: "https://graph.chinacloudapi.cn/", activeDirectoryGraphApiVersion: "2013-04-05", batchResourceId: "https://batch.chinacloudapi.cn/", - storageEndpointSuffix: "core.chinacloudapi.cn", + storageEndpointSuffix: ".core.chinacloudapi.cn", keyVaultDnsSuffix: ".vault.azure.cn", // TODO: add dns suffixes for the china cloud for datalake store and datalake analytics once they are defined. azureDataLakeStoreFileSystemEndpointSuffix: "N/A", @@ -2297,7 +2303,7 @@ function copyFile(srcFile, destFile, force) { activeDirectoryGraphResourceId: "https://graph.windows.net/", batchResourceId: "https://batch.core.usgovcloudapi.net/", activeDirectoryGraphApiVersion: "2013-04-05", - storageEndpointSuffix: "core.usgovcloudapi.net", + storageEndpointSuffix: ".core.usgovcloudapi.net", keyVaultDnsSuffix: ".vault.usgovcloudapi.net", azureDataLakeStoreFileSystemEndpointSuffix: "N/A", azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "N/A", @@ -2317,7 +2323,7 @@ function copyFile(srcFile, destFile, force) { activeDirectoryGraphResourceId: "https://graph.cloudapi.de/", batchResourceId: "https://batch.microsoftazure.de/", activeDirectoryGraphApiVersion: "2013-04-05", - storageEndpointSuffix: "core.cloudapi.de", + storageEndpointSuffix: ".core.cloudapi.de", keyVaultDnsSuffix: ".vault.microsoftazure.de", azureDataLakeStoreFileSystemEndpointSuffix: "N/A", azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "N/A", @@ -2351,16 +2357,16 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var uuidv4 = _interopDefault(__nccwpck_require__(20621)); -var tslib = __nccwpck_require__(4351); +var axios = _interopDefault(__nccwpck_require__(96545)); +var stream = __nccwpck_require__(92413); +var FormData = _interopDefault(__nccwpck_require__(64334)); var tough = __nccwpck_require__(68930); +var tunnel = __nccwpck_require__(74294); var http = __nccwpck_require__(98605); var https = __nccwpck_require__(57211); -var node_fetch = _interopDefault(__nccwpck_require__(80467)); -var FormData = _interopDefault(__nccwpck_require__(69970)); -var stream = __nccwpck_require__(92413); -var tunnel = __nccwpck_require__(74294); var xml2js = __nccwpck_require__(66189); var os = __nccwpck_require__(12087); +var tslib = __nccwpck_require__(75636); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. @@ -2370,24 +2376,6 @@ var os = __nccwpck_require__(12087); function getHeaderKey(headerName) { return headerName.toLowerCase(); } -function isHttpHeadersLike(object) { - if (!object || typeof object !== "object") { - return false; - } - if (typeof object.rawHeaders === "function" && - typeof object.clone === "function" && - typeof object.get === "function" && - typeof object.set === "function" && - typeof object.contains === "function" && - typeof object.remove === "function" && - typeof object.headersArray === "function" && - typeof object.headerValues === "function" && - typeof object.headerNames === "function" && - typeof object.toJson === "function") { - return true; - } - return false; -} /** * A collection of HTTP header key/value pairs. */ @@ -2407,10 +2395,7 @@ var HttpHeaders = /** @class */ (function () { * @param headerValue The value of the header to set. */ HttpHeaders.prototype.set = function (headerName, headerValue) { - this._headersMap[getHeaderKey(headerName)] = { - name: headerName, - value: headerValue.toString(), - }; + this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() }; }; /** * Get the header value for the provided header name, or undefined if no header exists in this @@ -2517,7 +2502,7 @@ function encodeString(value) { function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length - var bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); + var bufferValue = (value instanceof Buffer) ? value : Buffer.from(value.buffer); return bufferValue.toString("base64"); } /** @@ -2536,7 +2521,7 @@ var Constants = { * @const * @type {string} */ - msRestVersion: "2.5.0", + msRestVersion: "1.11.2", /** * Specifies HTTP. * @@ -2565,14 +2550,6 @@ var Constants = { * @type {string} */ HTTPS_PROXY: "HTTPS_PROXY", - /** - * Specifies NO Proxy. - */ - NO_PROXY: "NO_PROXY", - /** - * Specifies ALL Proxy. - */ - ALL_PROXY: "ALL_PROXY", HttpConstants: { /** * Http Verbs @@ -2587,11 +2564,11 @@ var Constants = { POST: "POST", MERGE: "MERGE", HEAD: "HEAD", - PATCH: "PATCH", + PATCH: "PATCH" }, StatusCodes: { - TooManyRequests: 429, - }, + TooManyRequests: 429 + } }, /** * Defines constants for use with HTTP headers. @@ -2620,18 +2597,15 @@ var Constants = { * @const * @type {string} */ - USER_AGENT: "User-Agent", - }, + USER_AGENT: "User-Agent" + } }; // Copyright (c) Microsoft Corporation. All rights reserved. /** * A constant that indicates whether the environment is node.js or browser based. */ -var isNode = typeof process !== "undefined" && - !!process.version && - !!process.versions && - !!process.versions.node; +var isNode = (typeof process !== "undefined") && !!process.version && !!process.versions && !!process.versions.node; /** * Encodes an URI. * @@ -2795,15 +2769,6 @@ function isDuration(value) { function replaceAll(value, searchValue, replaceValue) { return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); } -/** - * Determines whether the given enity is a basic/primitive type - * (string, number, boolean, null, undefined). - * @param value Any entity - * @return boolean - true is it is primitive type, false otherwise. - */ -function isPrimitiveType(value) { - return (typeof value !== "object" && typeof value !== "function") || value === null; -} // Copyright (c) Microsoft Corporation. All rights reserved. var Serializer = /** @class */ (function () { @@ -2816,7 +2781,7 @@ var Serializer = /** @class */ (function () { var failValidation = function (constraintName, constraintValue) { throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + "."); }; - if (mapper.constraints && value != undefined) { + if (mapper.constraints && (value != undefined)) { var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems; if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); @@ -2845,14 +2810,10 @@ var Serializer = /** @class */ (function () { if (MultipleOf != undefined && value % MultipleOf !== 0) { failValidation("MultipleOf", MultipleOf); } - if (Pattern) { - var pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; - if (typeof value !== "string" || value.match(pattern) === null) { - failValidation("Pattern", Pattern); - } + if (Pattern && value.match(Pattern) === null) { + failValidation("Pattern", Pattern); } - if (UniqueItems && - value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { + if (UniqueItems && value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { failValidation("UniqueItems", UniqueItems); } } @@ -2874,10 +2835,10 @@ var Serializer = /** @class */ (function () { if (!objectName) { objectName = mapper.serializedName; } - if (mapperType.match(/^Sequence$/gi) !== null) { + if (mapperType.match(/^Sequence$/ig) !== null) { payload = []; } - if (mapper.isConstant) { + if (object == undefined && (mapper.defaultValue != undefined || mapper.isConstant)) { object = mapper.defaultValue; } // This table of allowed values should help explain @@ -2905,32 +2866,32 @@ var Serializer = /** @class */ (function () { else { // Validate Constraints if any this.validateConstraints(mapper, object, objectName); - if (mapperType.match(/^any$/gi) !== null) { + if (mapperType.match(/^any$/ig) !== null) { payload = object; } - else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/gi) !== null) { + else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/ig) !== null) { payload = serializeBasicTypes(mapperType, objectName, object); } - else if (mapperType.match(/^Enum$/gi) !== null) { + else if (mapperType.match(/^Enum$/ig) !== null) { var enumMapper = mapper; payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); } - else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/gi) !== null) { + else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) { payload = serializeDateTypes(mapperType, object, objectName); } - else if (mapperType.match(/^ByteArray$/gi) !== null) { + else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = serializeByteArrayType(objectName, object); } - else if (mapperType.match(/^Base64Url$/gi) !== null) { + else if (mapperType.match(/^Base64Url$/ig) !== null) { payload = serializeBase64UrlType(objectName, object); } - else if (mapperType.match(/^Sequence$/gi) !== null) { + else if (mapperType.match(/^Sequence$/ig) !== null) { payload = serializeSequenceType(this, mapper, object, objectName); } - else if (mapperType.match(/^Dictionary$/gi) !== null) { + else if (mapperType.match(/^Dictionary$/ig) !== null) { payload = serializeDictionaryType(this, mapper, object, objectName); } - else if (mapperType.match(/^Composite$/gi) !== null) { + else if (mapperType.match(/^Composite$/ig) !== null) { payload = serializeCompositeType(this, mapper, object, objectName); } } @@ -2955,10 +2916,6 @@ var Serializer = /** @class */ (function () { // so let's do the more user-friendly thing and return an empty list. responseBody = []; } - // specifically check for undefined as default value can be a falsey value `0, "", false, null` - if (mapper.defaultValue !== undefined) { - responseBody = mapper.defaultValue; - } return responseBody; } var payload; @@ -2966,7 +2923,7 @@ var Serializer = /** @class */ (function () { if (!objectName) { objectName = mapper.serializedName; } - if (mapperType.match(/^Composite$/gi) !== null) { + if (mapperType.match(/^Composite$/ig) !== null) { payload = deserializeCompositeType(this, mapper, responseBody, objectName); } else { @@ -2980,13 +2937,13 @@ var Serializer = /** @class */ (function () { responseBody = responseBody["_"]; } } - if (mapperType.match(/^Number$/gi) !== null) { + if (mapperType.match(/^Number$/ig) !== null) { payload = parseFloat(responseBody); if (isNaN(payload)) { payload = responseBody; } } - else if (mapperType.match(/^Boolean$/gi) !== null) { + else if (mapperType.match(/^Boolean$/ig) !== null) { if (responseBody === "true") { payload = true; } @@ -2997,25 +2954,25 @@ var Serializer = /** @class */ (function () { payload = responseBody; } } - else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/gi) !== null) { + else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/ig) !== null) { payload = responseBody; } - else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/gi) !== null) { + else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) { payload = new Date(responseBody); } - else if (mapperType.match(/^UnixTime$/gi) !== null) { + else if (mapperType.match(/^UnixTime$/ig) !== null) { payload = unixTimeToDate(responseBody); } - else if (mapperType.match(/^ByteArray$/gi) !== null) { + else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = decodeString(responseBody); } - else if (mapperType.match(/^Base64Url$/gi) !== null) { + else if (mapperType.match(/^Base64Url$/ig) !== null) { payload = base64UrlToByteArray(responseBody); } - else if (mapperType.match(/^Sequence$/gi) !== null) { + else if (mapperType.match(/^Sequence$/ig) !== null) { payload = deserializeSequenceType(this, mapper, responseBody, objectName); } - else if (mapperType.match(/^Dictionary$/gi) !== null) { + else if (mapperType.match(/^Dictionary$/ig) !== null) { payload = deserializeDictionaryType(this, mapper, responseBody, objectName); } } @@ -3028,7 +2985,7 @@ var Serializer = /** @class */ (function () { }()); function trimEnd(str, ch) { var len = str.length; - while (len - 1 >= 0 && str[len - 1] === ch) { + while ((len - 1) >= 0 && str[len - 1] === ch) { --len; } return str.substr(0, len); @@ -3093,27 +3050,27 @@ function unixTimeToDate(n) { } function serializeBasicTypes(typeName, objectName, value) { if (value !== null && value !== undefined) { - if (typeName.match(/^Number$/gi) !== null) { + if (typeName.match(/^Number$/ig) !== null) { if (typeof value !== "number") { throw new Error(objectName + " with value " + value + " must be of type number."); } } - else if (typeName.match(/^String$/gi) !== null) { + else if (typeName.match(/^String$/ig) !== null) { if (typeof value.valueOf() !== "string") { throw new Error(objectName + " with value \"" + value + "\" must be of type string."); } } - else if (typeName.match(/^Uuid$/gi) !== null) { + else if (typeName.match(/^Uuid$/ig) !== null) { if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid."); } } - else if (typeName.match(/^Boolean$/gi) !== null) { + else if (typeName.match(/^Boolean$/ig) !== null) { if (typeof value !== "boolean") { throw new Error(objectName + " with value " + value + " must be of type boolean."); } } - else if (typeName.match(/^Stream$/gi) !== null) { + else if (typeName.match(/^Stream$/ig) !== null) { var objectType = typeof value; if (objectType !== "string" && objectType !== "function" && @@ -3161,31 +3118,28 @@ function serializeBase64UrlType(objectName, value) { } function serializeDateTypes(typeName, value, objectName) { if (value != undefined) { - if (typeName.match(/^Date$/gi) !== null) { + if (typeName.match(/^Date$/ig) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format."); } - value = - value instanceof Date - ? value.toISOString().substring(0, 10) - : new Date(value).toISOString().substring(0, 10); + value = (value instanceof Date) ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10); } - else if (typeName.match(/^DateTime$/gi) !== null) { + else if (typeName.match(/^DateTime$/ig) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format."); } - value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + value = (value instanceof Date) ? value.toISOString() : new Date(value).toISOString(); } - else if (typeName.match(/^DateTimeRfc1123$/gi) !== null) { + else if (typeName.match(/^DateTimeRfc1123$/ig) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format."); } - value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); + value = (value instanceof Date) ? value.toUTCString() : new Date(value).toUTCString(); } - else if (typeName.match(/^UnixTime$/gi) !== null) { + else if (typeName.match(/^UnixTime$/ig) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " + @@ -3193,7 +3147,7 @@ function serializeDateTypes(typeName, value, objectName) { } value = dateToUnixTime(value); } - else if (typeName.match(/^TimeSpan$/gi) !== null) { + else if (typeName.match(/^TimeSpan$/ig) !== null) { if (!isDuration(value)) { throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\"."); } @@ -3287,7 +3241,7 @@ function serializeCompositeType(serializer, mapper, object, objectName) { for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) { var pathName = paths_1[_c]; var childObject = parentObject[pathName]; - if (childObject == undefined && object[key] != undefined) { + if ((childObject == undefined) && (object[key] != undefined)) { parentObject[pathName] = {}; } parentObject = parentObject[pathName]; @@ -3299,9 +3253,7 @@ function serializeCompositeType(serializer, mapper, object, objectName) { : objectName; var toSerialize = object[key]; var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator && - polymorphicDiscriminator.clientName === key && - toSerialize == undefined) { + if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) { toSerialize = mapper.serializedName; } var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName); @@ -3402,18 +3354,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName) } propertyInstance = res; var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; - // checking that the model property name (key)(ex: "fishtype") and the - // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") - // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") - // is a better approach. The generator is not consistent with escaping '\.' in the - // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator - // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However, - // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and - // the transformation of model property name (ex: "fishtype") is done consistently. - // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator. - if (polymorphicDiscriminator && - key === polymorphicDiscriminator.clientName && - propertyInstance == undefined) { + if (polymorphicDiscriminator && propertyMapper.serializedName === polymorphicDiscriminator.serializedName && propertyInstance == undefined) { propertyInstance = mapper.serializedName; } var serializedValue = void 0; @@ -3422,7 +3363,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName) propertyInstance = responseBody[key]; instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); } - else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { + else if (propertyInstance !== undefined) { serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); instance[key] = serializedValue; } @@ -3448,9 +3389,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName) else if (responseBody) { for (var _e = 0, _f = Object.keys(responseBody); _e < _f.length; _e++) { var key = _f[_e]; - if (instance[key] === undefined && - !handledPropertyNames.includes(key) && - !isSpecialXmlProperty(key)) { + if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key)) { instance[key] = responseBody[key]; } } @@ -3515,14 +3454,12 @@ function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyNam return mapper; } function getPolymorphicDiscriminatorRecursively(serializer, mapper) { - return (mapper.type.polymorphicDiscriminator || - getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || - getPolymorphicDiscriminatorSafely(serializer, mapper.type.className)); + return mapper.type.polymorphicDiscriminator + || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) + || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className); } function getPolymorphicDiscriminatorSafely(serializer, typeName) { - return (typeName && - serializer.modelMappers[typeName] && - serializer.modelMappers[typeName].type.polymorphicDiscriminator); + return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator); } // TODO: why is this here? function serializeObject(toSerialize) { @@ -3578,25 +3515,10 @@ var MapperType = strEnum([ "String", "Stream", "TimeSpan", - "UnixTime", + "UnixTime" ]); // Copyright (c) Microsoft Corporation. All rights reserved. -function isWebResourceLike(object) { - if (typeof object !== "object") { - return false; - } - if (typeof object.url === "string" && - typeof object.method === "string" && - typeof object.headers === "object" && - isHttpHeadersLike(object.headers) && - typeof object.validateRequestProperties === "function" && - typeof object.prepare === "function" && - typeof object.clone === "function") { - return true; - } - return false; -} /** * Creates a new WebResource object. * @@ -3606,11 +3528,11 @@ function isWebResourceLike(object) { * @constructor */ var WebResource = /** @class */ (function () { - function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings, redirectLimit) { + function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings) { this.streamResponseBody = streamResponseBody; this.url = url || ""; this.method = method || "GET"; - this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); + this.headers = (headers instanceof HttpHeaders ? headers : new HttpHeaders(headers)); this.body = body; this.query = query; this.formData = undefined; @@ -3622,7 +3544,6 @@ var WebResource = /** @class */ (function () { this.proxySettings = proxySettings; this.keepAlive = keepAlive; this.agentSettings = agentSettings; - this.redirectLimit = redirectLimit; } /** * Validates that the required properties such as method, url, headers["Content-Type"], @@ -3652,14 +3573,13 @@ var WebResource = /** @class */ (function () { if (options.url && options.pathTemplate) { throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them."); } - if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") && - (options.url == undefined || typeof options.url.valueOf() !== "string")) { + if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") && (options.url == undefined || typeof options.url.valueOf() !== "string")) { throw new Error("Please provide exactly one of options.pathTemplate or options.url."); } // set the url if it is provided. if (options.url) { if (typeof options.url !== "string") { - throw new Error('options.url must be of type "string".'); + throw new Error("options.url must be of type \"string\"."); } this.url = options.url; } @@ -3667,10 +3587,7 @@ var WebResource = /** @class */ (function () { if (options.method) { var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; if (validMethods.indexOf(options.method.toUpperCase()) === -1) { - throw new Error('The provided method "' + - options.method + - '" is invalid. Supported HTTP methods are: ' + - JSON.stringify(validMethods)); + throw new Error("The provided method \"" + options.method + "\" is invalid. Supported HTTP methods are: " + JSON.stringify(validMethods)); } } this.method = options.method.toUpperCase(); @@ -3678,16 +3595,14 @@ var WebResource = /** @class */ (function () { if (options.pathTemplate) { var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters; if (typeof pathTemplate_1 !== "string") { - throw new Error('options.pathTemplate must be of type "string".'); + throw new Error("options.pathTemplate must be of type \"string\"."); } if (!options.baseUrl) { options.baseUrl = "https://management.azure.com"; } var baseUrl = options.baseUrl; - var url_1 = baseUrl + - (baseUrl.endsWith("/") ? "" : "/") + - (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1); - var segments = url_1.match(/({\w*\s*\w*})/gi); + var url_1 = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1); + var segments = url_1.match(/({\w*\s*\w*})/ig); if (segments && segments.length) { if (!pathParameters_1) { throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided."); @@ -3695,9 +3610,7 @@ var WebResource = /** @class */ (function () { segments.forEach(function (item) { var pathParamName = item.slice(1, -1); var pathParam = pathParameters_1[pathParamName]; - if (pathParam === null || - pathParam === undefined || - !(typeof pathParam === "string" || typeof pathParam === "object")) { + if (pathParam === null || pathParam === undefined || !(typeof pathParam === "string" || typeof pathParam === "object")) { throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName + (" however, it is not present in " + pathParameters_1 + " - " + JSON.stringify(pathParameters_1, undefined, 2) + ".") + ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") + @@ -3806,8 +3719,6 @@ var WebResource = /** @class */ (function () { this.abortSignal = options.abortSignal; this.onDownloadProgress = options.onDownloadProgress; this.onUploadProgress = options.onUploadProgress; - this.redirectLimit = options.redirectLimit; - this.streamResponseBody = options.streamResponseBody; return this; }; /** @@ -3815,7 +3726,7 @@ var WebResource = /** @class */ (function () { * @returns {WebResource} The clone of this WebResource HTTP request object. */ WebResource.prototype.clone = function () { - var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.agentSettings, this.redirectLimit); + var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.agentSettings); if (this.formData) { result.formData = this.formData; } @@ -3833,979 +3744,6 @@ var WebResource = /** @class */ (function () { return WebResource; }()); -/** - * @author Toru Nagashima - * @copyright 2015 Toru Nagashima. All rights reserved. - * See LICENSE file in root directory for full license. - */ -/** - * @typedef {object} PrivateData - * @property {EventTarget} eventTarget The event target. - * @property {{type:string}} event The original event object. - * @property {number} eventPhase The current event phase. - * @property {EventTarget|null} currentTarget The current event target. - * @property {boolean} canceled The flag to prevent default. - * @property {boolean} stopped The flag to stop propagation. - * @property {boolean} immediateStopped The flag to stop propagation immediately. - * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. - * @property {number} timeStamp The unix time. - * @private - */ - -/** - * Private data for event wrappers. - * @type {WeakMap} - * @private - */ -const privateData = new WeakMap(); - -/** - * Cache for wrapper classes. - * @type {WeakMap} - * @private - */ -const wrappers = new WeakMap(); - -/** - * Get private data. - * @param {Event} event The event object to get private data. - * @returns {PrivateData} The private data of the event. - * @private - */ -function pd(event) { - const retv = privateData.get(event); - console.assert( - retv != null, - "'this' is expected an Event object, but got", - event - ); - return retv -} - -/** - * https://dom.spec.whatwg.org/#set-the-canceled-flag - * @param data {PrivateData} private data. - */ -function setCancelFlag(data) { - if (data.passiveListener != null) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error( - "Unable to preventDefault inside passive event listener invocation.", - data.passiveListener - ); - } - return - } - if (!data.event.cancelable) { - return - } - - data.canceled = true; - if (typeof data.event.preventDefault === "function") { - data.event.preventDefault(); - } -} - -/** - * @see https://dom.spec.whatwg.org/#interface-event - * @private - */ -/** - * The event wrapper. - * @constructor - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Event|{type:string}} event The original event to wrap. - */ -function Event(eventTarget, event) { - privateData.set(this, { - eventTarget, - event, - eventPhase: 2, - currentTarget: eventTarget, - canceled: false, - stopped: false, - immediateStopped: false, - passiveListener: null, - timeStamp: event.timeStamp || Date.now(), - }); - - // https://heycam.github.io/webidl/#Unforgeable - Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); - - // Define accessors - const keys = Object.keys(event); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in this)) { - Object.defineProperty(this, key, defineRedirectDescriptor(key)); - } - } -} - -// Should be enumerable, but class methods are not enumerable. -Event.prototype = { - /** - * The type of this event. - * @type {string} - */ - get type() { - return pd(this).event.type - }, - - /** - * The target of this event. - * @type {EventTarget} - */ - get target() { - return pd(this).eventTarget - }, - - /** - * The target of this event. - * @type {EventTarget} - */ - get currentTarget() { - return pd(this).currentTarget - }, - - /** - * @returns {EventTarget[]} The composed path of this event. - */ - composedPath() { - const currentTarget = pd(this).currentTarget; - if (currentTarget == null) { - return [] - } - return [currentTarget] - }, - - /** - * Constant of NONE. - * @type {number} - */ - get NONE() { - return 0 - }, - - /** - * Constant of CAPTURING_PHASE. - * @type {number} - */ - get CAPTURING_PHASE() { - return 1 - }, - - /** - * Constant of AT_TARGET. - * @type {number} - */ - get AT_TARGET() { - return 2 - }, - - /** - * Constant of BUBBLING_PHASE. - * @type {number} - */ - get BUBBLING_PHASE() { - return 3 - }, - - /** - * The target of this event. - * @type {number} - */ - get eventPhase() { - return pd(this).eventPhase - }, - - /** - * Stop event bubbling. - * @returns {void} - */ - stopPropagation() { - const data = pd(this); - - data.stopped = true; - if (typeof data.event.stopPropagation === "function") { - data.event.stopPropagation(); - } - }, - - /** - * Stop event bubbling. - * @returns {void} - */ - stopImmediatePropagation() { - const data = pd(this); - - data.stopped = true; - data.immediateStopped = true; - if (typeof data.event.stopImmediatePropagation === "function") { - data.event.stopImmediatePropagation(); - } - }, - - /** - * The flag to be bubbling. - * @type {boolean} - */ - get bubbles() { - return Boolean(pd(this).event.bubbles) - }, - - /** - * The flag to be cancelable. - * @type {boolean} - */ - get cancelable() { - return Boolean(pd(this).event.cancelable) - }, - - /** - * Cancel this event. - * @returns {void} - */ - preventDefault() { - setCancelFlag(pd(this)); - }, - - /** - * The flag to indicate cancellation state. - * @type {boolean} - */ - get defaultPrevented() { - return pd(this).canceled - }, - - /** - * The flag to be composed. - * @type {boolean} - */ - get composed() { - return Boolean(pd(this).event.composed) - }, - - /** - * The unix time of this event. - * @type {number} - */ - get timeStamp() { - return pd(this).timeStamp - }, - - /** - * The target of this event. - * @type {EventTarget} - * @deprecated - */ - get srcElement() { - return pd(this).eventTarget - }, - - /** - * The flag to stop event bubbling. - * @type {boolean} - * @deprecated - */ - get cancelBubble() { - return pd(this).stopped - }, - set cancelBubble(value) { - if (!value) { - return - } - const data = pd(this); - - data.stopped = true; - if (typeof data.event.cancelBubble === "boolean") { - data.event.cancelBubble = true; - } - }, - - /** - * The flag to indicate cancellation state. - * @type {boolean} - * @deprecated - */ - get returnValue() { - return !pd(this).canceled - }, - set returnValue(value) { - if (!value) { - setCancelFlag(pd(this)); - } - }, - - /** - * Initialize this event object. But do nothing under event dispatching. - * @param {string} type The event type. - * @param {boolean} [bubbles=false] The flag to be possible to bubble up. - * @param {boolean} [cancelable=false] The flag to be possible to cancel. - * @deprecated - */ - initEvent() { - // Do nothing. - }, -}; - -// `constructor` is not enumerable. -Object.defineProperty(Event.prototype, "constructor", { - value: Event, - configurable: true, - writable: true, -}); - -// Ensure `event instanceof window.Event` is `true`. -if (typeof window !== "undefined" && typeof window.Event !== "undefined") { - Object.setPrototypeOf(Event.prototype, window.Event.prototype); - - // Make association for wrappers. - wrappers.set(window.Event.prototype, Event); -} - -/** - * Get the property descriptor to redirect a given property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to redirect the property. - * @private - */ -function defineRedirectDescriptor(key) { - return { - get() { - return pd(this).event[key] - }, - set(value) { - pd(this).event[key] = value; - }, - configurable: true, - enumerable: true, - } -} - -/** - * Get the property descriptor to call a given method property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to call the method property. - * @private - */ -function defineCallDescriptor(key) { - return { - value() { - const event = pd(this).event; - return event[key].apply(event, arguments) - }, - configurable: true, - enumerable: true, - } -} - -/** - * Define new wrapper class. - * @param {Function} BaseEvent The base wrapper class. - * @param {Object} proto The prototype of the original event. - * @returns {Function} The defined wrapper class. - * @private - */ -function defineWrapper(BaseEvent, proto) { - const keys = Object.keys(proto); - if (keys.length === 0) { - return BaseEvent - } - - /** CustomEvent */ - function CustomEvent(eventTarget, event) { - BaseEvent.call(this, eventTarget, event); - } - - CustomEvent.prototype = Object.create(BaseEvent.prototype, { - constructor: { value: CustomEvent, configurable: true, writable: true }, - }); - - // Define accessors. - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in BaseEvent.prototype)) { - const descriptor = Object.getOwnPropertyDescriptor(proto, key); - const isFunc = typeof descriptor.value === "function"; - Object.defineProperty( - CustomEvent.prototype, - key, - isFunc - ? defineCallDescriptor(key) - : defineRedirectDescriptor(key) - ); - } - } - - return CustomEvent -} - -/** - * Get the wrapper class of a given prototype. - * @param {Object} proto The prototype of the original event to get its wrapper. - * @returns {Function} The wrapper class. - * @private - */ -function getWrapper(proto) { - if (proto == null || proto === Object.prototype) { - return Event - } - - let wrapper = wrappers.get(proto); - if (wrapper == null) { - wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); - wrappers.set(proto, wrapper); - } - return wrapper -} - -/** - * Wrap a given event to management a dispatching. - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Object} event The event to wrap. - * @returns {Event} The wrapper instance. - * @private - */ -function wrapEvent(eventTarget, event) { - const Wrapper = getWrapper(Object.getPrototypeOf(event)); - return new Wrapper(eventTarget, event) -} - -/** - * Get the immediateStopped flag of a given event. - * @param {Event} event The event to get. - * @returns {boolean} The flag to stop propagation immediately. - * @private - */ -function isStopped(event) { - return pd(event).immediateStopped -} - -/** - * Set the current event phase of a given event. - * @param {Event} event The event to set current target. - * @param {number} eventPhase New event phase. - * @returns {void} - * @private - */ -function setEventPhase(event, eventPhase) { - pd(event).eventPhase = eventPhase; -} - -/** - * Set the current target of a given event. - * @param {Event} event The event to set current target. - * @param {EventTarget|null} currentTarget New current target. - * @returns {void} - * @private - */ -function setCurrentTarget(event, currentTarget) { - pd(event).currentTarget = currentTarget; -} - -/** - * Set a passive listener of a given event. - * @param {Event} event The event to set current target. - * @param {Function|null} passiveListener New passive listener. - * @returns {void} - * @private - */ -function setPassiveListener(event, passiveListener) { - pd(event).passiveListener = passiveListener; -} - -/** - * @typedef {object} ListenerNode - * @property {Function} listener - * @property {1|2|3} listenerType - * @property {boolean} passive - * @property {boolean} once - * @property {ListenerNode|null} next - * @private - */ - -/** - * @type {WeakMap>} - * @private - */ -const listenersMap = new WeakMap(); - -// Listener types -const CAPTURE = 1; -const BUBBLE = 2; -const ATTRIBUTE = 3; - -/** - * Check whether a given value is an object or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is an object. - */ -function isObject(x) { - return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax -} - -/** - * Get listeners. - * @param {EventTarget} eventTarget The event target to get. - * @returns {Map} The listeners. - * @private - */ -function getListeners(eventTarget) { - const listeners = listenersMap.get(eventTarget); - if (listeners == null) { - throw new TypeError( - "'this' is expected an EventTarget object, but got another value." - ) - } - return listeners -} - -/** - * Get the property descriptor for the event attribute of a given event. - * @param {string} eventName The event name to get property descriptor. - * @returns {PropertyDescriptor} The property descriptor. - * @private - */ -function defineEventAttributeDescriptor(eventName) { - return { - get() { - const listeners = getListeners(this); - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - return node.listener - } - node = node.next; - } - return null - }, - - set(listener) { - if (typeof listener !== "function" && !isObject(listener)) { - listener = null; // eslint-disable-line no-param-reassign - } - const listeners = getListeners(this); - - // Traverse to the tail while removing old value. - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - // Remove old value. - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - - node = node.next; - } - - // Add new value. - if (listener !== null) { - const newNode = { - listener, - listenerType: ATTRIBUTE, - passive: false, - once: false, - next: null, - }; - if (prev === null) { - listeners.set(eventName, newNode); - } else { - prev.next = newNode; - } - } - }, - configurable: true, - enumerable: true, - } -} - -/** - * Define an event attribute (e.g. `eventTarget.onclick`). - * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. - * @param {string} eventName The event name to define. - * @returns {void} - */ -function defineEventAttribute(eventTargetPrototype, eventName) { - Object.defineProperty( - eventTargetPrototype, - `on${eventName}`, - defineEventAttributeDescriptor(eventName) - ); -} - -/** - * Define a custom EventTarget with event attributes. - * @param {string[]} eventNames Event names for event attributes. - * @returns {EventTarget} The custom EventTarget. - * @private - */ -function defineCustomEventTarget(eventNames) { - /** CustomEventTarget */ - function CustomEventTarget() { - EventTarget.call(this); - } - - CustomEventTarget.prototype = Object.create(EventTarget.prototype, { - constructor: { - value: CustomEventTarget, - configurable: true, - writable: true, - }, - }); - - for (let i = 0; i < eventNames.length; ++i) { - defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); - } - - return CustomEventTarget -} - -/** - * EventTarget. - * - * - This is constructor if no arguments. - * - This is a function which returns a CustomEventTarget constructor if there are arguments. - * - * For example: - * - * class A extends EventTarget {} - * class B extends EventTarget("message") {} - * class C extends EventTarget("message", "error") {} - * class D extends EventTarget(["message", "error"]) {} - */ -function EventTarget() { - /*eslint-disable consistent-return */ - if (this instanceof EventTarget) { - listenersMap.set(this, new Map()); - return - } - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return defineCustomEventTarget(arguments[0]) - } - if (arguments.length > 0) { - const types = new Array(arguments.length); - for (let i = 0; i < arguments.length; ++i) { - types[i] = arguments[i]; - } - return defineCustomEventTarget(types) - } - throw new TypeError("Cannot call a class as a function") - /*eslint-enable consistent-return */ -} - -// Should be enumerable, but class methods are not enumerable. -EventTarget.prototype = { - /** - * Add a given listener to this event target. - * @param {string} eventName The event name to add. - * @param {Function} listener The listener to add. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - addEventListener(eventName, listener, options) { - if (listener == null) { - return - } - if (typeof listener !== "function" && !isObject(listener)) { - throw new TypeError("'listener' should be a function or an object.") - } - - const listeners = getListeners(this); - const optionsIsObj = isObject(options); - const capture = optionsIsObj - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - const newNode = { - listener, - listenerType, - passive: optionsIsObj && Boolean(options.passive), - once: optionsIsObj && Boolean(options.once), - next: null, - }; - - // Set it as the first node if the first node is null. - let node = listeners.get(eventName); - if (node === undefined) { - listeners.set(eventName, newNode); - return - } - - // Traverse to the tail while checking duplication.. - let prev = null; - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - // Should ignore duplication. - return - } - prev = node; - node = node.next; - } - - // Add it. - prev.next = newNode; - }, - - /** - * Remove a given listener from this event target. - * @param {string} eventName The event name to remove. - * @param {Function} listener The listener to remove. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - removeEventListener(eventName, listener, options) { - if (listener == null) { - return - } - - const listeners = getListeners(this); - const capture = isObject(options) - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - return - } - - prev = node; - node = node.next; - } - }, - - /** - * Dispatch a given event. - * @param {Event|{type:string}} event The event to dispatch. - * @returns {boolean} `false` if canceled. - */ - dispatchEvent(event) { - if (event == null || typeof event.type !== "string") { - throw new TypeError('"event.type" should be a string.') - } - - // If listeners aren't registered, terminate. - const listeners = getListeners(this); - const eventName = event.type; - let node = listeners.get(eventName); - if (node == null) { - return true - } - - // Since we cannot rewrite several properties, so wrap object. - const wrappedEvent = wrapEvent(this, event); - - // This doesn't process capturing phase and bubbling phase. - // This isn't participating in a tree. - let prev = null; - while (node != null) { - // Remove this listener if it's once - if (node.once) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - - // Call this listener - setPassiveListener( - wrappedEvent, - node.passive ? node.listener : null - ); - if (typeof node.listener === "function") { - try { - node.listener.call(this, wrappedEvent); - } catch (err) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error(err); - } - } - } else if ( - node.listenerType !== ATTRIBUTE && - typeof node.listener.handleEvent === "function" - ) { - node.listener.handleEvent(wrappedEvent); - } - - // Break if `event.stopImmediatePropagation` was called. - if (isStopped(wrappedEvent)) { - break - } - - node = node.next; - } - setPassiveListener(wrappedEvent, null); - setEventPhase(wrappedEvent, 0); - setCurrentTarget(wrappedEvent, null); - - return !wrappedEvent.defaultPrevented - }, -}; - -// `constructor` is not enumerable. -Object.defineProperty(EventTarget.prototype, "constructor", { - value: EventTarget, - configurable: true, - writable: true, -}); - -// Ensure `eventTarget instanceof window.EventTarget` is `true`. -if ( - typeof window !== "undefined" && - typeof window.EventTarget !== "undefined" -) { - Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); -} - -/** - * @author Toru Nagashima - * See LICENSE file in root directory for full license. - */ - -/** - * The signal class. - * @see https://dom.spec.whatwg.org/#abortsignal - */ -class AbortSignal extends EventTarget { - /** - * AbortSignal cannot be constructed directly. - */ - constructor() { - super(); - throw new TypeError("AbortSignal cannot be constructed directly"); - } - /** - * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. - */ - get aborted() { - const aborted = abortedFlags.get(this); - if (typeof aborted !== "boolean") { - throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); - } - return aborted; - } -} -defineEventAttribute(AbortSignal.prototype, "abort"); -/** - * Create an AbortSignal object. - */ -function createAbortSignal() { - const signal = Object.create(AbortSignal.prototype); - EventTarget.call(signal); - abortedFlags.set(signal, false); - return signal; -} -/** - * Abort a given signal. - */ -function abortSignal(signal) { - if (abortedFlags.get(signal) !== false) { - return; - } - abortedFlags.set(signal, true); - signal.dispatchEvent({ type: "abort" }); -} -/** - * Aborted flag for each instances. - */ -const abortedFlags = new WeakMap(); -// Properties should be enumerable. -Object.defineProperties(AbortSignal.prototype, { - aborted: { enumerable: true }, -}); -// `toString()` should return `"[object AbortSignal]"` -if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortSignal", - }); -} - -/** - * The AbortController. - * @see https://dom.spec.whatwg.org/#abortcontroller - */ -class AbortController { - /** - * Initialize this controller. - */ - constructor() { - signals.set(this, createAbortSignal()); - } - /** - * Returns the `AbortSignal` object associated with this object. - */ - get signal() { - return getSignal(this); - } - /** - * Abort and signal to any observers that the associated activity is to be aborted. - */ - abort() { - abortSignal(getSignal(this)); - } -} -/** - * Associated signals. - */ -const signals = new WeakMap(); -/** - * Get the associated signal of a given controller. - */ -function getSignal(controller) { - const signal = signals.get(controller); - if (signal == null) { - throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); - } - return signal; -} -// Properties should be enumerable. -Object.defineProperties(AbortController.prototype, { - signal: { enumerable: true }, - abort: { enumerable: true }, -}); -if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortController", - }); -} - // Copyright (c) Microsoft Corporation. All rights reserved. var RestError = /** @class */ (function (_super) { tslib.__extends(RestError, _super); @@ -4825,212 +3763,6 @@ var RestError = /** @class */ (function (_super) { return RestError; }(Error)); -// Copyright (c) Microsoft Corporation. All rights reserved. -var FetchHttpClient = /** @class */ (function () { - function FetchHttpClient() { - } - FetchHttpClient.prototype.sendRequest = function (httpRequest) { - return tslib.__awaiter(this, void 0, void 0, function () { - var abortController, abortListener, formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, body, loadedBytes_1, uploadReportStream, platformSpecificRequestInit, requestInit, operationResponse, response, headers, _b, _c, onDownloadProgress_1, responseBody, loadedBytes_2, downloadReportStream, length_1, error_1, fetchError, uploadStreamDone, downloadStreamDone; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - if (!httpRequest && typeof httpRequest !== "object") { - throw new Error("'httpRequest' (WebResource) cannot be null or undefined and must be of type object."); - } - abortController = new AbortController(); - if (httpRequest.abortSignal) { - if (httpRequest.abortSignal.aborted) { - throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest); - } - abortListener = function (event) { - if (event.type === "abort") { - abortController.abort(); - } - }; - httpRequest.abortSignal.addEventListener("abort", abortListener); - } - if (httpRequest.timeout) { - setTimeout(function () { - abortController.abort(); - }, httpRequest.timeout); - } - if (httpRequest.formData) { - formData = httpRequest.formData; - requestForm_1 = new FormData(); - appendFormValue = function (key, value) { - // value function probably returns a stream so we can provide a fresh stream on each retry - if (typeof value === "function") { - value = value(); - } - if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) { - requestForm_1.append(key, value.value, value.options); - } - else { - requestForm_1.append(key, value); - } - }; - for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) { - formKey = _a[_i]; - formValue = formData[formKey]; - if (Array.isArray(formValue)) { - for (j = 0; j < formValue.length; j++) { - appendFormValue(formKey, formValue[j]); - } - } - else { - appendFormValue(formKey, formValue); - } - } - httpRequest.body = requestForm_1; - httpRequest.formData = undefined; - contentType = httpRequest.headers.get("Content-Type"); - if (contentType && contentType.indexOf("multipart/form-data") !== -1) { - if (typeof requestForm_1.getBoundary === "function") { - httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary()); - } - else { - // browser will automatically apply a suitable content-type header - httpRequest.headers.remove("Content-Type"); - } - } - } - body = httpRequest.body - ? typeof httpRequest.body === "function" - ? httpRequest.body() - : httpRequest.body - : undefined; - if (httpRequest.onUploadProgress && httpRequest.body) { - loadedBytes_1 = 0; - uploadReportStream = new stream.Transform({ - transform: function (chunk, _encoding, callback) { - loadedBytes_1 += chunk.length; - httpRequest.onUploadProgress({ loadedBytes: loadedBytes_1 }); - callback(undefined, chunk); - }, - }); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } - else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - return [4 /*yield*/, this.prepareRequest(httpRequest)]; - case 1: - platformSpecificRequestInit = _d.sent(); - requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController.signal, redirect: "manual" }, platformSpecificRequestInit); - _d.label = 2; - case 2: - _d.trys.push([2, 8, 9, 10]); - return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)]; - case 3: - response = _d.sent(); - headers = parseHeaders(response.headers); - _b = { - headers: headers, - request: httpRequest, - status: response.status, - readableStreamBody: httpRequest.streamResponseBody - ? response.body - : undefined - }; - if (!!httpRequest.streamResponseBody) return [3 /*break*/, 5]; - return [4 /*yield*/, response.text()]; - case 4: - _c = _d.sent(); - return [3 /*break*/, 6]; - case 5: - _c = undefined; - _d.label = 6; - case 6: - operationResponse = (_b.bodyAsText = _c, - _b.redirected = response.redirected, - _b.url = response.url, - _b); - onDownloadProgress_1 = httpRequest.onDownloadProgress; - if (onDownloadProgress_1) { - responseBody = response.body || undefined; - if (isReadableStream(responseBody)) { - loadedBytes_2 = 0; - downloadReportStream = new stream.Transform({ - transform: function (chunk, _encoding, callback) { - loadedBytes_2 += chunk.length; - onDownloadProgress_1({ loadedBytes: loadedBytes_2 }); - callback(undefined, chunk); - }, - }); - responseBody.pipe(downloadReportStream); - operationResponse.readableStreamBody = downloadReportStream; - } - else { - length_1 = parseInt(headers.get("Content-Length")) || undefined; - if (length_1) { - // Calling callback for non-stream response for consistency with browser - onDownloadProgress_1({ loadedBytes: length_1 }); - } - } - } - return [4 /*yield*/, this.processRequest(operationResponse)]; - case 7: - _d.sent(); - return [2 /*return*/, operationResponse]; - case 8: - error_1 = _d.sent(); - fetchError = error_1; - if (fetchError.code === "ENOTFOUND") { - throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); - } - else if (fetchError.type === "aborted") { - throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest); - } - throw fetchError; - case 9: - // clean up event listener - if (httpRequest.abortSignal && abortListener) { - uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); - } - downloadStreamDone = Promise.resolve(); - if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { - downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody); - } - Promise.all([uploadStreamDone, downloadStreamDone]) - .then(function () { - var _a; - (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); - return; - }) - .catch(function (_e) { }); - } - return [7 /*endfinally*/]; - case 10: return [2 /*return*/]; - } - }); - }); - }; - return FetchHttpClient; -}()); -function isReadableStream(body) { - return body && typeof body.pipe === "function"; -} -function isStreamComplete(stream) { - return new Promise(function (resolve) { - stream.on("close", resolve); - stream.on("end", resolve); - stream.on("error", resolve); - }); -} -function parseHeaders(headers) { - var httpHeaders = new HttpHeaders(); - headers.forEach(function (value, key) { - httpHeaders.set(key, value); - }); - return httpHeaders; -} - // Copyright (c) Microsoft Corporation. All rights reserved. /** * A class that handles the query portion of a URLBuilder. @@ -5123,6 +3855,11 @@ var URLQuery = /** @class */ (function () { break; case "ParameterValue": switch (currentCharacter) { + case "=": + parameterName = ""; + parameterValue = ""; + currentState = "Invalid"; + break; case "&": result.set(parameterName, parameterValue); parameterName = ""; @@ -5134,6 +3871,11 @@ var URLQuery = /** @class */ (function () { break; } break; + case "Invalid": + if (currentCharacter === "&") { + currentState = "ParameterName"; + } + break; default: throw new Error("Unrecognized URLQuery parse state: " + currentState); } @@ -5215,12 +3957,8 @@ var URLBuilder = /** @class */ (function () { this._path = undefined; } else { - var schemeIndex = path.indexOf("://"); - if (schemeIndex !== -1) { - var schemeStart = path.lastIndexOf("/", schemeIndex); - // Make sure to only grab the URL part of the path before setting the state back to SCHEME - // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com" - this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME"); + if (path.indexOf("://") !== -1) { + this.set(path, "SCHEME"); } else { this.set(path, "PATH"); @@ -5392,9 +4130,9 @@ var URLToken = /** @class */ (function () { */ function isAlphaNumericCharacter(character) { var characterCode = character.charCodeAt(0); - return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || - (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || - (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */); + return (48 /* '0' */ <= characterCode && characterCode <= 57 /* '9' */) || + (65 /* 'A' */ <= characterCode && characterCode <= 90 /* 'Z' */) || + (97 /* 'a' */ <= characterCode && characterCode <= 122 /* 'z' */); } /** * A class that tokenizes URL strings. @@ -5621,65 +4359,76 @@ function nextQuery(tokenizer) { } // Copyright (c) Microsoft Corporation. All rights reserved. -function createProxyAgent(requestUrl, proxySettings, headers) { - var tunnelOptions = { - proxy: { - host: URLBuilder.parse(proxySettings.host).getHost(), - port: proxySettings.port, - headers: (headers && headers.rawHeaders()) || {}, - }, - }; - if (proxySettings.username && proxySettings.password) { - tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password; - } - var requestScheme = URLBuilder.parse(requestUrl).getScheme() || ""; - var isRequestHttps = requestScheme.toLowerCase() === "https"; - var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || ""; - var isProxyHttps = proxyScheme.toLowerCase() === "https"; - var proxyAgent = { - isHttps: isRequestHttps, - agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions), - }; - return proxyAgent; -} -function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { - if (isRequestHttps && isProxyHttps) { - return tunnel.httpsOverHttps(tunnelOptions); - } - else if (isRequestHttps && !isProxyHttps) { - return tunnel.httpsOverHttp(tunnelOptions); - } - else if (!isRequestHttps && isProxyHttps) { - return tunnel.httpOverHttps(tunnelOptions); - } - else { - return tunnel.httpOverHttp(tunnelOptions); - } -} - -// Copyright (c) Microsoft Corporation. All rights reserved. -var NodeFetchHttpClient = /** @class */ (function (_super) { - tslib.__extends(NodeFetchHttpClient, _super); - function NodeFetchHttpClient() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.cookieJar = new tough.CookieJar(undefined, { looseMode: true }); - return _this; - } - NodeFetchHttpClient.prototype.fetch = function (input, init) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, node_fetch(input, init)]; - }); - }); - }; - NodeFetchHttpClient.prototype.prepareRequest = function (httpRequest) { +var axiosInstance = axios.create(); +// This hack is still required with 0.19.0 version of axios since axios tries to merge the +// Content-Type header from it's config[""] where the method name is lower-case, +// into the request header. It could be possible that the Content-Type header is not present +// in the original request and this would create problems while creating the signature for +// storage data plane sdks. +axiosInstance.interceptors.request.use(function (config) { return (tslib.__assign(tslib.__assign({}, config), { method: config.method && config.method.toUpperCase() })); }); +// keepalive agents are reused across instances to provide maximum socket reuse for +// outbound requests +var keepaliveAgents = { + http: new http.Agent({ keepAlive: true }), + https: new https.Agent({ keepAlive: true }), +}; +/** + * A HttpClient implementation that uses axios to send HTTP requests. + */ +var AxiosHttpClient = /** @class */ (function () { + function AxiosHttpClient() { + this.cookieJar = new tough.CookieJar(); + } + AxiosHttpClient.prototype.sendRequest = function (httpRequest) { return tslib.__awaiter(this, void 0, void 0, function () { - var requestInit, cookieString, _a, httpAgent, httpsAgent, tunnel, options, agent; + var formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, cookieString, abortSignal, abortListener, cancelToken, rawHeaders, httpRequestBody, axiosBody, onUploadProgress, loadedBytes_1, uploadReportStream, res, config, _b, httpAgent, httpsAgent, agent, err_1, axiosErr, headers, onDownloadProgress, responseBody, loadedBytes_2, downloadReportStream, length_1, operationResponse, setCookieHeader_1; var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { + return tslib.__generator(this, function (_c) { + switch (_c.label) { case 0: - requestInit = {}; + if (typeof httpRequest !== "object") { + throw new Error("httpRequest (WebResource) cannot be null or undefined and must be of type object."); + } + if (httpRequest.formData) { + formData = httpRequest.formData; + requestForm_1 = new FormData(); + appendFormValue = function (key, value) { + // value function probably returns a stream so we can provide a fresh stream on each retry + if (typeof value === "function") { + value = value(); + } + if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) { + requestForm_1.append(key, value.value, value.options); + } + else { + requestForm_1.append(key, value); + } + }; + for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) { + formKey = _a[_i]; + formValue = formData[formKey]; + if (Array.isArray(formValue)) { + for (j = 0; j < formValue.length; j++) { + appendFormValue(formKey, formValue[j]); + } + } + else { + appendFormValue(formKey, formValue); + } + } + httpRequest.body = requestForm_1; + httpRequest.formData = undefined; + contentType = httpRequest.headers.get("Content-Type"); + if (contentType && contentType.indexOf("multipart/form-data") !== -1) { + if (typeof requestForm_1.getBoundary === "function") { + httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary()); + } + else { + // browser will automatically apply a suitable content-type header + httpRequest.headers.remove("Content-Type"); + } + } + } if (!(this.cookieJar && !httpRequest.headers.get("Cookie"))) return [3 /*break*/, 2]; return [4 /*yield*/, new Promise(function (resolve, reject) { _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) { @@ -5692,52 +4441,149 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { }); })]; case 1: - cookieString = _b.sent(); + cookieString = _c.sent(); httpRequest.headers.set("Cookie", cookieString); - _b.label = 2; + _c.label = 2; case 2: + abortSignal = httpRequest.abortSignal; + if (abortSignal && abortSignal.aborted) { + throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest); + } + cancelToken = abortSignal && new axios.CancelToken(function (canceler) { + abortListener = function () { return canceler(); }; + abortSignal.addEventListener("abort", abortListener); + }); + rawHeaders = httpRequest.headers.rawHeaders(); + httpRequestBody = httpRequest.body; + axiosBody = + // Workaround for https://github.com/axios/axios/issues/755 + // tslint:disable-next-line:no-null-keyword + typeof httpRequestBody === "undefined" ? null : + typeof httpRequestBody === "function" ? httpRequestBody() : + httpRequestBody; + onUploadProgress = httpRequest.onUploadProgress; + if (onUploadProgress && axiosBody) { + loadedBytes_1 = 0; + uploadReportStream = new stream.Transform({ + transform: function (chunk, _encoding, callback) { + loadedBytes_1 += chunk.length; + onUploadProgress({ loadedBytes: loadedBytes_1 }); + callback(undefined, chunk); + } + }); + if (isReadableStream(axiosBody)) { + axiosBody.pipe(uploadReportStream); + } + else { + uploadReportStream.end(axiosBody); + } + axiosBody = uploadReportStream; + } + _c.label = 3; + case 3: + _c.trys.push([3, 5, 6, 7]); + config = { + method: httpRequest.method, + url: httpRequest.url, + headers: rawHeaders, + data: axiosBody, + transformResponse: function (data) { return data; }, + validateStatus: function () { return true; }, + // Workaround for https://github.com/axios/axios/issues/1362 + maxContentLength: Infinity, + responseType: httpRequest.streamResponseBody ? "stream" : "text", + cancelToken: cancelToken, + timeout: httpRequest.timeout, + proxy: false + }; if (httpRequest.agentSettings) { - _a = httpRequest.agentSettings, httpAgent = _a.http, httpsAgent = _a.https; - if (httpsAgent && httpRequest.url.startsWith("https")) { - requestInit.agent = httpsAgent; + _b = httpRequest.agentSettings, httpAgent = _b.http, httpsAgent = _b.https; + if (httpsAgent) { + config.httpsAgent = httpsAgent; } - else if (httpAgent) { - requestInit.agent = httpAgent; + if (httpAgent) { + config.httpAgent = httpAgent; } } else if (httpRequest.proxySettings) { - tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); - requestInit.agent = tunnel.agent; + agent = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); + if (agent.isHttps) { + config.httpsAgent = agent.agent; + } + else { + config.httpAgent = agent.agent; + } } if (httpRequest.keepAlive === true) { - if (requestInit.agent) { - requestInit.agent.keepAlive = true; + if (config.httpAgent) { + config.httpAgent.keepAlive = true; + } + else { + config.httpAgent = keepaliveAgents.http; + } + if (config.httpsAgent) { + config.httpsAgent.keepAlive = true; } else { - options = { keepAlive: true }; - agent = httpRequest.url.startsWith("https") - ? new https.Agent(options) - : new http.Agent(options); - requestInit.agent = agent; + config.httpsAgent = keepaliveAgents.https; } } - return [2 /*return*/, requestInit]; - } - }); - }); - }; - NodeFetchHttpClient.prototype.processRequest = function (operationResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var setCookieHeader_1; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.cookieJar) return [3 /*break*/, 2]; + return [4 /*yield*/, axiosInstance.request(config)]; + case 4: + res = _c.sent(); + return [3 /*break*/, 7]; + case 5: + err_1 = _c.sent(); + if (err_1 instanceof axios.Cancel) { + throw new RestError(err_1.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); + } + else { + axiosErr = err_1; + throw new RestError(axiosErr.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); + } + return [3 /*break*/, 7]; + case 6: + if (abortSignal && abortListener) { + abortSignal.removeEventListener("abort", abortListener); + } + return [7 /*endfinally*/]; + case 7: + headers = new HttpHeaders(res.headers); + onDownloadProgress = httpRequest.onDownloadProgress; + responseBody = res.data; + if (onDownloadProgress) { + if (isReadableStream(responseBody)) { + loadedBytes_2 = 0; + downloadReportStream = new stream.Transform({ + transform: function (chunk, _encoding, callback) { + loadedBytes_2 += chunk.length; + onDownloadProgress({ loadedBytes: loadedBytes_2 }); + callback(undefined, chunk); + } + }); + responseBody.pipe(downloadReportStream); + responseBody = downloadReportStream; + } + else { + length_1 = parseInt(headers.get("Content-Length")) || responseBody.length || undefined; + if (length_1) { + // Calling callback for non-stream response for consistency with browser + onDownloadProgress({ loadedBytes: length_1 }); + } + } + } + operationResponse = { + request: httpRequest, + status: res.status, + headers: headers, + readableStreamBody: httpRequest.streamResponseBody ? responseBody : undefined, + bodyAsText: httpRequest.streamResponseBody ? undefined : responseBody + }; + if (!this.cookieJar) return [3 /*break*/, 9]; setCookieHeader_1 = operationResponse.headers.get("Set-Cookie"); - if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 2]; + if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 9]; return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.cookieJar.setCookie(setCookieHeader_1, operationResponse.request.url, { ignoreError: true }, function (err) { + _this.cookieJar.setCookie(setCookieHeader_1, httpRequest.url, function (err) { if (err) { reject(err); } @@ -5746,16 +4592,56 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { } }); })]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; + case 8: + _c.sent(); + _c.label = 9; + case 9: return [2 /*return*/, operationResponse]; } }); }); }; - return NodeFetchHttpClient; -}(FetchHttpClient)); + return AxiosHttpClient; +}()); +function isReadableStream(body) { + return typeof body.pipe === "function"; +} +function createProxyAgent(requestUrl, proxySettings, headers) { + var tunnelOptions = { + proxy: { + host: URLBuilder.parse(proxySettings.host).getHost(), + port: proxySettings.port, + headers: (headers && headers.rawHeaders()) || {} + } + }; + if ((proxySettings.username && proxySettings.password)) { + tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password; + } + var requestScheme = URLBuilder.parse(requestUrl).getScheme() || ""; + var isRequestHttps = requestScheme.toLowerCase() === "https"; + var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || ""; + var isProxyHttps = proxyScheme.toLowerCase() === "https"; + var proxyAgent = { + isHttps: isRequestHttps, + agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) + }; + return proxyAgent; +} +function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { + if (isRequestHttps && isProxyHttps) { + return tunnel.httpsOverHttps(tunnelOptions); + } + else if (isRequestHttps && !isProxyHttps) { + return tunnel.httpsOverHttp(tunnelOptions); + } + else if (!isRequestHttps && isProxyHttps) { + return tunnel.httpOverHttps(tunnelOptions); + } + else { + return tunnel.httpOverHttp(tunnelOptions); + } +} + +// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved. (function (HttpPipelineLogLevel) { @@ -5777,6 +4663,49 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO"; })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {})); +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * A static-key-based credential that supports updating + * the underlying key value. + */ +var AzureKeyCredential = /** @class */ (function () { + /** + * Create an instance of an AzureKeyCredential for use + * with a service client. + * + * @param key - The initial value of the key to use in authentication + */ + function AzureKeyCredential(key) { + if (!key) { + throw new Error("key must be a non-empty string"); + } + this._key = key; + } + Object.defineProperty(AzureKeyCredential.prototype, "key", { + /** + * The value of the key to be used in authentication + */ + get: function () { + return this._key; + }, + enumerable: false, + configurable: true + }); + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey - The new key value to be used + */ + AzureKeyCredential.prototype.update = function (newKey) { + this._key = newKey; + }; + return AzureKeyCredential; +}()); + // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** @@ -5796,6 +4725,8 @@ function isTokenCredential(credential) { (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); } +// Copyright (c) Microsoft Corporation. + // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. /** @@ -5825,8 +4756,7 @@ function isStreamOperation(operationSpec) { var result = false; for (var statusCode in operationSpec.responses) { var operationResponse = operationSpec.responses[statusCode]; - if (operationResponse.bodyMapper && - operationResponse.bodyMapper.type.name === MapperType.Stream) { + if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { result = true; break; } @@ -5837,10 +4767,12 @@ function isStreamOperation(operationSpec) { // Copyright (c) Microsoft Corporation. All rights reserved. function stringifyXML(obj, opts) { var builder = new xml2js.Builder({ + explicitArray: false, + explicitCharkey: false, rootName: (opts || {}).rootName, renderOpts: { - pretty: false, - }, + pretty: false + } }); return builder.buildObject(obj); } @@ -5848,7 +4780,7 @@ function parseXML(str) { var xmlParser = new xml2js.Parser({ explicitArray: false, explicitCharkey: false, - explicitRoot: false, + explicitRoot: false }); return new Promise(function (resolve, reject) { if (!str) { @@ -5905,9 +4837,9 @@ var RequestPolicyOptions = /** @class */ (function () { * @returns Whether or not a log with the provided log level should be logged. */ RequestPolicyOptions.prototype.shouldLog = function (logLevel) { - return (!!this._logger && + return !!this._logger && logLevel !== exports.HttpPipelineLogLevel.OFF && - logLevel <= this._logger.minimumLogLevel); + logLevel <= this._logger.minimumLogLevel; }; /** * Attempt to log the provided message to the provided logger. If no logger was provided or if @@ -5932,7 +4864,7 @@ function deserializationPolicy(deserializationContentTypes) { return { create: function (nextPolicy, options) { return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options); - }, + } }; } var defaultJsonContentTypes = ["application/json", "text/json"]; @@ -5945,21 +4877,15 @@ var DeserializationPolicy = /** @class */ (function (_super) { tslib.__extends(DeserializationPolicy, _super); function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) { var _this = _super.call(this, nextPolicy, options) || this; - _this.jsonContentTypes = - (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; - _this.xmlContentTypes = - (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; + _this.jsonContentTypes = deserializationContentTypes && deserializationContentTypes.json || defaultJsonContentTypes; + _this.xmlContentTypes = deserializationContentTypes && deserializationContentTypes.xml || defaultXmlContentTypes; return _this; } DeserializationPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { var _this = this; return tslib.__generator(this, function (_a) { - return [2 /*return*/, this._nextPolicy - .sendRequest(request) - .then(function (response) { - return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); - })]; + return [2 /*return*/, this._nextPolicy.sendRequest(request).then(function (response) { return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); })]; }); }); }; @@ -6002,12 +4928,9 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { if (operationSpec && operationSpec.responses) { var statusCode = parsedResponse.status; var expectedStatusCodes = Object.keys(operationSpec.responses); - var hasNoExpectedStatusCodes = expectedStatusCodes.length === 0 || - (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"); + var hasNoExpectedStatusCodes = (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); var responseSpec = getOperationResponse(parsedResponse); - var isExpectedStatusCode = hasNoExpectedStatusCodes - ? 200 <= statusCode && statusCode < 300 - : !!responseSpec; + var isExpectedStatusCode = hasNoExpectedStatusCodes ? (200 <= statusCode && statusCode < 300) : !!responseSpec; if (!isExpectedStatusCode) { var defaultResponseSpec = operationSpec.responses.default; if (defaultResponseSpec) { @@ -6022,8 +4945,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { try { if (parsedErrorResponse) { var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper; - if (defaultResponseBodyMapper && - defaultResponseBodyMapper.serializedName === "CloudError") { + if (defaultResponseBodyMapper && defaultResponseBodyMapper.serializedName === "CloudError") { if (parsedErrorResponse.error) { parsedErrorResponse = parsedErrorResponse.error; } @@ -6046,12 +4968,10 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { } if (defaultResponseBodyMapper) { var valueToDeserialize = parsedErrorResponse; - if (operationSpec.isXML && - defaultResponseBodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof parsedErrorResponse === "object" - ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName] - : []; + if (operationSpec.isXML && defaultResponseBodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = typeof parsedErrorResponse === "object" + ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName] + : []; } error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body"); } @@ -6067,10 +4987,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { if (responseSpec.bodyMapper) { var valueToDeserialize = parsedResponse.parsedBody; if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof valueToDeserialize === "object" - ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] - : []; + valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : []; } try { parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody"); @@ -6105,11 +5022,8 @@ function parse(jsonContentTypes, xmlContentTypes, operationResponse) { if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) { var text_1 = operationResponse.bodyAsText; var contentType = operationResponse.headers.get("Content-Type") || ""; - var contentComponents = !contentType - ? [] - : contentType.split(";").map(function (component) { return component.toLowerCase(); }); - if (contentComponents.length === 0 || - contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) { + var contentComponents = !contentType ? [] : contentType.split(";").map(function (component) { return component.toLowerCase(); }); + if (contentComponents.length === 0 || contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) { return new Promise(function (resolve) { operationResponse.parsedBody = JSON.parse(text_1); resolve(operationResponse); @@ -6132,7 +5046,7 @@ function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, max return { create: function (nextPolicy, options) { return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); - }, + } }; } var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; @@ -6148,7 +5062,7 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { /** * @constructor * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain. - * @param {RequestPolicyOptionsLike} options The options for this RequestPolicy. + * @param {RequestPolicyOptions} options The options for this RequestPolicy. * @param {number} [retryCount] The client retry count. * @param {number} [retryInterval] The client retry interval, in milliseconds. * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds. @@ -6156,23 +5070,16 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { */ function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { var _this = _super.call(this, nextPolicy, options) || this; - function isNumber(n) { - return typeof n === "number"; - } + function isNumber(n) { return typeof n === "number"; } _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - _this.minRetryInterval = isNumber(minRetryInterval) - ? minRetryInterval - : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - _this.maxRetryInterval = isNumber(maxRetryInterval) - ? maxRetryInterval - : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + _this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; + _this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; return _this; } ExponentialRetryPolicy.prototype.sendRequest = function (request) { var _this = this; - return this._nextPolicy - .sendRequest(request.clone()) + return this._nextPolicy.sendRequest(request.clone()) .then(function (response) { return retry(_this, request, response); }) .catch(function (error) { return retry(_this, request, error.response, undefined, error); }); }; @@ -6187,10 +5094,7 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { * @return {boolean} True if the operation qualifies for a retry; false otherwise. */ function shouldRetry(policy, statusCode, retryData) { - if (statusCode == undefined || - (statusCode < 500 && statusCode !== 408) || - statusCode === 501 || - statusCode === 505) { + if (statusCode == undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) { return false; } var currentCount; @@ -6198,9 +5102,9 @@ function shouldRetry(policy, statusCode, retryData) { throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null."); } else { - currentCount = retryData && retryData.retryCount; + currentCount = (retryData && retryData.retryCount); } - return currentCount < policy.retryCount; + return (currentCount < policy.retryCount); } /** * Updates the retry data for the next attempt. @@ -6213,7 +5117,7 @@ function updateRetryData(policy, retryData, err) { if (!retryData) { retryData = { retryCount: 0, - retryInterval: 0, + retryInterval: 0 }; } if (err) { @@ -6258,7 +5162,7 @@ function generateClientRequestIdPolicy(requestIdHeaderName) { return { create: function (nextPolicy, options) { return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); - }, + } }; } var GenerateClientRequestIdPolicy = /** @class */ (function (_super) { @@ -6284,11 +5188,11 @@ function getDefaultUserAgentKey() { function getPlatformSpecificData() { var runtimeInfo = { key: "Node", - value: process.version, + value: process.version }; var osInfo = { key: "OS", - value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")", + value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")" }; return [runtimeInfo, osInfo]; } @@ -6297,19 +5201,17 @@ function getPlatformSpecificData() { function getRuntimeInfo() { var msRestRuntime = { key: "ms-rest-js", - value: Constants.msRestVersion, + value: Constants.msRestVersion }; return [msRestRuntime]; } function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) { if (keySeparator === void 0) { keySeparator = " "; } if (valueSeparator === void 0) { valueSeparator = "/"; } - return telemetryInfo - .map(function (info) { + return telemetryInfo.map(function (info) { var value = info.value ? "" + valueSeparator + info.value : ""; return "" + info.key + value; - }) - .join(keySeparator); + }).join(keySeparator); } var getDefaultUserAgentHeaderName = getDefaultUserAgentKey; function getDefaultUserAgentValue() { @@ -6319,14 +5221,12 @@ function getDefaultUserAgentValue() { return userAgent; } function userAgentPolicy(userAgentData) { - var key = !userAgentData || userAgentData.key == undefined ? getDefaultUserAgentKey() : userAgentData.key; - var value = !userAgentData || userAgentData.value == undefined - ? getDefaultUserAgentValue() - : userAgentData.value; + var key = (!userAgentData || userAgentData.key == undefined) ? getDefaultUserAgentKey() : userAgentData.key; + var value = (!userAgentData || userAgentData.value == undefined) ? getDefaultUserAgentValue() : userAgentData.value; return { create: function (nextPolicy, options) { return new UserAgentPolicy(nextPolicy, options, key, value); - }, + } }; } var UserAgentPolicy = /** @class */ (function (_super) { @@ -6355,16 +5255,12 @@ var UserAgentPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); // Copyright (c) Microsoft Corporation. All rights reserved. -var DefaultRedirectOptions = { - handleRedirects: true, - maxRetries: 20, -}; function redirectPolicy(maximumRetries) { if (maximumRetries === void 0) { maximumRetries = 20; } return { create: function (nextPolicy, options) { return new RedirectPolicy(nextPolicy, options, maximumRetries); - }, + } }; } var RedirectPolicy = /** @class */ (function (_super) { @@ -6377,9 +5273,7 @@ var RedirectPolicy = /** @class */ (function (_super) { } RedirectPolicy.prototype.sendRequest = function (request) { var _this = this; - return this._nextPolicy - .sendRequest(request) - .then(function (response) { return handleRedirect(_this, response, 0); }); + return this._nextPolicy.sendRequest(request).then(function (response) { return handleRedirect(_this, response, 0); }); }; return RedirectPolicy; }(BaseRequestPolicy)); @@ -6387,46 +5281,28 @@ function handleRedirect(policy, response, currentRetries) { var request = response.request, status = response.status; var locationHeader = response.headers.get("location"); if (locationHeader && - (status === 300 || - (status === 301 && ["GET", "HEAD"].includes(request.method)) || - (status === 302 && ["GET", "POST", "HEAD"].includes(request.method)) || - (status === 303 && "POST" === request.method) || - status === 307) && - ((request.redirectLimit !== undefined && currentRetries < request.redirectLimit) || - (request.redirectLimit === undefined && currentRetries < policy.maxRetries))) { + (status === 300 || status === 307 || (status === 303 && request.method === "POST")) && + (!policy.maxRetries || currentRetries < policy.maxRetries)) { var builder = URLBuilder.parse(request.url); builder.setPath(locationHeader); request.url = builder.toString(); - // POST request with Status code 302 and 303 should be converted into a + // POST request with Status code 303 should be converted into a // redirected GET request if the redirect url is present in the location header - // reference: https://tools.ietf.org/html/rfc7231#page-57 && https://fetch.spec.whatwg.org/#http-redirect-fetch - if ((status === 302 || status === 303) && request.method === "POST") { + if (status === 303) { request.method = "GET"; - delete request.body; } - return policy._nextPolicy - .sendRequest(request) - .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); }) - .then(function (res) { return recordRedirect(res, request.url); }); + return policy._nextPolicy.sendRequest(request) + .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); }); } return Promise.resolve(response); } -function recordRedirect(response, redirect) { - // This is called as the recursive calls to handleRedirect() unwind, - // only record the deepest/last redirect - if (!response.redirected) { - response.redirected = true; - response.url = redirect; - } - return response; -} function rpRegistrationPolicy(retryTimeout) { if (retryTimeout === void 0) { retryTimeout = 30; } return { create: function (nextPolicy, options) { return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); - }, + } }; } var RPRegistrationPolicy = /** @class */ (function (_super) { @@ -6439,8 +5315,7 @@ var RPRegistrationPolicy = /** @class */ (function (_super) { } RPRegistrationPolicy.prototype.sendRequest = function (request) { var _this = this; - return this._nextPolicy - .sendRequest(request.clone()) + return this._nextPolicy.sendRequest(request.clone()) .then(function (response) { return registerIfNeeded(_this, request, response); }); }; return RPRegistrationPolicy; @@ -6450,7 +5325,7 @@ function registerIfNeeded(policy, request, response) { var rpName = checkRPNotRegisteredError(response.bodyAsText); if (rpName) { var urlPrefix = extractSubscriptionUrl(request.url); - return (registerRP(policy, urlPrefix, rpName, request) + return registerRP(policy, urlPrefix, rpName, request) // Autoregistration of ${provider} failed for some reason. We will not return this error // instead will return the initial response with 409 status code back to the user. // do nothing here as we are returning the original response at the end of this method. @@ -6463,14 +5338,14 @@ function registerIfNeeded(policy, request, response) { return policy._nextPolicy.sendRequest(request.clone()); } return response; - })); + }); } } return Promise.resolve(response); } /** * Reuses the headers of the original request and url (if specified). - * @param {WebResourceLike} originalRequest The original request + * @param {WebResource} originalRequest The original request * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false. * @returns {object} A new request object with desired headers. */ @@ -6502,11 +5377,8 @@ function checkRPNotRegisteredError(body) { catch (err) { // do nothing; } - if (responseBody && - responseBody.error && - responseBody.error.message && - responseBody.error.code && - responseBody.error.code === "MissingSubscriptionRegistration") { + if (responseBody && responseBody.error && responseBody.error.message && + responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") { var matchRes = responseBody.error.message.match(/.*'(.*)'/i); if (matchRes) { result = matchRes.pop(); @@ -6523,7 +5395,7 @@ function checkRPNotRegisteredError(body) { */ function extractSubscriptionUrl(url) { var result; - var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); + var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//ig); if (matchRes && matchRes[0]) { result = matchRes[0]; } @@ -6537,7 +5409,7 @@ function extractSubscriptionUrl(url) { * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ * @param {string} provider The provider name to be registered. - * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response + * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response * with a message that the provider is not registered. * @param {registrationCallback} callback The callback that handles the RP registration */ @@ -6547,7 +5419,8 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { var reqOptions = getRequestEssentials(originalRequest); reqOptions.method = "POST"; reqOptions.url = postUrl; - return policy._nextPolicy.sendRequest(reqOptions).then(function (response) { + return policy._nextPolicy.sendRequest(reqOptions) + .then(function (response) { if (response.status !== 200) { throw new Error("Autoregistration of " + provider + " failed. Please try registering manually."); } @@ -6559,7 +5432,7 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { * Polling will happen till the registrationState property of the response body is "Registered". * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. * @param {string} url The request url for polling - * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response + * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response * with a message that the provider is not registered. * @returns {Promise} True if RP Registration is successful. */ @@ -6573,8 +5446,7 @@ function getRegistrationStatus(policy, url, originalRequest) { return true; } else { - return delay(policy._retryTimeout * 1000) - .then(function () { return getRegistrationStatus(policy, url, originalRequest); }); + return delay(policy._retryTimeout * 1000).then(function () { return getRegistrationStatus(policy, url, originalRequest); }); } }); } @@ -6584,7 +5456,7 @@ function signingPolicy(authenticationProvider) { return { create: function (nextPolicy, options) { return new SigningPolicy(nextPolicy, options, authenticationProvider); - }, + } }; } var SigningPolicy = /** @class */ (function (_super) { @@ -6599,9 +5471,7 @@ var SigningPolicy = /** @class */ (function (_super) { }; SigningPolicy.prototype.sendRequest = function (request) { var _this = this; - return this.signRequest(request).then(function (nextRequest) { - return _this._nextPolicy.sendRequest(nextRequest); - }); + return this.signRequest(request).then(function (nextRequest) { return _this._nextPolicy.sendRequest(nextRequest); }); }; return SigningPolicy; }(BaseRequestPolicy)); @@ -6611,7 +5481,7 @@ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, max return { create: function (nextPolicy, options) { return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); - }, + } }; } /** @@ -6633,23 +5503,14 @@ var SystemErrorRetryPolicy = /** @class */ (function (_super) { _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT; - _this.retryInterval = - typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL; - _this.minRetryInterval = - typeof minRetryInterval === "number" - ? minRetryInterval - : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - _this.maxRetryInterval = - typeof maxRetryInterval === "number" - ? maxRetryInterval - : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + _this.retryInterval = typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL; + _this.minRetryInterval = typeof minRetryInterval === "number" ? minRetryInterval : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL; + _this.maxRetryInterval = typeof maxRetryInterval === "number" ? maxRetryInterval : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL; return _this; } SystemErrorRetryPolicy.prototype.sendRequest = function (request) { var _this = this; - return this._nextPolicy - .sendRequest(request.clone()) - .catch(function (error) { return retry$1(_this, request, error.response, error); }); + return this._nextPolicy.sendRequest(request.clone()).then(function (response) { return retry$1(_this, request, response); }); }; return SystemErrorRetryPolicy; }(BaseRequestPolicy)); @@ -6666,9 +5527,9 @@ function shouldRetry$1(policy, retryData) { throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null."); } else { - currentCount = retryData && retryData.retryCount; + currentCount = (retryData && retryData.retryCount); } - return currentCount < policy.retryCount; + return (currentCount < policy.retryCount); } /** * Updates the retry data for the next attempt. @@ -6680,7 +5541,7 @@ function updateRetryData$1(policy, retryData, err) { if (!retryData) { retryData = { retryCount: 0, - retryInterval: 0, + retryInterval: 0 }; } if (err) { @@ -6693,47 +5554,31 @@ function updateRetryData$1(policy, retryData, err) { retryData.retryCount++; // Adjust retry interval var incrementDelta = Math.pow(2, retryData.retryCount) - 1; - var boundedRandDelta = policy.retryInterval * 0.8 + Math.floor(Math.random() * (policy.retryInterval * 0.4)); + var boundedRandDelta = policy.retryInterval * 0.8 + + Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8)); incrementDelta *= boundedRandDelta; retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval); return retryData; } -function retry$1(policy, request, operationResponse, err, retryData) { - return tslib.__awaiter(this, void 0, void 0, function () { - var error_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - retryData = updateRetryData$1(policy, retryData, err); - if (!(err && - err.code && - shouldRetry$1(policy, retryData) && - (err.code === "ETIMEDOUT" || - err.code === "ESOCKETTIMEDOUT" || - err.code === "ECONNREFUSED" || - err.code === "ECONNRESET" || - err.code === "ENOENT"))) return [3 /*break*/, 5]; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, delay(retryData.retryInterval)]; - case 2: - _a.sent(); - return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())]; - case 3: - error_1 = _a.sent(); - return [2 /*return*/, retry$1(policy, request, operationResponse, error_1, retryData)]; - case 4: return [3 /*break*/, 6]; - case 5: - if (err) { - // If the operation failed in the end, return all errors instead of just the last one - return [2 /*return*/, Promise.reject(retryData.error)]; - } - return [2 /*return*/, operationResponse]; - case 6: return [2 /*return*/]; - } - }); - }); +function retry$1(policy, request, operationResponse, retryData, err) { + retryData = updateRetryData$1(policy, retryData, err); + if (err && err.code && shouldRetry$1(policy, retryData) && + (err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || + err.code === "ECONNRESET" || err.code === "ENOENT")) { + // If previous operation ended with an error and the policy allows a retry, do that + return delay(retryData.retryInterval) + .then(function () { return policy._nextPolicy.sendRequest(request.clone()); }) + .then(function (res) { return retry$1(policy, request, res, retryData, err); }) + .catch(function (err) { return retry$1(policy, request, operationResponse, retryData, err); }); + } + else { + if (err != undefined) { + // If the operation failed in the end, return all errors instead of just the last one + err = retryData.error; + return Promise.reject(err); + } + return Promise.resolve(operationResponse); + } } // Copyright (c) Microsoft Corporation. All rights reserved. @@ -6750,7 +5595,7 @@ function agentPolicy(agentSettings) { return { create: function (nextPolicy, options) { return new AgentPolicy(nextPolicy, options, agentSettings); - }, + } }; } var AgentPolicy = /** @class */ (function (_super) { @@ -6770,101 +5615,23 @@ var AgentPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); // Copyright (c) Microsoft Corporation. All rights reserved. -/** - * @internal - */ -var noProxyList = loadNoProxy(); -var byPassedList = new Map(); -/** - * @internal - */ -function getEnvironmentValue(name) { - if (process.env[name]) { - return process.env[name]; - } - else if (process.env[name.toLowerCase()]) { - return process.env[name.toLowerCase()]; - } - return undefined; -} function loadEnvironmentProxyValue() { if (!process) { return undefined; } - var httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); - var allProxy = getEnvironmentValue(Constants.ALL_PROXY); - var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; -} -// Check whether the host of a given `uri` is in the noProxyList. -// If there's a match, any request sent to the same host won't have the proxy settings set. -// This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 -function isBypassed(uri) { - if (noProxyList.length === 0) { - return false; - } - var host = URLBuilder.parse(uri).getHost(); - if (byPassedList.has(host)) { - return byPassedList.get(host); + if (process.env[Constants.HTTPS_PROXY]) { + return process.env[Constants.HTTPS_PROXY]; } - var isBypassedFlag = false; - for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) { - var pattern = noProxyList_1[_i]; - if (pattern[0] === ".") { - // This should match either domain it self or any subdomain or host - // .foo.com will match foo.com it self or *.foo.com - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } - else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } - } - } - else { - if (host === pattern) { - isBypassedFlag = true; - } - } + else if (process.env[Constants.HTTPS_PROXY.toLowerCase()]) { + return process.env[Constants.HTTPS_PROXY.toLowerCase()]; } - byPassedList.set(host, isBypassedFlag); - return isBypassedFlag; -} -/** - * @internal - */ -function loadNoProxy() { - var noProxy = getEnvironmentValue(Constants.NO_PROXY); - if (noProxy) { - return noProxy - .split(",") - .map(function (item) { return item.trim(); }) - .filter(function (item) { return item.length; }); + else if (process.env[Constants.HTTP_PROXY]) { + return process.env[Constants.HTTP_PROXY]; } - return []; -} -/** - * @internal - */ -function extractAuthFromUrl(url) { - var atIndex = url.indexOf("@"); - if (atIndex === -1) { - return { urlWithoutAuth: url }; + else if (process.env[Constants.HTTP_PROXY.toLowerCase()]) { + return process.env[Constants.HTTP_PROXY.toLowerCase()]; } - var schemeIndex = url.indexOf("://"); - var authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; - var auth = url.substring(authStart, atIndex); - var colonIndex = auth.indexOf(":"); - var hasPassword = colonIndex !== -1; - var username = hasPassword ? auth.substring(0, colonIndex) : auth; - var password = hasPassword ? auth.substring(colonIndex + 1) : undefined; - var urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); - return { - username: username, - password: password, - urlWithoutAuth: urlWithoutAuth, - }; + return undefined; } function getDefaultProxySettings(proxyUrl) { if (!proxyUrl) { @@ -6873,24 +5640,17 @@ function getDefaultProxySettings(proxyUrl) { return undefined; } } - var _a = extractAuthFromUrl(proxyUrl), username = _a.username, password = _a.password, urlWithoutAuth = _a.urlWithoutAuth; - var parsedUrl = URLBuilder.parse(urlWithoutAuth); - var schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; + var parsedUrl = URLBuilder.parse(proxyUrl); return { - host: schema + parsedUrl.getHost(), - port: Number.parseInt(parsedUrl.getPort() || "80"), - username: username, - password: password, + host: parsedUrl.getScheme() + "://" + parsedUrl.getHost(), + port: Number.parseInt(parsedUrl.getPort() || "80") }; } function proxyPolicy(proxySettings) { - if (!proxySettings) { - proxySettings = getDefaultProxySettings(); - } return { create: function (nextPolicy, options) { return new ProxyPolicy(nextPolicy, options, proxySettings); - }, + } }; } var ProxyPolicy = /** @class */ (function (_super) { @@ -6901,7 +5661,7 @@ var ProxyPolicy = /** @class */ (function (_super) { return _this; } ProxyPolicy.prototype.sendRequest = function (request) { - if (!request.proxySettings && !isBypassed(request.url)) { + if (!request.proxySettings) { request.proxySettings = this.proxySettings; } return this._nextPolicy.sendRequest(request); @@ -6911,13 +5671,11 @@ var ProxyPolicy = /** @class */ (function (_super) { // Copyright (c) Microsoft Corporation. All rights reserved. var StatusCodes = Constants.HttpConstants.StatusCodes; -var DEFAULT_RETRY_COUNT = 3; -function throttlingRetryPolicy(maxRetries) { - if (maxRetries === void 0) { maxRetries = DEFAULT_RETRY_COUNT; } +function throttlingRetryPolicy() { return { create: function (nextPolicy, options) { - return new ThrottlingRetryPolicy(nextPolicy, options, maxRetries); - }, + return new ThrottlingRetryPolicy(nextPolicy, options); + } }; } /** @@ -6928,9 +5686,9 @@ function throttlingRetryPolicy(maxRetries) { */ var ThrottlingRetryPolicy = /** @class */ (function (_super) { tslib.__extends(ThrottlingRetryPolicy, _super); - function ThrottlingRetryPolicy(nextPolicy, options, retryLimit) { + function ThrottlingRetryPolicy(nextPolicy, options, _handleResponse) { var _this = _super.call(this, nextPolicy, options) || this; - _this.retryLimit = retryLimit; + _this._handleResponse = _handleResponse || _this._defaultResponseHandler; return _this; } ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) { @@ -6938,33 +5696,29 @@ var ThrottlingRetryPolicy = /** @class */ (function (_super) { var _this = this; return tslib.__generator(this, function (_a) { return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) { - return _this.retry(httpRequest, response, 0); + if (response.status !== StatusCodes.TooManyRequests) { + return response; + } + else { + return _this._handleResponse(httpRequest, response); + } })]; }); }); }; - ThrottlingRetryPolicy.prototype.retry = function (httpRequest, httpResponse, retryCount) { + ThrottlingRetryPolicy.prototype._defaultResponseHandler = function (httpRequest, httpResponse) { return tslib.__awaiter(this, void 0, void 0, function () { - var retryAfterHeader, delayInMs, res; + var retryAfterHeader, delayInMs; + var _this = this; return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (httpResponse.status !== StatusCodes.TooManyRequests) { - return [2 /*return*/, httpResponse]; - } - retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); - if (!(retryAfterHeader && retryCount < this.retryLimit)) return [3 /*break*/, 3]; - delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); - if (!delayInMs) return [3 /*break*/, 3]; - return [4 /*yield*/, delay(delayInMs)]; - case 1: - _a.sent(); - return [4 /*yield*/, this._nextPolicy.sendRequest(httpRequest)]; - case 2: - res = _a.sent(); - return [2 /*return*/, this.retry(httpRequest, res, retryCount + 1)]; - case 3: return [2 /*return*/, httpResponse]; + retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); + if (retryAfterHeader) { + delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); + if (delayInMs) { + return [2 /*return*/, delay(delayInMs).then(function (_) { return _this._nextPolicy.sendRequest(httpRequest); })]; + } } + return [2 /*return*/, httpResponse]; }); }); }; @@ -7022,6 +5776,7 @@ var AzureIdentityCredentialAdapter = /** @class */ (function () { else { throw new Error("Could find token for scope"); } + return [2 /*return*/]; } }); }); @@ -7070,7 +5825,7 @@ var ServiceClient = /** @class */ (function () { throw new Error("credentials argument needs to implement signRequest method"); } this._withCredentials = options.withCredentials || false; - this._httpClient = options.httpClient || new NodeFetchHttpClient(); + this._httpClient = options.httpClient || new AxiosHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); var requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { @@ -7096,7 +5851,7 @@ var ServiceClient = /** @class */ (function () { } var httpRequest; try { - if (isWebResourceLike(options)) { + if (options instanceof WebResource) { options.validateRequestProperties(); httpRequest = options; } @@ -7169,30 +5924,20 @@ var ServiceClient = /** @class */ (function () { } } } - else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || - queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { + else { queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); } } if (!queryParameter.skipEncoding) { if (Array.isArray(queryParameterValue)) { for (var index in queryParameterValue) { - if (queryParameterValue[index] !== undefined && - queryParameterValue[index] !== null) { - queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); - } + queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); } } else { queryParameterValue = encodeURIComponent(queryParameterValue); } } - if (queryParameter.collectionFormat != undefined && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { - queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); - } requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); } } @@ -7208,8 +5953,7 @@ var ServiceClient = /** @class */ (function () { var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); if (headerValue != undefined) { headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter)); - var headerCollectionPrefix = headerParameter.mapper - .headerCollectionPrefix; + var headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix; if (headerCollectionPrefix) { for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) { var key = _g[_f]; @@ -7217,8 +5961,7 @@ var ServiceClient = /** @class */ (function () { } } else { - httpRequest.headers.set(headerParameter.mapper.serializedName || - getPathStringFromParameter(headerParameter), headerValue); + httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue); } } } @@ -7248,9 +5991,8 @@ var ServiceClient = /** @class */ (function () { if (httpRequest.streamResponseBody == undefined) { httpRequest.streamResponseBody = isStreamOperation(operationSpec); } - result = this.sendRequest(httpRequest).then(function (res) { - return flattenResponse(res, operationSpec.responses[res.status]); - }); + result = this.sendRequest(httpRequest) + .then(function (res) { return flattenResponse(res, operationSpec.responses[res.status]); }); } catch (error) { result = Promise.reject(error); @@ -7282,9 +6024,7 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName }); } else if (!isStream) { - httpRequest.body = stringifyXML(httpRequest.body, { - rootName: xmlName || serializedName, - }); + httpRequest.body = stringifyXML(httpRequest.body, { rootName: xmlName || serializedName }); } } else if (!isStream) { @@ -7342,10 +6082,7 @@ function createDefaultRequestPolicyFactories(credentials, options) { if (userAgentHeaderName && userAgentHeaderValue) { factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue })); } - var redirectOptions = tslib.__assign(tslib.__assign({}, DefaultRedirectOptions), options.redirectOptions); - if (redirectOptions.handleRedirects) { - factories.push(redirectPolicy(redirectOptions.maxRetries)); - } + factories.push(redirectPolicy()); factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout)); if (!options.noRetryPolicy) { factories.push(exponentialRetryPolicy()); @@ -7382,9 +6119,7 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu } var useDefaultValue = false; if (!propertySearchResult.propertyFound) { - useDefaultValue = - parameterMapper.required || - (parameterPath[0] === "options" && parameterPath.length === 2); + useDefaultValue = parameterMapper.required || (parameterPath[0] === "options" && parameterPath.length === 2); } value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; } @@ -7438,7 +6173,7 @@ function flattenResponse(_response, responseSpec) { var bodyMapper = responseSpec && responseSpec.bodyMapper; var addOperationResponse = function (obj) { return Object.defineProperty(obj, "_response", { - value: _response, + value: _response }); }; if (bodyMapper) { @@ -7446,12 +6181,14 @@ function flattenResponse(_response, responseSpec) { if (typeName === "Stream") { return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); } - var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; + var modelProperties_1 = typeName === "Composite" && bodyMapper.type.modelProperties || {}; var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; }); if (typeName === "Sequence" || isPageableResponse) { - // We're expecting a sequece(array) make sure that the response body is in the + // We're expecting a sequence(array) make sure that the response body is in the // correct format, if not make it an empty array [] - var parsedBody = Array.isArray(_response.parsedBody) ? _response.parsedBody : []; + var parsedBody = Array.isArray(_response.parsedBody) + ? _response.parsedBody + : []; var arrayResponse = tslib.__spreadArrays(parsedBody); for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) { var key = _a[_i]; @@ -7472,9 +6209,7 @@ function flattenResponse(_response, responseSpec) { return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody)); } } - if (bodyMapper || - _response.request.method === "HEAD" || - isPrimitiveType(_response.parsedBody)) { + if (bodyMapper || _response.request.method === "HEAD") { // primitive body types and HEAD booleans return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { body: _response.parsedBody })); } @@ -7487,7 +6222,7 @@ function logPolicy(logger) { return { create: function (nextPolicy, options) { return new LogPolicy(nextPolicy, options, logger); - }, + } }; } var LogPolicy = /** @class */ (function (_super) { @@ -7538,8 +6273,8 @@ var TokenCredentials = /** @class */ (function () { /** * Signs a request with the Authentication header. * - * @param {WebResourceLike} webResource The WebResourceLike to be signed. - * @return {Promise} The signed request object. + * @param {WebResource} webResource The WebResource to be signed. + * @return {Promise} The signed request object. */ TokenCredentials.prototype.signRequest = function (webResource) { if (!webResource.headers) @@ -7578,8 +6313,8 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Signs a request with the Authentication header. * - * @param {WebResourceLike} webResource The WebResourceLike to be signed. - * @returns {Promise} The signed request object. + * @param {WebResource} webResource The WebResource to be signed. + * @returns {Promise} The signed request object. */ BasicAuthenticationCredentials.prototype.signRequest = function (webResource) { var credentials = this.userName + ":" + this.password; @@ -7661,8 +6396,8 @@ var TopicCredentials = /** @class */ (function (_super) { } var options = { inHeader: { - "aeg-sas-key": topicKey, - }, + "aeg-sas-key": topicKey + } }; _this = _super.call(this, options) || this; return _this; @@ -7686,8 +6421,8 @@ var DomainCredentials = /** @class */ (function (_super) { } var options = { inHeader: { - "aeg-sas-key": domainKey, - }, + "aeg-sas-key": domainKey + } }; _this = _super.call(this, options) || this; return _this; @@ -7695,562 +6430,55 @@ var DomainCredentials = /** @class */ (function (_super) { return DomainCredentials; }(ApiKeyCredentials)); -exports.ApiKeyCredentials = ApiKeyCredentials; -exports.AzureIdentityCredentialAdapter = AzureIdentityCredentialAdapter; -exports.BaseRequestPolicy = BaseRequestPolicy; -exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials; -exports.Constants = Constants; -exports.DefaultHttpClient = NodeFetchHttpClient; -exports.DomainCredentials = DomainCredentials; +// Copyright (c) Microsoft Corporation. All rights reserved. + +exports.WebResource = WebResource; +exports.DefaultHttpClient = AxiosHttpClient; exports.HttpHeaders = HttpHeaders; -exports.MapperType = MapperType; -exports.RequestPolicyOptions = RequestPolicyOptions; exports.RestError = RestError; -exports.Serializer = Serializer; exports.ServiceClient = ServiceClient; -exports.TokenCredentials = TokenCredentials; -exports.TopicCredentials = TopicCredentials; -exports.URLBuilder = URLBuilder; -exports.URLQuery = URLQuery; -exports.WebResource = WebResource; -exports.agentPolicy = agentPolicy; -exports.applyMixins = applyMixins; -exports.delay = delay; -exports.deserializationPolicy = deserializationPolicy; -exports.deserializeResponseBody = deserializeResponseBody; -exports.encodeUri = encodeUri; -exports.executePromisesSequentially = executePromisesSequentially; -exports.exponentialRetryPolicy = exponentialRetryPolicy; exports.flattenResponse = flattenResponse; +exports.Constants = Constants; +exports.logPolicy = logPolicy; +exports.BaseRequestPolicy = BaseRequestPolicy; +exports.RequestPolicyOptions = RequestPolicyOptions; exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy; -exports.generateUuid = generateUuid; +exports.exponentialRetryPolicy = exponentialRetryPolicy; +exports.systemErrorRetryPolicy = systemErrorRetryPolicy; +exports.throttlingRetryPolicy = throttlingRetryPolicy; exports.getDefaultProxySettings = getDefaultProxySettings; -exports.getDefaultUserAgentValue = getDefaultUserAgentValue; -exports.isDuration = isDuration; -exports.isNode = isNode; -exports.isValidUuid = isValidUuid; -exports.logPolicy = logPolicy; -exports.promiseToCallback = promiseToCallback; -exports.promiseToServiceCallback = promiseToServiceCallback; exports.proxyPolicy = proxyPolicy; exports.redirectPolicy = redirectPolicy; -exports.serializeObject = serializeObject; exports.signingPolicy = signingPolicy; +exports.userAgentPolicy = userAgentPolicy; +exports.getDefaultUserAgentValue = getDefaultUserAgentValue; +exports.deserializationPolicy = deserializationPolicy; +exports.deserializeResponseBody = deserializeResponseBody; +exports.MapperType = MapperType; +exports.Serializer = Serializer; +exports.serializeObject = serializeObject; exports.stripRequest = stripRequest; exports.stripResponse = stripResponse; -exports.systemErrorRetryPolicy = systemErrorRetryPolicy; -exports.throttlingRetryPolicy = throttlingRetryPolicy; -exports.userAgentPolicy = userAgentPolicy; +exports.delay = delay; +exports.executePromisesSequentially = executePromisesSequentially; +exports.generateUuid = generateUuid; +exports.encodeUri = encodeUri; +exports.promiseToCallback = promiseToCallback; +exports.promiseToServiceCallback = promiseToServiceCallback; +exports.isValidUuid = isValidUuid; +exports.applyMixins = applyMixins; +exports.isNode = isNode; +exports.isDuration = isDuration; +exports.URLBuilder = URLBuilder; +exports.URLQuery = URLQuery; +exports.TokenCredentials = TokenCredentials; +exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials; +exports.ApiKeyCredentials = ApiKeyCredentials; +exports.TopicCredentials = TopicCredentials; +exports.DomainCredentials = DomainCredentials; //# sourceMappingURL=msRest.node.js.map -/***/ }), - -/***/ 69970: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var CombinedStream = __nccwpck_require__(85443); -var util = __nccwpck_require__(31669); -var path = __nccwpck_require__(85622); -var http = __nccwpck_require__(98605); -var https = __nccwpck_require__(57211); -var parseUrl = __nccwpck_require__(78835).parse; -var fs = __nccwpck_require__(35747); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var populate = __nccwpck_require__(53647); - -// Public API -module.exports = FormData; - -// make it a Stream -util.inherits(FormData, CombinedStream); - -/** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream - */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - - CombinedStream.call(this); - - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } -} - -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - -FormData.prototype.append = function(field, value, options) { - - options = options || {}; - - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } - - var append = CombinedStream.prototype.append.bind(this); - - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } - - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; - } - - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - - append(header); - append(value); - append(footer); - - // pass along options.knownLength - this._trackLength(header, value, options); -}; - -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; - - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } - - this._valueLength += valueLength; - - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; - - // empty or either doesn't have path or not an http response - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { - return; - } - - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; - -FormData.prototype._lengthRetriever = function(value, callback) { - - if (value.hasOwnProperty('fd')) { - - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { - - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); - - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { - - var fileSize; - - if (err) { - callback(err); - return; - } - - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); - - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); - - // something else - } else { - callback('Unknown stream'); - } -}; - -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; - } - - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; - - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } - - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; - - // skip nullish headers. - if (header == null) { - continue; - } - - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } - - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } - } - - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; - -FormData.prototype._getContentDisposition = function(value, options) { - - var filename - , contentDisposition - ; - - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } - - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } - - return contentDisposition; -}; - -FormData.prototype._getContentType = function(value, options) { - - // use custom content-type above all - var contentType = options.contentType; - - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } - - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } - - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } - - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } - - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } - - return contentType; -}; - -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; - - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } - - next(footer); - }.bind(this); -}; - -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; - -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; - - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } - - return formHeaders; -}; - -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); - } - - return this._boundary; -}; - -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); - - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { - - // Add content to the buffer. - if(Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); - }else { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); - } - - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); - } - } - } - - // Add the footer and return the Buffer object. - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); -}; - -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } - - this._boundary = boundary; -}; - -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; - - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } - - return knownLength; -}; - -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; - - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } - - return hasKnownLength; -}; - -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; - - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } - - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; - } - - values.forEach(function(length) { - knownLength += length; - }); - - cb(null, knownLength); - }); -}; - -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; - - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { - - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); - - // use custom params - } else { - - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; - } - } - - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); - - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } - - // get content length and fire away - this.getLength(function(err, length) { - if (err) { - this._error(err); - return; - } - - // add content length - request.setHeader('Content-Length', length); - - this.pipe(request); - if (cb) { - request.on('error', cb); - request.on('response', cb.bind(this, null)); - } - }.bind(this)); - - return request; -}; - -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } -}; - -FormData.prototype.toString = function () { - return '[object FormData]'; -}; - - -/***/ }), - -/***/ 53647: -/***/ ((module) => { - -// populates missing values -module.exports = function(dst, src) { - - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); - - return dst; -}; - - /***/ }), /***/ 68930: @@ -8288,9 +6516,9 @@ module.exports = function(dst, src) { * POSSIBILITY OF SUCH DAMAGE. */ +var net = __nccwpck_require__(11631); var urlParse = __nccwpck_require__(78835).parse; var util = __nccwpck_require__(31669); -var ipRegex = __nccwpck_require__(29233)({ exact: true }); var pubsuffix = __nccwpck_require__(23005); var Store = __nccwpck_require__(5340)/* .Store */ .y; var MemoryCookieStore = __nccwpck_require__(96868)/* .MemoryCookieStore */ .m; @@ -8579,7 +6807,7 @@ function domainMatch(str, domStr, canonicalize) { /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ /* "* The string is a host name (i.e., not an IP address)." */ - if (ipRegex.test(str)) { + if (net.isIP(str)) { return false; } @@ -9266,17 +7494,11 @@ CookieJar.prototype.setCookie = function(cookie, url, options, cb) { } // S5.3 step 1 - if (typeof(cookie) === 'string' || cookie instanceof String) { + if (!(cookie instanceof Cookie)) { cookie = Cookie.parse(cookie, { loose: loose }); - if (!cookie) { - err = new Error("Cookie failed to parse"); - return cb(options.ignoreError ? null : err); - } } - else if (!(cookie instanceof Cookie)) { - // If you're seeing this error, and are passing in a Cookie object, - // it *might* be a Cookie object from another loaded version of tough-cookie. - err = new Error("First argument to setCookie must be a Cookie object or string"); + if (!cookie) { + err = new Error("Cookie failed to parse"); return cb(options.ignoreError ? null : err); } @@ -10204,7 +8426,7 @@ Store.prototype.getAllCookies = function(cb) { /***/ ((module) => { // generated by genversion -module.exports = '3.0.1' +module.exports = '2.5.0' /***/ }), @@ -10291,1199 +8513,6 @@ function v4(options, buf, offset) { module.exports = v4; -/***/ }), - -/***/ 2265: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __nccwpck_require__(35747); -const crypto_1 = __nccwpck_require__(76417); -const applicationTokenCredentialsBase_1 = __nccwpck_require__(60968); -const authConstants_1 = __nccwpck_require__(26700); -class ApplicationTokenCertificateCredentials extends applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase { - /** - * Creates a new ApplicationTokenCredentials object. - * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} - * for detailed instructions on creating an Azure Active Directory application. - * - * @param clientId - The active directory application client id. - * @param domain - The domain or tenant id containing this application. - * @param certificate - A PEM encoded certificate private key. - * @param thumbprint - A hex encoded thumbprint of the certificate. - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). - * @param environment - The azure environment to authenticate with. - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. - */ - constructor(clientId, domain, certificate, thumbprint, tokenAudience, environment, tokenCache) { - if (!certificate || typeof certificate.valueOf() !== "string") { - throw new Error("certificate must be a non empty string."); - } - if (!thumbprint || typeof thumbprint.valueOf() !== "string") { - throw new Error("thumbprint must be a non empty string."); - } - super(clientId, domain, tokenAudience, environment, tokenCache); - this.certificate = certificate; - this.thumbprint = thumbprint; - } - /** - * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL. - * @returns A promise that resolves to TokenResponse and rejects with an Error. - */ - getToken() { - return __awaiter(this, void 0, void 0, function* () { - try { - return yield this.getTokenFromCache(); - } - catch (error) { - if (error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { - throw error; - } - return new Promise((resolve, reject) => { - const resource = this.getActiveDirectoryResourceId(); - this.authContext.acquireTokenWithClientCertificate(resource, this.clientId, this.certificate, this.thumbprint, (error, tokenResponse) => { - if (error) { - return reject(error); - } - if (tokenResponse.error || tokenResponse.errorDescription) { - return reject(tokenResponse); - } - return resolve(tokenResponse); - }); - }); - } - }); - } - /** - * Creates a new instance of ApplicationTokenCertificateCredentials. - * - * @param clientId The active directory application client id also known as the SPN (ServicePrincipal Name). - * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} - * for an example. - * @param certificateStringOrFilePath - A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example: - * - CertificateString: "-----BEGIN PRIVATE KEY-----\n\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n\n-----END CERTIFICATE-----\n" - * - CertificateFilePath: **Absolute** file path of the .pem file. - * @param domain The domain or tenant id containing this application. - * @param options AzureTokenCredentialsOptions - Object representing optional parameters. - * - * @returns ApplicationTokenCertificateCredentials - */ - static create(clientId, certificateStringOrFilePath, domain, options) { - if (!certificateStringOrFilePath || typeof certificateStringOrFilePath.valueOf() !== "string") { - throw new Error("'certificateStringOrFilePath' must be a non empty string."); - } - if (!certificateStringOrFilePath.startsWith("-----BEGIN")) { - certificateStringOrFilePath = fs_1.readFileSync(certificateStringOrFilePath, "utf8"); - } - const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9\+\/\n\r]+\=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/; - const matchCert = certificateStringOrFilePath.match(certificatePattern); - const rawCertificate = matchCert ? matchCert[3] : ""; - if (!rawCertificate) { - throw new Error("Unable to correctly parse the certificate from the value provided in 'certificateStringOrFilePath' "); - } - const thumbprint = crypto_1.createHash("sha1") - .update(Buffer.from(rawCertificate, "base64")) - .digest("hex"); - return new ApplicationTokenCertificateCredentials(clientId, domain, certificateStringOrFilePath, thumbprint, options.tokenAudience, options.environment, options.tokenCache); - } -} -exports.ApplicationTokenCertificateCredentials = ApplicationTokenCertificateCredentials; -//# sourceMappingURL=applicationTokenCertificateCredentials.js.map - -/***/ }), - -/***/ 35216: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const applicationTokenCredentialsBase_1 = __nccwpck_require__(60968); -const authConstants_1 = __nccwpck_require__(26700); -class ApplicationTokenCredentials extends applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase { - /** - * Creates a new ApplicationTokenCredentials object. - * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} - * for detailed instructions on creating an Azure Active Directory application. - * - * @param clientId - The active directory application client id. - * @param domain - The domain or tenant id containing this application. - * @param secret - The authentication secret for the application. - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). - * @param environment - The azure environment to authenticate with. - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. - */ - constructor(clientId, domain, secret, tokenAudience, environment, tokenCache) { - if (!secret || typeof secret.valueOf() !== "string") { - throw new Error("secret must be a non empty string."); - } - super(clientId, domain, tokenAudience, environment, tokenCache); - this.secret = secret; - } - /** - * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL. - * @returns A promise that resolves to TokenResponse and rejects with an Error. - */ - getToken() { - return __awaiter(this, void 0, void 0, function* () { - try { - return yield this.getTokenFromCache(); - } - catch (error) { - if (error.message && error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { - throw error; - } - const resource = this.getActiveDirectoryResourceId(); - return new Promise((resolve, reject) => { - this.authContext.acquireTokenWithClientCredentials(resource, this.clientId, this.secret, (error, tokenResponse) => { - if (error) { - return reject(error); - } - if (tokenResponse.error || tokenResponse.errorDescription) { - return reject(tokenResponse); - } - return resolve(tokenResponse); - }); - }); - } - }); - } -} -exports.ApplicationTokenCredentials = ApplicationTokenCredentials; -//# sourceMappingURL=applicationTokenCredentials.js.map - -/***/ }), - -/***/ 60968: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tokenCredentialsBase_1 = __nccwpck_require__(5558); -const authConstants_1 = __nccwpck_require__(26700); -class ApplicationTokenCredentialsBase extends tokenCredentialsBase_1.TokenCredentialsBase { - /** - * Creates a new ApplicationTokenCredentials object. - * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} - * for detailed instructions on creating an Azure Active Directory application. - * - * @param clientId - The active directory application client id. - * @param domain - The domain or tenant id containing this application. - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). - * @param environment - The azure environment to authenticate with. - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. - */ - constructor(clientId, domain, tokenAudience, environment, tokenCache) { - super(clientId, domain, tokenAudience, environment, tokenCache); - } - getTokenFromCache() { - const _super = Object.create(null, { - getTokenFromCache: { get: () => super.getTokenFromCache } - }); - return __awaiter(this, void 0, void 0, function* () { - // a thin wrapper over the base implementation. try get token from cache, additionaly clean up cache if required. - try { - return yield _super.getTokenFromCache.call(this, undefined); - } - catch (error) { - // Remove the stale token from the tokencache. ADAL gives the same error message "Entry not found in cache." - // for entry not being present in the cache and for accessToken being expired in the cache. We do not want the token cache - // to contain the expired token, we clean it up here. - const status = yield this.removeInvalidItemsFromCache({ - _clientId: this.clientId - }); - if (status.result) { - throw error; - } - const message = status && status.details && status.details.message - ? status.details.message - : status.details; - throw new Error(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR + - " : " + - "critical failure while removing expired token for service principal from token cache. " + - message); - } - }); - } - /** - * Removes invalid items from token cache. This method is different. Here we never reject in case of error. - * Rather we resolve with an object that says the result is false and error information is provided in - * the details property of the resolved object. This is done to do better error handling in the above function - * where removeInvalidItemsFromCache() is called. - * @param query - The query to be used for finding the token for service principal from the cache - * @returns resultObject with more info. - */ - removeInvalidItemsFromCache(query) { - const self = this; - return new Promise((resolve) => { - self.tokenCache.find(query, (error, entries) => { - if (error) { - return resolve({ result: false, details: error }); - } - if (entries && entries.length > 0) { - return self.tokenCache.remove(entries, (err) => { - if (err) { - return resolve({ result: false, details: err }); - } - return resolve({ result: true }); - }); - } - else { - return resolve({ result: true }); - } - }); - }); - } -} -exports.ApplicationTokenCredentialsBase = ApplicationTokenCredentialsBase; -//# sourceMappingURL=applicationTokenCredentialsBase.js.map - -/***/ }), - -/***/ 38909: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const ms_rest_js_1 = __nccwpck_require__(30812); -const login_1 = __nccwpck_require__(29325); -/** - * Describes the credentials by retrieving token via Azure CLI. - */ -class AzureCliCredentials { - constructor(subscriptionInfo, tokenInfo, - // tslint:disable-next-line: no-inferrable-types - resource = "https://management.azure.com") { - /** - * Azure resource endpoints. - * - Defaults to Azure Resource Manager from environment: AzureCloud. "https://management.azure.com" - * - For Azure KeyVault: "https://vault.azure.net" - * - For Azure Batch: "https://batch.core.windows.net" - * - For Azure Active Directory Graph: "https://graph.windows.net" - * - * To get the resource for other clouds: - * - `az cloud list` - */ - // tslint:disable-next-line: no-inferrable-types - this.resource = "https://management.azure.com"; - /** - * The number of seconds within which it is good to renew the token. - * A constant set to 270 seconds (4.5 minutes). - */ - this._tokenRenewalMarginInSeconds = 270; - this.subscriptionInfo = subscriptionInfo; - this.tokenInfo = tokenInfo; - this.resource = resource; - } - /** - * Tries to get the new token from Azure CLI, if the token has expired or the subscription has - * changed else uses the cached accessToken. - * @returns The tokenResponse (tokenType and accessToken are the two important properties). - */ - getToken() { - return __awaiter(this, void 0, void 0, function* () { - if (this._hasTokenExpired() || this._hasSubscriptionChanged() || this._hasResourceChanged()) { - try { - // refresh the access token - this.tokenInfo = yield AzureCliCredentials.getAccessToken({ - subscriptionIdOrName: this.subscriptionInfo.id, - resource: this.resource - }); - } - catch (err) { - throw new Error(`An error occurred while refreshing the new access ` + - `token:${err.stderr ? err.stderr : err.message}`); - } - } - const result = { - accessToken: this.tokenInfo.accessToken, - tokenType: this.tokenInfo.tokenType, - expiresOn: this.tokenInfo.expiresOn, - tenantId: this.tokenInfo.tenant - }; - return result; - }); - } - /** - * Signs a request with the Authentication header. - * @param The request to be signed. - */ - signRequest(webResource) { - return __awaiter(this, void 0, void 0, function* () { - const tokenResponse = yield this.getToken(); - webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`); - return webResource; - }); - } - _hasTokenExpired() { - let result = true; - const now = Math.floor(Date.now() / 1000); - if (this.tokenInfo.expiresOn && - this.tokenInfo.expiresOn instanceof Date && - Math.floor(this.tokenInfo.expiresOn.getTime() / 1000) - now > - this._tokenRenewalMarginInSeconds) { - result = false; - } - return result; - } - _hasSubscriptionChanged() { - return this.subscriptionInfo.id !== this.tokenInfo.subscription; - } - _parseToken() { - try { - const base64Url = this.tokenInfo.accessToken.split(".")[1]; - const base64 = decodeURIComponent(Buffer.from(base64Url, "base64") - .toString("binary") - .split("") - .map((c) => { - return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); - }) - .join("")); - return JSON.parse(base64); - } - catch (err) { - const msg = `An error occurred while parsing the access token: ${err.stack}`; - throw new Error(msg); - } - } - _isAzureResourceManagerEndpoint(newResource, currentResource) { - if (newResource.endsWith("/")) - newResource = newResource.slice(0, -1); - if (currentResource.endsWith("/")) - currentResource = currentResource.slice(0, -1); - return ((newResource === "https://management.core.windows.net" && - currentResource === "https://management.azure.com") || - (newResource === "https://management.azure.com" && - currentResource === "https://management.core.windows.net")); - } - _hasResourceChanged() { - const parsedToken = this._parseToken(); - // normalize the resource string, since it is possible to - // provide a resource without a trailing slash - const currentResource = parsedToken.aud && parsedToken.aud.endsWith("/") - ? parsedToken.aud.slice(0, -1) - : parsedToken.aud; - const newResource = this.resource.endsWith("/") ? this.resource.slice(0, -1) : this.resource; - const result = this._isAzureResourceManagerEndpoint(newResource, currentResource) - ? false - : currentResource !== newResource; - return result; - } - /** - * Gets the access token for the default or specified subscription. - * @param options Optional parameters that can be provided to get the access token. - */ - static getAccessToken(options = {}) { - return __awaiter(this, void 0, void 0, function* () { - try { - const cmdArguments = ["account", "get-access-token"]; - if (options.subscriptionIdOrName) { - cmdArguments.push("-s"); - cmdArguments.push(options.subscriptionIdOrName); - } - if (options.resource) { - cmdArguments.push("--resource"); - cmdArguments.push(options.resource); - } - const result = yield login_1.execAz(cmdArguments); - result.expiresOn = new Date(result.expiresOn); - return result; - } - catch (err) { - const message = `An error occurred while getting credentials from ` + `Azure CLI: ${err.stack}`; - throw new Error(message); - } - }); - } - /** - * Gets the subscription from Azure CLI. - * @param subscriptionIdOrName - The name or id of the subscription for which the information is - * required. - */ - static getSubscription(subscriptionIdOrName) { - return __awaiter(this, void 0, void 0, function* () { - if (subscriptionIdOrName && - (typeof subscriptionIdOrName !== "string" || !subscriptionIdOrName.length)) { - throw new Error("'subscriptionIdOrName' must be a non-empty string."); - } - try { - const cmdArguments = ["account", "show"]; - if (subscriptionIdOrName) { - cmdArguments.push("-s"); - cmdArguments.push(subscriptionIdOrName); - } - const result = yield login_1.execAz(cmdArguments); - return result; - } - catch (err) { - const message = `An error occurred while getting information about the current subscription from ` + - `Azure CLI: ${err.stack}`; - throw new Error(message); - } - }); - } - /** - * Sets the specified subscription as the default subscription for Azure CLI. - * @param subscriptionIdOrName The name or id of the subsciption that needs to be set as the - * default subscription. - */ - static setDefaultSubscription(subscriptionIdOrName) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield login_1.execAz(["account", "set", "-s", subscriptionIdOrName]); - } - catch (err) { - const message = `An error occurred while setting the current subscription from ` + - `Azure CLI: ${err.stack}`; - throw new Error(message); - } - }); - } - /** - * Returns a list of all the subscriptions from Azure CLI. - * @param options Optional parameters that can be provided while listing all the subcriptions. - */ - static listAllSubscriptions(options = {}) { - return __awaiter(this, void 0, void 0, function* () { - let subscriptionList = []; - try { - const cmdArguments = ["account", "list"]; - if (options.all) { - cmdArguments.push(" --all"); - } - if (options.refresh) { - cmdArguments.push("--refresh"); - } - subscriptionList = yield login_1.execAz(cmdArguments); - if (subscriptionList && subscriptionList.length) { - for (const sub of subscriptionList) { - if (sub.cloudName) { - sub.environmentName = sub.cloudName; - delete sub.cloudName; - } - } - } - return subscriptionList; - } - catch (err) { - const message = `An error occurred while getting a list of all the subscription from ` + - `Azure CLI: ${err.stack}`; - throw new Error(message); - } - }); - } - /** - * Provides credentials that can be used by the JS SDK to interact with Azure via azure cli. - * **Pre-requisite** - * - **install azure-cli** . For more information see - * {@link https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest Install Azure CLI} - * - **login via `az login`** - * @param options - Optional parameters that can be provided while creating AzureCliCredentials. - */ - static create(options = {}) { - return __awaiter(this, void 0, void 0, function* () { - const [subscriptinInfo, accessToken] = yield Promise.all([ - AzureCliCredentials.getSubscription(options.subscriptionIdOrName), - AzureCliCredentials.getAccessToken(options) - ]); - return new AzureCliCredentials(subscriptinInfo, accessToken, options.resource); - }); - } -} -exports.AzureCliCredentials = AzureCliCredentials; -//# sourceMappingURL=azureCliCredentials.js.map - -/***/ }), - -/***/ 80450: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tokenCredentialsBase_1 = __nccwpck_require__(5558); -const authConstants_1 = __nccwpck_require__(26700); -class DeviceTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase { - /** - * Creates a new DeviceTokenCredentials object that gets a new access token using userCodeInfo (contains user_code, device_code) - * for authenticating user on device. - * - * When this credential is used, the script will provide a url and code. The user needs to copy the url and the code, paste it - * in a browser and authenticate over there. If successful, the script will get the access token. - * - * - * @param clientId - The active directory application client id. - * @param domain - The domain or tenant id containing this application. Default value is "common" - * @param username - The user name for account in the form: "user@example.com". - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). - * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} - * for an example. - * @param environment - The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud". - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. - */ - constructor(clientId, domain, username, tokenAudience, environment, tokenCache) { - if (!username) { - username = "user@example.com"; - } - if (!domain) { - domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT; - } - if (!clientId) { - clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID; - } - super(clientId, domain, tokenAudience, environment, tokenCache); - this.username = username; - } - getToken() { - // For device auth, this is just getTokenFromCache. - return this.getTokenFromCache(this.username); - } -} -exports.DeviceTokenCredentials = DeviceTokenCredentials; -//# sourceMappingURL=deviceTokenCredentials.js.map - -/***/ }), - -/***/ 23699: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -Object.defineProperty(exports, "__esModule", ({ value: true })); -const applicationTokenCredentials_1 = __nccwpck_require__(35216); -const applicationTokenCertificateCredentials_1 = __nccwpck_require__(2265); -const deviceTokenCredentials_1 = __nccwpck_require__(80450); -const msiAppServiceTokenCredentials_1 = __nccwpck_require__(68376); -const msiTokenCredentials_1 = __nccwpck_require__(6182); -const msiVmTokenCredentials_1 = __nccwpck_require__(73287); -const tokenCredentialsBase_1 = __nccwpck_require__(5558); -const userTokenCredentials_1 = __nccwpck_require__(14502); -const adal_node_1 = __nccwpck_require__(35894); -function createAuthenticator(credentials) { - const convertedCredentials = _convert(credentials); - const authenticator = _createAuthenticatorMapper(convertedCredentials); - return authenticator; -} -exports.createAuthenticator = createAuthenticator; -function _convert(credentials) { - if (credentials instanceof msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials) { - return new msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials({ - msiEndpoint: credentials.msiEndpoint, - msiSecret: credentials.msiSecret, - msiApiVersion: credentials.msiApiVersion, - resource: credentials.resource - }); - } - else if (credentials instanceof msiVmTokenCredentials_1.MSIVmTokenCredentials) { - return new msiVmTokenCredentials_1.MSIVmTokenCredentials({ - resource: credentials.resource, - msiEndpoint: credentials.msiEndpoint - }); - } - else if (credentials instanceof msiTokenCredentials_1.MSITokenCredentials) { - throw new Error("MSI-credentials not one of: MSIVmTokenCredentials, MSIAppServiceTokenCredentials"); - } - else { - return credentials; - } -} -function _createAuthenticatorMapper(credentials) { - return (challenge) => new Promise((resolve, reject) => { - // Function to take token Response and format a authorization value - const _formAuthorizationValue = (err, tokenResponse) => { - if (err) { - return reject(err); - } - if (tokenResponse.error) { - return reject(tokenResponse.error); - } - tokenResponse = tokenResponse; - // Calculate the value to be set in the request's Authorization header and resume the call. - const authorizationValue = tokenResponse.tokenType + " " + tokenResponse.accessToken; - return resolve(authorizationValue); - }; - // Create a new authentication context. - if (credentials instanceof tokenCredentialsBase_1.TokenCredentialsBase) { - const context = new adal_node_1.AuthenticationContext(challenge.authorization, true, credentials.authContext && credentials.authContext.cache); - if (credentials instanceof applicationTokenCredentials_1.ApplicationTokenCredentials) { - return context.acquireTokenWithClientCredentials(challenge.resource, credentials.clientId, credentials.secret, _formAuthorizationValue); - } - else if (credentials instanceof applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials) { - return context.acquireTokenWithClientCertificate(challenge.resource, credentials.clientId, credentials.certificate, credentials.thumbprint, _formAuthorizationValue); - } - else if (credentials instanceof userTokenCredentials_1.UserTokenCredentials) { - return context.acquireTokenWithUsernamePassword(challenge.resource, credentials.username, credentials.password, credentials.clientId, _formAuthorizationValue); - } - else if (credentials instanceof deviceTokenCredentials_1.DeviceTokenCredentials) { - return context.acquireToken(challenge.resource, credentials.username, credentials.clientId, _formAuthorizationValue); - } - } - else if (credentials instanceof msiTokenCredentials_1.MSITokenCredentials) { - return credentials.getToken(); - } - else { - return reject(new Error("credentials must be one of: ApplicationTokenCredentials, UserTokenCredentials, " + - "DeviceTokenCredentials, MSITokenCredentials")); - } - }); -} -//# sourceMappingURL=keyVaultFactory.js.map - -/***/ }), - -/***/ 68376: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const msiTokenCredentials_1 = __nccwpck_require__(6182); -const ms_rest_js_1 = __nccwpck_require__(30812); -/** - * Provides information about managed service identity token credentials in an App Service environment. - */ -class MSIAppServiceTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials { - /** - * Creates an instance of MSIAppServiceTokenCredentials. - * @param options.msiEndpoint - The local URL from which your app can request tokens. - * Unless this property is specified, any of the two environment variables `IDENTITY_ENDPOINT` or `MSI_ENDPOINT` will be used as the default value. - * @param options.msiSecret - The secret used in communication between your code and the local MSI agent. - * Unless this property is specified, any of the two environment variables `IDENTITY_SECRET` or `MSI_SECRET` will be used as the default value. - * @param options.resource - The resource uri or token audience for which the token is needed. - * For e.g. it can be: - * - resource management endpoint "https://management.azure.com/" (default) - * - management endpoint "https://management.core.windows.net/" - * @param options.msiApiVersion - The api-version of the local MSI agent. Default value is "2017-09-01". - * @param options.clientId - The clientId of the managed identity you would like the token for. Required, if - * your app service has user-assigned managed identities. - */ - constructor(options) { - if (!options) - options = {}; - super(options); - options.msiEndpoint = - options.msiEndpoint || process.env["IDENTITY_ENDPOINT"] || process.env["MSI_ENDPOINT"]; - options.msiSecret = - options.msiSecret || process.env["IDENTITY_SECRET"] || process.env["MSI_SECRET"]; - if (!options.msiEndpoint || - (options.msiEndpoint && typeof options.msiEndpoint.valueOf() !== "string")) { - throw new Error('Either provide "msiEndpoint" as a property of the "options" object ' + - 'or set the environment variable "IDENTITY_ENDPOINT" or "MSI_ENDPOINT" and it must be of type "string".'); - } - if (!options.msiSecret || - (options.msiSecret && typeof options.msiSecret.valueOf() !== "string")) { - throw new Error('Either provide "msiSecret" as a property of the "options" object ' + - 'or set the environment variable "IDENTITY_SECRET" or "MSI_SECRET" and it must be of type "string".'); - } - if (!options.msiApiVersion) { - options.msiApiVersion = "2017-09-01"; - } - else if (typeof options.msiApiVersion.valueOf() !== "string") { - throw new Error("msiApiVersion must be a uri."); - } - this.msiEndpoint = options.msiEndpoint; - this.msiSecret = options.msiSecret; - this.msiApiVersion = options.msiApiVersion; - this.clientId = options.clientId; - } - /** - * Prepares and sends a GET request to a service endpoint indicated by the app service, which responds with the access token. - * @returns Promise with the tokenResponse (tokenType and accessToken are the two important properties). - */ - getToken() { - return __awaiter(this, void 0, void 0, function* () { - const reqOptions = this.prepareRequestOptions(); - const opRes = yield this._httpClient.sendRequest(reqOptions); - if (opRes.bodyAsText === undefined || opRes.bodyAsText.indexOf("ExceptionMessage") !== -1) { - throw new Error(`MSI: Failed to retrieve a token from "${reqOptions.url}" with an error: ${opRes.bodyAsText}`); - } - const result = this.parseTokenResponse(opRes.bodyAsText); - if (!result.tokenType) { - throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`); - } - else if (!result.accessToken) { - throw new Error(`Invalid token response, did not find accessToken. Response body is: ${opRes.bodyAsText}`); - } - return result; - }); - } - prepareRequestOptions() { - const endpoint = this.msiEndpoint.endsWith("/") ? this.msiEndpoint : `${this.msiEndpoint}/`; - const reqOptions = { - url: endpoint, - headers: { - secret: this.msiSecret - }, - queryParameters: { - resource: this.resource, - "api-version": this.msiApiVersion, - clientid: this.clientId - }, - method: "GET" - }; - const webResource = new ms_rest_js_1.WebResource(); - return webResource.prepare(reqOptions); - } -} -exports.MSIAppServiceTokenCredentials = MSIAppServiceTokenCredentials; -//# sourceMappingURL=msiAppServiceTokenCredentials.js.map - -/***/ }), - -/***/ 6182: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const ms_rest_js_1 = __nccwpck_require__(30812); -const authConstants_1 = __nccwpck_require__(26700); -/** - * Provides information about managed service identity token credentials. - * This object can only be used to acquire token on a virtual machine provisioned in Azure with managed service identity. - */ -class MSITokenCredentials { - /** - * Creates an instance of MSITokenCredentials. - * @param options - Optional parameters - * @param options.resource - The resource uri or token audience for which the token is needed. - * For e.g. it can be: - * - resource management endpoint "https://management.azure.com/"(default) - * - management endpoint "https://management.core.windows.net/" - */ - constructor(options) { - if (!options) - options = {}; - if (!options.resource) { - options.resource = authConstants_1.AuthConstants.RESOURCE_MANAGER_ENDPOINT; - } - else if (typeof options.resource.valueOf() !== "string") { - throw new Error("resource must be a uri."); - } - this.resource = options.resource; - this._httpClient = options.httpClient || new ms_rest_js_1.DefaultHttpClient(); - } - /** - * Parses a tokenResponse json string into a object, and converts properties on the first level to camelCase. - * This method tries to standardize the tokenResponse - * @param body - A json string - * @returns The tokenResponse (tokenType and accessToken are the two important properties). - */ - parseTokenResponse(body) { - // Docs show different examples of possible MSI responses for different services. https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/overview - // expires_on - is a Date like string in this doc - // - https://docs.microsoft.com/en-us/azure/app-service/app-service-managed-service-identity#rest-protocol-examples - // In other doc it is stringified number. - // - https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/tutorial-linux-vm-access-arm#get-an-access-token-using-the-vms-identity-and-use-it-to-call-resource-manager - const parsedBody = JSON.parse(body); - parsedBody.accessToken = parsedBody["access_token"]; - delete parsedBody["access_token"]; - parsedBody.tokenType = parsedBody["token_type"]; - delete parsedBody["token_type"]; - if (parsedBody["refresh_token"]) { - parsedBody.refreshToken = parsedBody["refresh_token"]; - delete parsedBody["refresh_token"]; - } - if (parsedBody["expires_in"]) { - parsedBody.expiresIn = parsedBody["expires_in"]; - if (typeof parsedBody["expires_in"] === "string") { - // normal number as a string '1504130527' - parsedBody.expiresIn = parseInt(parsedBody["expires_in"], 10); - } - delete parsedBody["expires_in"]; - } - if (parsedBody["not_before"]) { - parsedBody.notBefore = parsedBody["not_before"]; - if (typeof parsedBody["not_before"] === "string") { - // normal number as a string '1504130527' - parsedBody.notBefore = parseInt(parsedBody["not_before"], 10); - } - delete parsedBody["not_before"]; - } - if (parsedBody["expires_on"]) { - parsedBody.expiresOn = parsedBody["expires_on"]; - if (typeof parsedBody["expires_on"] === "string") { - // possibly a Date string '09/14/2017 00:00:00 PM +00:00' - if (parsedBody["expires_on"].includes(":") || parsedBody["expires_on"].includes("/")) { - parsedBody.expiresOn = new Date(parseInt(parsedBody["expires_on"], 10)); - } - else { - // normal number as a string '1504130527' - parsedBody.expiresOn = new Date(parseInt(parsedBody["expires_on"], 10)); - } - } - delete parsedBody["expires_on"]; - } - return parsedBody; - } - /** - * Signs a request with the Authentication header. - * - * @param webResource - The WebResource to be signed. - * @returns Promise with signed WebResource. - */ - signRequest(webResource) { - return __awaiter(this, void 0, void 0, function* () { - const tokenResponse = yield this.getToken(); - webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`); - return webResource; - }); - } -} -exports.MSITokenCredentials = MSITokenCredentials; -//# sourceMappingURL=msiTokenCredentials.js.map - -/***/ }), - -/***/ 73287: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const msiTokenCredentials_1 = __nccwpck_require__(6182); -const ms_rest_js_1 = __nccwpck_require__(30812); -/** - * Provides information about managed service identity token credentials on a virtual machine provisioned in Azure. - */ -class MSIVmTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials { - constructor(options) { - if (!options) - options = {}; - super(options); - if (!options.msiEndpoint) { - options.msiEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token"; - } - else if (typeof options.msiEndpoint !== "string") { - throw new Error("msiEndpoint must be a string."); - } - const urlBuilder = ms_rest_js_1.URLBuilder.parse(options.msiEndpoint); - if (!urlBuilder.getScheme()) { - options.msiEndpoint = `http://${options.msiEndpoint}`; - } - if (!options.apiVersion) { - options.apiVersion = "2018-02-01"; - } - else if (typeof options.apiVersion !== "string") { - throw new Error("apiVersion must be a string."); - } - if (!options.httpMethod) { - options.httpMethod = "GET"; - } - this.apiVersion = options.apiVersion; - this.msiEndpoint = options.msiEndpoint; - this.httpMethod = options.httpMethod; - this.objectId = options.objectId; - this.clientId = options.clientId; - this.identityId = options.identityId; - } - /** - * Prepares and sends a POST request to a service endpoint hosted on the Azure VM, which responds with the access token. - * @returns Promise with the tokenResponse (tokenType and accessToken are the two important properties). - */ - getToken() { - return __awaiter(this, void 0, void 0, function* () { - const reqOptions = this.prepareRequestOptions(); - const opRes = yield this._httpClient.sendRequest(reqOptions); - const result = this.parseTokenResponse(opRes.bodyAsText); - if (!result.tokenType) { - throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`); - } - else if (!result.accessToken) { - throw new Error(`Invalid token response, did not find accessToken. Response body is: ${opRes.bodyAsText}`); - } - return result; - }); - } - prepareRequestOptions() { - const reqOptions = { - url: this.msiEndpoint, - headers: { - "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", - Metadata: "true" - }, - method: this.httpMethod, - queryParameters: { - "api-version": this.apiVersion, - resource: this.resource, - object_id: this.objectId, - client_id: this.clientId, - mi_res_id: this.identityId - } - }; - const webResource = new ms_rest_js_1.WebResource(); - return webResource.prepare(reqOptions); - } -} -exports.MSIVmTokenCredentials = MSIVmTokenCredentials; -//# sourceMappingURL=msiVmTokenCredentials.js.map - -/***/ }), - -/***/ 5558: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const ms_rest_js_1 = __nccwpck_require__(30812); -const ms_rest_azure_env_1 = __nccwpck_require__(40787); -const adal_node_1 = __nccwpck_require__(35894); -class TokenCredentialsBase { - constructor(clientId, domain, tokenAudience, environment = ms_rest_azure_env_1.Environment.AzureCloud, tokenCache = new adal_node_1.MemoryCache()) { - this.clientId = clientId; - this.domain = domain; - this.tokenAudience = tokenAudience; - this.environment = environment; - this.tokenCache = tokenCache; - if (!clientId || typeof clientId.valueOf() !== "string") { - throw new Error("clientId must be a non empty string."); - } - if (!domain || typeof domain.valueOf() !== "string") { - throw new Error("domain must be a non empty string."); - } - if (this.tokenAudience === "graph" && this.domain.toLowerCase() === "common") { - throw new Error(`${'If the tokenAudience is specified as "graph" then "domain" cannot be defaulted to "common" tenant.\ - It must be the actual tenant (preferably a string in a guid format).'}`); - } - const authorityUrl = this.environment.activeDirectoryEndpointUrl + this.domain; - this.authContext = new adal_node_1.AuthenticationContext(authorityUrl, this.environment.validateAuthority, this.tokenCache); - } - setDomain(domain) { - this.domain = domain; - const authorityUrl = this.environment.activeDirectoryEndpointUrl + this.domain; - this.authContext = new adal_node_1.AuthenticationContext(authorityUrl, this.environment.validateAuthority, this.tokenCache); - } - getActiveDirectoryResourceId() { - let resource = this.environment.activeDirectoryResourceId; - if (this.tokenAudience) { - resource = this.tokenAudience; - if (this.tokenAudience.toLowerCase() === "graph") { - resource = this.environment.activeDirectoryGraphResourceId; - } - else if (this.tokenAudience.toLowerCase() === "batch") { - resource = this.environment.batchResourceId; - } - } - return resource; - } - getTokenFromCache(username) { - const self = this; - const resource = this.getActiveDirectoryResourceId(); - return new Promise((resolve, reject) => { - self.authContext.acquireToken(resource, username, self.clientId, (error, tokenResponse) => { - if (error) { - return reject(error); - } - if (tokenResponse.error || tokenResponse.errorDescription) { - return reject(tokenResponse); - } - return resolve(tokenResponse); - }); - }); - } - /** - * Signs a request with the Authentication header. - * - * @param webResource - The WebResource to be signed. - */ - signRequest(webResource) { - return __awaiter(this, void 0, void 0, function* () { - const tokenResponse = yield this.getToken(); - webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`); - return webResource; - }); - } -} -exports.TokenCredentialsBase = TokenCredentialsBase; -//# sourceMappingURL=tokenCredentialsBase.js.map - -/***/ }), - -/***/ 14502: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tokenCredentialsBase_1 = __nccwpck_require__(5558); -class UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase { - /** - * Creates a new UserTokenCredentials object. - * - * - * @param clientId - The active directory application client id. - * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} - * for an example. - * @param domain - The domain or tenant id containing this application. - * @param username - The user name for the Organization Id account. - * @param password - The password for the Organization Id account. - * @param tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferably in a guid format). - * @param environment - The azure environment to authenticate with. - * @param tokenCache - The token cache. Default value is the MemoryCache object from adal. - */ - constructor(clientId, domain, username, password, tokenAudience, environment, tokenCache) { - if (!clientId || typeof clientId.valueOf() !== "string") { - throw new Error("clientId must be a non empty string."); - } - if (!domain || typeof domain.valueOf() !== "string") { - throw new Error("domain must be a non empty string."); - } - if (!username || typeof username.valueOf() !== "string") { - throw new Error("username must be a non empty string."); - } - if (!password || typeof password.valueOf() !== "string") { - throw new Error("password must be a non empty string."); - } - super(clientId, domain, tokenAudience, environment, tokenCache); - this.username = username; - this.password = password; - } - crossCheckUserNameWithToken(username, userIdFromToken) { - // to maintain the casing consistency between "azureprofile.json" and token cache. (RD 1996587) - // use the "userId" here, which should be the same with "username" except the casing. - return username.toLowerCase() === userIdFromToken.toLowerCase(); - } - /** - * Tries to get the token from cache initially. If that is unsuccessful then it tries to get the token from ADAL. - * - * @returns The tokenResponse (tokenType and accessToken are the two important properties). - */ - getToken() { - return __awaiter(this, void 0, void 0, function* () { - try { - return yield this.getTokenFromCache(this.username); - } - catch (error) { - const self = this; - const resource = this.getActiveDirectoryResourceId(); - return new Promise((resolve, reject) => { - self.authContext.acquireTokenWithUsernamePassword(resource, self.username, self.password, self.clientId, (error, tokenResponse) => { - if (error) { - return reject(error); - } - if (tokenResponse.error || tokenResponse.errorDescription) { - return reject(tokenResponse); - } - tokenResponse = tokenResponse; - if (self.crossCheckUserNameWithToken(self.username, tokenResponse.userId)) { - return resolve(tokenResponse); - } - else { - return reject(`The userId "${tokenResponse.userId}" in access token doesn't match the username "${self.username}" provided during authentication.`); - } - }); - }); - } - }); - } -} -exports.UserTokenCredentials = UserTokenCredentials; -//# sourceMappingURL=userTokenCredentials.js.map - /***/ }), /***/ 29325: @@ -11507,16 +8536,16 @@ const msRest = __nccwpck_require__(30812); const child_process_1 = __nccwpck_require__(63129); const fs_1 = __nccwpck_require__(35747); const ms_rest_azure_env_1 = __nccwpck_require__(40787); -const applicationTokenCredentials_1 = __nccwpck_require__(35216); -const applicationTokenCertificateCredentials_1 = __nccwpck_require__(2265); -const deviceTokenCredentials_1 = __nccwpck_require__(80450); -const userTokenCredentials_1 = __nccwpck_require__(14502); -const authConstants_1 = __nccwpck_require__(26700); -const subscriptionUtils_1 = __nccwpck_require__(47813); -const msiVmTokenCredentials_1 = __nccwpck_require__(73287); -const msiAppServiceTokenCredentials_1 = __nccwpck_require__(68376); -/** - * Urls for management plane token +const applicationTokenCredentials_1 = __nccwpck_require__(93084); +const applicationTokenCertificateCredentials_1 = __nccwpck_require__(11339); +const deviceTokenCredentials_1 = __nccwpck_require__(50567); +const userTokenCredentials_1 = __nccwpck_require__(52055); +const authConstants_1 = __nccwpck_require__(95954); +const subscriptionUtils_1 = __nccwpck_require__(29286); +const msiVmTokenCredentials_1 = __nccwpck_require__(95120); +const msiAppServiceTokenCredentials_1 = __nccwpck_require__(6505); +/** + * @constant {Array} managementPlaneTokenAudiences - Urls for management plane token * audience across different azure environments. */ const managementPlaneTokenAudiences = [ @@ -11551,21 +8580,19 @@ if (process.env["AZURE_ADAL_LOGGING_ENABLED"]) { * Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants. * This method is applicable only for organizational ids that are not 2FA enabled otherwise please use interactive login. * - * When using personal accounts, the `domain` property in the `options` parameter is required to be set to the Id of a tenant for that account. Otherwise, the resulting credential will not be able to access the account's resources. - * - * @param username - The user name for the Organization Id account. - * @param password - The password for the Organization Id account. - * @param options - Object representing optional parameters. - * @param options.clientId - The active directory application client id. + * @param {string} username The user name for the Organization Id account. + * @param {string} password The password for the Organization Id account. + * @param {object} [options] Object representing optional parameters. + * @param {string} [options.clientId] The active directory application client id. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param options.tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferably in a guid format). - * @param options.domain - The domain or tenant Id containing this application. Default value "common". - * @param options.environment - The azure environment to authenticate with. - * @param options.tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). + * @param {string} [options.domain] The domain or tenant id containing this application. Default value "common". + * @param {Environment} [options.environment] The azure environment to authenticate with. + * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal. * - * @returns A Promise that resolves to AuthResponse, which contains `credentials` and an optional `subscriptions` array, and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withUsernamePasswordWithAuthResponse(username, password, options) { return __awaiter(this, void 0, void 0, function* () { @@ -11581,35 +8608,38 @@ function withUsernamePasswordWithAuthResponse(username, password, options) { if (!options.environment) { options.environment = ms_rest_azure_env_1.Environment.AzureCloud; } - const creds = new userTokenCredentials_1.UserTokenCredentials(options.clientId, options.domain, username, password, options.tokenAudience, options.environment, options.tokenCache); - const tokenResponse = yield creds.getToken(); - // The token cache gets propulated for all the tenants as a part of building the tenantList. - let tenantList = yield subscriptionUtils_1.buildTenantList(creds); - if (tenantList.length === 0 && tokenResponse.tenantId) { - tenantList = [tokenResponse.tenantId]; + let creds; + let tenantList = []; + let subscriptionList = []; + try { + creds = new userTokenCredentials_1.UserTokenCredentials(options.clientId, options.domain, username, password, options.tokenAudience, options.environment); + yield creds.getToken(); + // The token cache gets propulated for all the tenants as a part of building the tenantList. + tenantList = yield subscriptionUtils_1.buildTenantList(creds); + subscriptionList = yield _getSubscriptions(creds, tenantList, options.tokenAudience); + } + catch (err) { + return Promise.reject(err); } - const subscriptionList = yield _getSubscriptions(creds, tenantList, options.tokenAudience); - return { credentials: creds, subscriptions: subscriptionList }; + return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); }); } exports.withUsernamePasswordWithAuthResponse = withUsernamePasswordWithAuthResponse; /** - * Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrincipalId/clientId across all the applicable tenants. - * - * When using personal accounts, the `domain` parameter is required to be set to the Id of a tenant for that account. Otherwise, the resulting credential will not be able to access the account's resources. + * Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants. * - * @param clientId - The active directory application client Id also known as the SPN (ServicePrincipal Name). + * @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name). * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param secret - The application secret for the service principal. - * @param domain - The domain or tenant Id containing this application. - * @param options - Object representing optional parameters. - * @param options.tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferably in a guid format). - * @param options.environment - The azure environment to authenticate with. - * @param options.tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {string} secret The application secret for the service principal. + * @param {string} domain The domain or tenant id containing this application. + * @param {object} [options] Object representing optional parameters. + * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). + * @param {Environment} [options.environment] The azure environment to authenticate with. + * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal. * - * @returns A Promise that resolves to AuthResponse, which contains "credentials" and optional "subscriptions" array and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options) { return __awaiter(this, void 0, void 0, function* () { @@ -11619,32 +8649,37 @@ function withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, op if (!options.environment) { options.environment = ms_rest_azure_env_1.Environment.AzureCloud; } - const creds = new applicationTokenCredentials_1.ApplicationTokenCredentials(clientId, domain, secret, options.tokenAudience, options.environment, options.tokenCache); - yield creds.getToken(); - const subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); - return { credentials: creds, subscriptions: subscriptionList }; + let creds; + let subscriptionList = []; + try { + creds = new applicationTokenCredentials_1.ApplicationTokenCredentials(clientId, domain, secret, options.tokenAudience, options.environment); + yield creds.getToken(); + subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); + } + catch (err) { + return Promise.reject(err); + } + return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); }); } exports.withServicePrincipalSecretWithAuthResponse = withServicePrincipalSecretWithAuthResponse; /** - * Provides an ApplicationTokenCertificateCredentials object and the list of subscriptions associated with that servicePrincipalId/clientId across all the applicable tenants. - * - * When using personal accounts, the `domain` parameter is required to be set to the Id of a tenant for that account. Otherwise, the resulting credential will not be able to access the account's resources. + * Provides an ApplicationTokenCertificateCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants. * - * @param clientId - The active directory application client Id also known as the SPN (ServicePrincipal Name). + * @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name). * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. - * @param certificateStringOrFilePath - A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example: + * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example: * - CertificateString: "-----BEGIN PRIVATE KEY-----\n\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n\n-----END CERTIFICATE-----\n" * - CertificateFilePath: **Absolute** file path of the .pem file. - * @param domain - The domain or tenant Id containing this application. - * @param options - Object representing optional parameters. - * @param options.tokenAudience - The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. - * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferably in a guid format). - * @param options.environment - The azure environment to authenticate with. - * @param options.tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {string} domain The domain or tenant id containing this application. + * @param {object} [options] Object representing optional parameters. + * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'. + * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format). + * @param {Environment} [options.environment] The azure environment to authenticate with. + * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal. * - * @returns A Promise that resolves to AuthResponse, which contains "credentials" and optional "subscriptions" array and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options) { return __awaiter(this, void 0, void 0, function* () { @@ -11654,10 +8689,17 @@ function withServicePrincipalCertificateWithAuthResponse(clientId, certificateSt if (!options.environment) { options.environment = ms_rest_azure_env_1.Environment.AzureCloud; } - const creds = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials.create(clientId, certificateStringOrFilePath, domain, options); - yield creds.getToken(); - const subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); - return { credentials: creds, subscriptions: subscriptionList }; + let creds; + let subscriptionList = []; + try { + creds = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials.create(clientId, certificateStringOrFilePath, domain, options); + yield creds.getToken(); + subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); + } + catch (err) { + return Promise.reject(err); + } + return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); }); } exports.withServicePrincipalCertificateWithAuthResponse = withServicePrincipalCertificateWithAuthResponse; @@ -11702,7 +8744,7 @@ function foundManagementEndpointUrl(authFileUrl, envUrl) { } authFileUrl = authFileUrl.endsWith("/") ? authFileUrl.slice(0, -1) : authFileUrl; envUrl = envUrl.endsWith("/") ? envUrl.slice(0, -1) : envUrl; - return authFileUrl.toLowerCase() === envUrl.toLowerCase(); + return (authFileUrl.toLowerCase() === envUrl.toLowerCase()); } /** * Before using this method please install az cli from https://github.com/Azure/azure-cli/releases. Then execute `az ad sp create-for-rbac --sdk-auth > ${yourFilename.json}`. @@ -11720,14 +8762,14 @@ function foundManagementEndpointUrl(authFileUrl, envUrl) { * the subscriptionId from the auth file to the user provided environment variable in the options * parameter or the default "AZURE_SUBSCRIPTION_ID". * - * @param options - Optional parameters - * @param options.filePath - Absolute file path to the auth file. If not provided + * @param {object} [options] - Optional parameters + * @param {string} [options.filePath] - Absolute file path to the auth file. If not provided * then please set the environment variable AZURE_AUTH_LOCATION. - * @param options.subscriptionEnvVariableName - The subscriptionId environment variable + * @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable * name. Default is "AZURE_SUBSCRIPTION_ID". - * @param optionalCallback - The optional callback. + * @param {function} [optionalCallback] The optional callback. * - * @returns A Promise that resolves to AuthResponse, which contains "credentials" and optional "subscriptions" array and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withAuthFileWithAuthResponse(options) { return __awaiter(this, void 0, void 0, function* () { @@ -11737,13 +8779,18 @@ function withAuthFileWithAuthResponse(options) { const subscriptionEnvVariableName = options.subscriptionEnvVariableName || "AZURE_SUBSCRIPTION_ID"; if (!filePath) { const msg = `Either provide an absolute file path to the auth file or set/export the environment variable - ${authConstants_1.AuthConstants.AZURE_AUTH_LOCATION}.`; - throw new Error(msg); + return Promise.reject(new Error(msg)); } let content, credsObj = {}; const optionsForSp = {}; - content = fs_1.readFileSync(filePath, { encoding: "utf8" }); - credsObj = JSON.parse(content); - validateAuthFileContent(credsObj, filePath); + try { + content = fs_1.readFileSync(filePath, { encoding: "utf8" }); + credsObj = JSON.parse(content); + validateAuthFileContent(credsObj, filePath); + } + catch (err) { + return Promise.reject(err); + } if (!credsObj.managementEndpointUrl) { credsObj.managementEndpointUrl = credsObj.resourceManagerEndpointUrl; } @@ -11776,7 +8823,7 @@ function withAuthFileWithAuthResponse(options) { const keys = Object.keys(credsObj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; - if (key.match(/^(clientId|clientSecret|clientCertificate|subscriptionId|tenantId)$/gi) === null) { + if (key.match(/^(clientId|clientSecret|clientCertificate|subscriptionId|tenantId)$/ig) === null) { if (key === "activeDirectoryEndpointUrl" && !key.endsWith("/")) { envParams[key] = credsObj[key] + "/"; } @@ -11801,36 +8848,38 @@ function withAuthFileWithAuthResponse(options) { } exports.withAuthFileWithAuthResponse = withAuthFileWithAuthResponse; /** - * Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants. + * Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a + * DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants. * - * When using personal accounts, the `domain` property in the `options` parameter is required to be set to the Id of a tenant for that account. Otherwise, the resulting credential will not be able to access the account's resources. + * @param {object} [options] Object representing optional parameters. * - * @param options - Object representing optional parameters. - * - * @param options.clientId - The active directory application client id. + * @param {string} [options.clientId] The active directory application client id. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} * for an example. * - * @param options.tokenAudience - The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided - * then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferably in a guid format). + * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided + * then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format). * - * @param options.domain - The domain or tenant Id containing this application. Default value is "common". + * @param {string} [options.domain] The domain or tenant id containing this application. Default value is "common". * - * @param options.environment - The azure environment to authenticate with. Default environment is "Public Azure". + * @param {Environment} [options.environment] The azure environment to authenticate with. Default environment is "Public Azure". * - * @param options.tokenCache - The token cache. Default value is the MemoryCache object from adal. + * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal. * - * @param options.language - The language code specifying how the message should be localized to. Default value "en-us". + * @param {object} [options.language] The language code specifying how the message should be localized to. Default value "en-us". * - * @param options.userCodeResponseLogger - A logger that logs the user code response message required for interactive login. When + * @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When * this option is specified the usercode response message will not be logged to console. * - * @param optionalCallback - The optional callback. + * @param {function} [optionalCallback] The optional callback. * - * @returns A Promise that resolves to AuthResponse, which contains "credentials" and optional "subscriptions" array and rejects with an Error. + * @returns {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. */ function withInteractiveWithAuthResponse(options) { return __awaiter(this, void 0, void 0, function* () { + if (!options) { + options = {}; + } if (!options) { options = {}; } @@ -11863,6 +8912,8 @@ function withInteractiveWithAuthResponse(options) { const authorityUrl = interactiveOptions.environment.activeDirectoryEndpointUrl + interactiveOptions.domain; const authContext = new adal.AuthenticationContext(authorityUrl, interactiveOptions.environment.validateAuthority, interactiveOptions.tokenCache); interactiveOptions.context = authContext; + let userCodeResponse; + let creds; function tryAcquireToken(interactiveOptions, resolve, reject) { authContext.acquireUserCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, interactiveOptions.language, (err, userCodeRes) => { if (err) { @@ -11872,44 +8923,46 @@ function withInteractiveWithAuthResponse(options) { }, 1000); } else { - reject(err); + return reject(err); } - return; } + userCodeResponse = userCodeRes; if (interactiveOptions.userCodeResponseLogger) { - interactiveOptions.userCodeResponseLogger(userCodeRes.message); + interactiveOptions.userCodeResponseLogger(userCodeResponse.message); } else { - console.log(userCodeRes.message); + console.log(userCodeResponse.message); } - return resolve(userCodeRes); + return resolve(userCodeResponse); }); } const getUserCode = new Promise((resolve, reject) => { return tryAcquireToken(interactiveOptions, resolve, reject); }); - const userCodeResponse = yield getUserCode; - const creds = yield new Promise((resolve, reject) => { - return authContext.acquireTokenWithDeviceCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, userCodeResponse, (error, tokenResponse) => { - if (error) { - return reject(error); - } - const response = tokenResponse; - interactiveOptions.userName = response.userId; - interactiveOptions.authorizationScheme = response.tokenType; - let creds; - try { - creds = new deviceTokenCredentials_1.DeviceTokenCredentials(interactiveOptions.clientId, interactiveOptions.domain, interactiveOptions.userName, interactiveOptions.tokenAudience, interactiveOptions.environment, interactiveOptions.tokenCache); - } - catch (err) { - return reject(err); - } - return resolve(creds); + return getUserCode.then(() => { + return new Promise((resolve, reject) => { + return authContext.acquireTokenWithDeviceCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, userCodeResponse, (error, tokenResponse) => { + if (error) { + return reject(error); + } + interactiveOptions.userName = tokenResponse.userId; + interactiveOptions.authorizationScheme = tokenResponse.tokenType; + try { + creds = new deviceTokenCredentials_1.DeviceTokenCredentials(interactiveOptions.clientId, interactiveOptions.domain, interactiveOptions.userName, interactiveOptions.tokenAudience, interactiveOptions.environment, interactiveOptions.tokenCache); + } + catch (err) { + return reject(err); + } + return resolve(creds); + }); }); + }).then((creds) => { + return subscriptionUtils_1.buildTenantList(creds); + }).then((tenants) => { + return _getSubscriptions(creds, tenants, interactiveOptions.tokenAudience); + }).then((subscriptions) => { + return Promise.resolve({ credentials: creds, subscriptions: subscriptions }); }); - const tenants = yield subscriptionUtils_1.buildTenantList(creds); - const subscriptions = yield _getSubscriptions(creds, tenants, interactiveOptions.tokenAudience); - return { credentials: creds, subscriptions: subscriptions }; }); } exports.withInteractiveWithAuthResponse = withInteractiveWithAuthResponse; @@ -11921,7 +8974,9 @@ function withAuthFile(options, callback) { const cb = callback; if (!callback) { return withAuthFileWithAuthResponse(options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -11942,7 +8997,9 @@ function interactive(options, callback) { const cb = callback; if (!callback) { return withInteractiveWithAuthResponse(options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -11963,7 +9020,9 @@ function withServicePrincipalSecret(clientId, secret, domain, options, callback) const cb = callback; if (!callback) { return withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -11984,7 +9043,9 @@ function withServicePrincipalCertificate(clientId, certificateStringOrFilePath, const cb = callback; if (!callback) { return withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -12005,7 +9066,9 @@ function withUsernamePassword(username, password, options, callback) { const cb = callback; if (!callback) { return withUsernamePasswordWithAuthResponse(username, password, options).then((authRes) => { - return authRes.credentials; + return Promise.resolve(authRes.credentials); + }).catch((err) => { + return Promise.reject(err); }); } else { @@ -12023,31 +9086,33 @@ exports.withUsernamePassword = withUsernamePassword; */ function _getSubscriptions(creds, tenants, tokenAudience) { if (tokenAudience && - !managementPlaneTokenAudiences.some((item) => { - return item === tokenAudience.toLowerCase(); - })) { - return Promise.resolve([]); + !managementPlaneTokenAudiences.some((item) => { return item === tokenAudience.toLowerCase(); })) { + return Promise.resolve(([])); } return subscriptionUtils_1.getSubscriptionsFromTenants(creds, tenants); } /** * Initializes MSITokenCredentials class and calls getToken and returns a token response. * - * @param domain - - required. The tenant id. - * @param options - - Optional parameters - * @param options.port - port on which the MSI service is running on the host VM. Default port is 50342 - * @param options.resource - The resource uri or token audience for which the token is needed. Default - "https://management.azure.com/" - * @param options.aadEndpoint - The add endpoint for authentication. default - "https://login.microsoftonline.com" - * @param callback - - the callback function. + * @param {string} domain - required. The tenant id. + * @param {object} options - Optional parameters + * @param {string} [options.port] - port on which the MSI service is running on the host VM. Default port is 50342 + * @param {string} [options.resource] - The resource uri or token audience for which the token is needed. Default - "https://management.azure.com/" + * @param {string} [options.aadEndpoint] - The add endpoint for authentication. default - "https://login.microsoftonline.com" + * @param {any} callback - the callback function. */ function _withMSI(options) { - return __awaiter(this, void 0, void 0, function* () { - if (!options) { - options = {}; - } + if (!options) { + options = {}; + } + return new Promise((resolve, reject) => { const creds = new msiVmTokenCredentials_1.MSIVmTokenCredentials(options); - yield creds.getToken(); - return creds; + creds.getToken().then((_tokenResponse) => { + // We ignore the token response, it's put in the cache. + return resolve(creds); + }).catch(error => { + reject(error); + }); }); } function loginWithVmMSI(options, callback) { @@ -12073,13 +9138,17 @@ exports.loginWithVmMSI = loginWithVmMSI; * Private method */ function _withAppServiceMSI(options) { - return __awaiter(this, void 0, void 0, function* () { - if (!options) { - options = {}; - } + if (!options) { + options = {}; + } + return new Promise((resolve, reject) => { const creds = new msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials(options); - yield creds.getToken(); - return creds; + creds.getToken().then((_tokenResponse) => { + // We ignore the token response, it's put in the cache. + return resolve(creds); + }).catch(error => { + reject(error); + }); }); } function loginWithAppServiceMSI(options, callback) { @@ -12104,13 +9173,12 @@ exports.loginWithAppServiceMSI = loginWithAppServiceMSI; /** * Executes the azure cli command and returns the result. It will be `undefined` if the command did * not return anything or a `JSON object` if the command did return something. - * @param cmdArguments Arguments to the az cli command to execute. + * @param cmd The az cli command to execute. */ -function execAz(cmdArguments) { +function execAz(cmd) { return __awaiter(this, void 0, void 0, function* () { - const azCmd = process.platform === "win32" ? "az.cmd" : "az"; return new Promise((resolve, reject) => { - child_process_1.execFile(azCmd, [...cmdArguments, "--out", "json"], { encoding: "utf8" }, (error, stdout) => { + child_process_1.exec(`az ${cmd} --out json`, { encoding: "utf8" }, (error, stdout) => { if (error) { return reject(error); } @@ -12119,8 +9187,8 @@ function execAz(cmdArguments) { return resolve(JSON.parse(stdout)); } catch (err) { - const msg = `An error occurred while parsing the output "${stdout}", of ` + - `the cmd az "${cmdArguments}": ${err.stack}.`; + const msg = `An error occured while parsing the output "${stdout}", of ` + + `the cmd "${cmd}": ${err.stack}.`; return reject(new Error(msg)); } } @@ -12142,29 +9210,27 @@ exports.execAz = execAz; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. Object.defineProperty(exports, "__esModule", ({ value: true })); -var applicationTokenCredentials_1 = __nccwpck_require__(35216); +var applicationTokenCredentials_1 = __nccwpck_require__(93084); exports.ApplicationTokenCredentials = applicationTokenCredentials_1.ApplicationTokenCredentials; -var applicationTokenCertificateCredentials_1 = __nccwpck_require__(2265); +var applicationTokenCertificateCredentials_1 = __nccwpck_require__(11339); exports.ApplicationTokenCertificateCredentials = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials; -var deviceTokenCredentials_1 = __nccwpck_require__(80450); +var deviceTokenCredentials_1 = __nccwpck_require__(50567); exports.DeviceTokenCredentials = deviceTokenCredentials_1.DeviceTokenCredentials; -var keyVaultFactory_1 = __nccwpck_require__(23699); +var keyVaultFactory_1 = __nccwpck_require__(96577); exports.createAuthenticator = keyVaultFactory_1.createAuthenticator; -var msiAppServiceTokenCredentials_1 = __nccwpck_require__(68376); +var msiAppServiceTokenCredentials_1 = __nccwpck_require__(6505); exports.MSIAppServiceTokenCredentials = msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials; -var msiTokenCredentials_1 = __nccwpck_require__(6182); +var msiTokenCredentials_1 = __nccwpck_require__(37563); exports.MSITokenCredentials = msiTokenCredentials_1.MSITokenCredentials; -var msiVmTokenCredentials_1 = __nccwpck_require__(73287); +var msiVmTokenCredentials_1 = __nccwpck_require__(95120); exports.MSIVmTokenCredentials = msiVmTokenCredentials_1.MSIVmTokenCredentials; -var tokenCredentialsBase_1 = __nccwpck_require__(5558); +var tokenCredentialsBase_1 = __nccwpck_require__(89357); exports.TokenCredentialsBase = tokenCredentialsBase_1.TokenCredentialsBase; -var userTokenCredentials_1 = __nccwpck_require__(14502); +var userTokenCredentials_1 = __nccwpck_require__(52055); exports.UserTokenCredentials = userTokenCredentials_1.UserTokenCredentials; -var authConstants_1 = __nccwpck_require__(26700); +var authConstants_1 = __nccwpck_require__(95954); exports.AuthConstants = authConstants_1.AuthConstants; -var subscriptionUtils_1 = __nccwpck_require__(47813); -exports.buildTenantList = subscriptionUtils_1.buildTenantList; -var azureCliCredentials_1 = __nccwpck_require__(38909); +var azureCliCredentials_1 = __nccwpck_require__(8366); exports.AzureCliCredentials = azureCliCredentials_1.AzureCliCredentials; var login_1 = __nccwpck_require__(29325); exports.interactiveLogin = login_1.interactive; @@ -12183,175495 +9249,107304 @@ exports.loginWithServicePrincipalCertificateWithAuthResponse = login_1.withServi /***/ }), -/***/ 47813: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const msRest = __nccwpck_require__(30812); -const applicationTokenCredentialsBase_1 = __nccwpck_require__(60968); -const authConstants_1 = __nccwpck_require__(26700); -/** - * Builds an array of tenantIds. - * @param credentials - The credentials. - * @param apiVersion - default value 2016-06-01 - * @returns A promise that resolves to an array of tenantIds and rejects with an error. - */ -function buildTenantList(credentials, apiVersion = "2016-06-01") { - return __awaiter(this, void 0, void 0, function* () { - if (credentials.domain && credentials.domain !== authConstants_1.AuthConstants.AAD_COMMON_TENANT) { - return [credentials.domain]; - } - const client = new msRest.ServiceClient(credentials); - const baseUrl = credentials.environment.resourceManagerEndpointUrl; - const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}tenants?api-version=${apiVersion}`; - const req = { - url: reqUrl, - method: "GET" - }; - const res = yield client.sendRequest(req); - const result = []; - if (res.status < 300) { - const tenants = res.parsedBody; - for (const tenant of tenants.value) { - result.push(tenant.tenantId); - } - } - return result; - }); -} -exports.buildTenantList = buildTenantList; -function getSubscriptionsFromTenants(credentials, tenantList, apiVersion = "2016-06-01") { - return __awaiter(this, void 0, void 0, function* () { - let subscriptions = []; - let userType = "user"; - let username; - const originalDomain = credentials.domain; - if (credentials instanceof applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase) { - userType = "servicePrincipal"; - username = credentials.clientId; - } - else { - username = credentials.username; - } - for (const tenant of tenantList) { - credentials.domain = tenant; - const client = new msRest.ServiceClient(credentials); - const baseUrl = credentials.environment.resourceManagerEndpointUrl; - const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}subscriptions?api-version=${apiVersion}`; - const req = { - url: reqUrl, - method: "GET" - }; - const res = yield client.sendRequest(req); - const subscriptionList = res.parsedBody.value; - subscriptions = subscriptions.concat(subscriptionList.map((s) => { - s.tenantId = tenant; - s.user = { name: username, type: userType }; - s.environmentName = credentials.environment.name; - s.name = s.displayName; - s.id = s.subscriptionId; - delete s.displayName; - delete s.subscriptionId; - delete s.subscriptionPolicies; - return s; - })); - } - // Reset the original domain. - credentials.domain = originalDomain; - return subscriptions; - }); -} -exports.getSubscriptionsFromTenants = getSubscriptionsFromTenants; -//# sourceMappingURL=subscriptionUtils.js.map - -/***/ }), - -/***/ 26700: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AuthConstants = { - AAD_COMMON_TENANT: "common", - DEFAULT_ADAL_CLIENT_ID: "04b07795-8ddb-461a-bbee-02f9e1bf7b46", - SDK_INTERNAL_ERROR: "SDK_INTERNAL_ERROR", - DEFAULT_LANGUAGE: "en-us", - AZURE_AUTH_LOCATION: "AZURE_AUTH_LOCATION", - RESOURCE_MANAGER_ENDPOINT: "https://management.azure.com/" -}; -//# sourceMappingURL=authConstants.js.map - -/***/ }), - -/***/ 22709: -/***/ (function(__unused_webpack_module, exports) { - -//! @version @js-joda/core - 3.2.0 -//! @copyright (c) 2015-present, Philipp Thürwächter, Pattrick Hüper & js-joda contributors -//! @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos -//! @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - function createErrorType(name, init, superErrorClass) { - if (superErrorClass === void 0) { - superErrorClass = Error; - } - - function JsJodaException(message) { - if (!Error.captureStackTrace) { - this.stack = new Error().stack; - } else { - Error.captureStackTrace(this, this.constructor); - } - - this.message = message; - init && init.apply(this, arguments); - - this.toString = function () { - return this.name + ": " + this.message; - }; - } - - JsJodaException.prototype = Object.create(superErrorClass.prototype); - JsJodaException.prototype.name = name; - JsJodaException.prototype.constructor = JsJodaException; - return JsJodaException; - } - - var DateTimeException = createErrorType('DateTimeException', messageWithCause); - var DateTimeParseException = createErrorType('DateTimeParseException', messageForDateTimeParseException); - var UnsupportedTemporalTypeException = createErrorType('UnsupportedTemporalTypeException', null, DateTimeException); - var ArithmeticException = createErrorType('ArithmeticException'); - var IllegalArgumentException = createErrorType('IllegalArgumentException'); - var IllegalStateException = createErrorType('IllegalStateException'); - var NullPointerException = createErrorType('NullPointerException'); - - function messageWithCause(message, cause) { - if (cause === void 0) { - cause = null; - } - - var msg = message || this.name; - - if (cause !== null && cause instanceof Error) { - msg += '\n-------\nCaused by: ' + cause.stack + '\n-------\n'; - } - - this.message = msg; - } - - function messageForDateTimeParseException(message, text, index, cause) { - if (text === void 0) { - text = ''; - } - - if (index === void 0) { - index = 0; - } - - if (cause === void 0) { - cause = null; - } - - var msg = message || this.name; - msg += ': ' + text + ', at index: ' + index; - - if (cause !== null && cause instanceof Error) { - msg += '\n-------\nCaused by: ' + cause.stack + '\n-------\n'; - } +/***/ 48566: +/***/ ((module, exports) => { - this.message = msg; +module.exports = exports = abbrev.abbrev = abbrev - this.parsedString = function () { - return text; - }; +abbrev.monkeyPatch = monkeyPatch - this.errorIndex = function () { - return index; - }; - } +function monkeyPatch () { + Object.defineProperty(Array.prototype, 'abbrev', { + value: function () { return abbrev(this) }, + enumerable: false, configurable: true, writable: true + }) - function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; - } + Object.defineProperty(Object.prototype, 'abbrev', { + value: function () { return abbrev(Object.keys(this)) }, + enumerable: false, configurable: true, writable: true + }) +} - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } +function abbrev (list) { + if (arguments.length !== 1 || !Array.isArray(list)) { + list = Array.prototype.slice.call(arguments, 0) + } + for (var i = 0, l = list.length, args = [] ; i < l ; i ++) { + args[i] = typeof list[i] === "string" ? list[i] : String(list[i]) + } - return self; - } + // sort them lexicographically, so that they're next to their nearest kin + args = args.sort(lexSort) - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - function assert(assertion, msg, error) { - if (!assertion) { - if (error) { - throw new error(msg); - } else { - throw new Error(msg); - } - } - } - function requireNonNull(value, parameterName) { - if (value == null) { - throw new NullPointerException(parameterName + ' must not be null'); + // walk through each, seeing how much it has in common with the next and previous + var abbrevs = {} + , prev = "" + for (var i = 0, l = args.length ; i < l ; i ++) { + var current = args[i] + , next = args[i + 1] || "" + , nextMatches = true + , prevMatches = true + if (current === next) continue + for (var j = 0, cl = current.length ; j < cl ; j ++) { + var curChar = current.charAt(j) + nextMatches = nextMatches && curChar === next.charAt(j) + prevMatches = prevMatches && curChar === prev.charAt(j) + if (!nextMatches && !prevMatches) { + j ++ + break } - - return value; } - function requireInstance(value, _class, parameterName) { - if (!(value instanceof _class)) { - throw new IllegalArgumentException(parameterName + ' must be an instance of ' + (_class.name ? _class.name : _class) + (value && value.constructor && value.constructor.name ? ', but is ' + value.constructor.name : '')); - } - - return value; + prev = current + if (j === cl) { + abbrevs[current] = current + continue } - function abstractMethodFail(methodName) { - throw new TypeError('abstract method "' + methodName + '" is not implemented'); + for (var a = current.substr(0, j) ; j <= cl ; j ++) { + abbrevs[a] = current + a += current.charAt(j) } + } + return abbrevs +} - var assert$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - assert: assert, - requireNonNull: requireNonNull, - requireInstance: requireInstance, - abstractMethodFail: abstractMethodFail - }); - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var MAX_SAFE_INTEGER = 9007199254740991; - var MIN_SAFE_INTEGER = -9007199254740991; - var MathUtil = function () { - function MathUtil() {} - - MathUtil.intDiv = function intDiv(x, y) { - var r = x / y; - r = MathUtil.roundDown(r); - return MathUtil.safeZero(r); - }; - - MathUtil.intMod = function intMod(x, y) { - var r = x - MathUtil.intDiv(x, y) * y; - r = MathUtil.roundDown(r); - return MathUtil.safeZero(r); - }; - - MathUtil.roundDown = function roundDown(r) { - if (r < 0) { - return Math.ceil(r); - } else { - return Math.floor(r); - } - }; - - MathUtil.floorDiv = function floorDiv(x, y) { - var r = Math.floor(x / y); - return MathUtil.safeZero(r); - }; - - MathUtil.floorMod = function floorMod(x, y) { - var r = x - MathUtil.floorDiv(x, y) * y; - return MathUtil.safeZero(r); - }; - - MathUtil.safeAdd = function safeAdd(x, y) { - MathUtil.verifyInt(x); - MathUtil.verifyInt(y); - - if (x === 0) { - return MathUtil.safeZero(y); - } - - if (y === 0) { - return MathUtil.safeZero(x); - } - - var r = MathUtil.safeToInt(x + y); - - if (r === x || r === y) { - throw new ArithmeticException('Invalid addition beyond MAX_SAFE_INTEGER!'); - } - - return r; - }; - - MathUtil.safeSubtract = function safeSubtract(x, y) { - MathUtil.verifyInt(x); - MathUtil.verifyInt(y); - - if (x === 0 && y === 0) { - return 0; - } else if (x === 0) { - return MathUtil.safeZero(-1 * y); - } else if (y === 0) { - return MathUtil.safeZero(x); - } - - return MathUtil.safeToInt(x - y); - }; - - MathUtil.safeMultiply = function safeMultiply(x, y) { - MathUtil.verifyInt(x); - MathUtil.verifyInt(y); - - if (x === 1) { - return MathUtil.safeZero(y); - } - - if (y === 1) { - return MathUtil.safeZero(x); - } - - if (x === 0 || y === 0) { - return 0; - } - - var r = MathUtil.safeToInt(x * y); - - if (r / y !== x || x === MIN_SAFE_INTEGER && y === -1 || y === MIN_SAFE_INTEGER && x === -1) { - throw new ArithmeticException('Multiplication overflows: ' + x + ' * ' + y); - } - - return r; - }; - - MathUtil.parseInt = function (_parseInt) { - function parseInt(_x) { - return _parseInt.apply(this, arguments); - } - - parseInt.toString = function () { - return _parseInt.toString(); - }; - - return parseInt; - }(function (value) { - var r = parseInt(value); - return MathUtil.safeToInt(r); - }); - - MathUtil.safeToInt = function safeToInt(value) { - MathUtil.verifyInt(value); - return MathUtil.safeZero(value); - }; - - MathUtil.verifyInt = function verifyInt(value) { - if (value == null) { - throw new ArithmeticException("Invalid value: '" + value + "', using null or undefined as argument"); - } - - if (isNaN(value)) { - throw new ArithmeticException('Invalid int value, using NaN as argument'); - } - - if (value % 1 !== 0) { - throw new ArithmeticException("Invalid value: '" + value + "' is a float"); - } - - if (value > MAX_SAFE_INTEGER || value < MIN_SAFE_INTEGER) { - throw new ArithmeticException('Calculation overflows an int: ' + value); - } - }; - - MathUtil.safeZero = function safeZero(value) { - return value === 0 ? 0 : +value; - }; - - MathUtil.compareNumbers = function compareNumbers(a, b) { - if (a < b) { - return -1; - } - - if (a > b) { - return 1; - } - - return 0; - }; - - MathUtil.smi = function smi(int) { - return int >>> 1 & 0x40000000 | int & 0xBFFFFFFF; - }; - - MathUtil.hash = function hash(number) { - if (number !== number || number === Infinity) { - return 0; - } - - var result = number; - - while (number > 0xFFFFFFFF) { - number /= 0xFFFFFFFF; - result ^= number; - } - - return MathUtil.smi(result); - }; - - MathUtil.hashCode = function hashCode() { - var result = 17; - - for (var _len = arguments.length, numbers = new Array(_len), _key = 0; _key < _len; _key++) { - numbers[_key] = arguments[_key]; - } - - for (var _i = 0, _numbers = numbers; _i < _numbers.length; _i++) { - var n = _numbers[_i]; - result = (result << 5) - result + MathUtil.hash(n); - } - - return MathUtil.hash(result); - }; - - return MathUtil; - }(); - MathUtil.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER; - MathUtil.MIN_SAFE_INTEGER = MIN_SAFE_INTEGER; - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var Enum = function () { - function Enum(name) { - this._name = name; - } - - var _proto = Enum.prototype; - - _proto.equals = function equals(other) { - return this === other; - }; - - _proto.toString = function toString() { - return this._name; - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return Enum; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalAmount = function () { - function TemporalAmount() {} - - var _proto = TemporalAmount.prototype; - - _proto.get = function get(unit) { - abstractMethodFail('get'); - }; - - _proto.units = function units() { - abstractMethodFail('units'); - }; - - _proto.addTo = function addTo(temporal) { - abstractMethodFail('addTo'); - }; - - _proto.subtractFrom = function subtractFrom(temporal) { - abstractMethodFail('subtractFrom'); - }; - - return TemporalAmount; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalUnit = function () { - function TemporalUnit() {} - - var _proto = TemporalUnit.prototype; - - _proto.duration = function duration() { - abstractMethodFail('duration'); - }; - - _proto.isDurationEstimated = function isDurationEstimated() { - abstractMethodFail('isDurationEstimated'); - }; - - _proto.isDateBased = function isDateBased() { - abstractMethodFail('isDateBased'); - }; - - _proto.isTimeBased = function isTimeBased() { - abstractMethodFail('isTimeBased'); - }; - - _proto.isSupportedBy = function isSupportedBy(temporal) { - abstractMethodFail('isSupportedBy'); - }; - - _proto.addTo = function addTo(dateTime, periodToAdd) { - abstractMethodFail('addTo'); - }; - - _proto.between = function between(temporal1, temporal2) { - abstractMethodFail('between'); - }; - - return TemporalUnit; - }(); - - var Duration = function (_TemporalAmount) { - _inheritsLoose(Duration, _TemporalAmount); - - function Duration(seconds, nanos) { - var _this; - - _this = _TemporalAmount.call(this) || this; - _this._seconds = MathUtil.safeToInt(seconds); - _this._nanos = MathUtil.safeToInt(nanos); - return _this; - } - - Duration.ofDays = function ofDays(days) { - return Duration._create(MathUtil.safeMultiply(days, LocalTime.SECONDS_PER_DAY), 0); - }; - - Duration.ofHours = function ofHours(hours) { - return Duration._create(MathUtil.safeMultiply(hours, LocalTime.SECONDS_PER_HOUR), 0); - }; - - Duration.ofMinutes = function ofMinutes(minutes) { - return Duration._create(MathUtil.safeMultiply(minutes, LocalTime.SECONDS_PER_MINUTE), 0); - }; - - Duration.ofSeconds = function ofSeconds(seconds, nanoAdjustment) { - if (nanoAdjustment === void 0) { - nanoAdjustment = 0; - } - - var secs = MathUtil.safeAdd(seconds, MathUtil.floorDiv(nanoAdjustment, LocalTime.NANOS_PER_SECOND)); - var nos = MathUtil.floorMod(nanoAdjustment, LocalTime.NANOS_PER_SECOND); - return Duration._create(secs, nos); - }; - - Duration.ofMillis = function ofMillis(millis) { - var secs = MathUtil.intDiv(millis, 1000); - var mos = MathUtil.intMod(millis, 1000); - - if (mos < 0) { - mos += 1000; - secs--; - } - - return Duration._create(secs, mos * 1000000); - }; - - Duration.ofNanos = function ofNanos(nanos) { - var secs = MathUtil.intDiv(nanos, LocalTime.NANOS_PER_SECOND); - var nos = MathUtil.intMod(nanos, LocalTime.NANOS_PER_SECOND); - - if (nos < 0) { - nos += LocalTime.NANOS_PER_SECOND; - secs--; - } - - return this._create(secs, nos); - }; - - Duration.of = function of(amount, unit) { - return Duration.ZERO.plus(amount, unit); - }; - - Duration.from = function from(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount); - var duration = Duration.ZERO; - amount.units().forEach(function (unit) { - duration = duration.plus(amount.get(unit), unit); - }); - return duration; - }; - - Duration.between = function between(startInclusive, endExclusive) { - requireNonNull(startInclusive, 'startInclusive'); - requireNonNull(endExclusive, 'endExclusive'); - var secs = startInclusive.until(endExclusive, ChronoUnit.SECONDS); - var nanos = 0; - - if (startInclusive.isSupported(ChronoField.NANO_OF_SECOND) && endExclusive.isSupported(ChronoField.NANO_OF_SECOND)) { - try { - var startNos = startInclusive.getLong(ChronoField.NANO_OF_SECOND); - nanos = endExclusive.getLong(ChronoField.NANO_OF_SECOND) - startNos; - - if (secs > 0 && nanos < 0) { - nanos += LocalTime.NANOS_PER_SECOND; - } else if (secs < 0 && nanos > 0) { - nanos -= LocalTime.NANOS_PER_SECOND; - } else if (secs === 0 && nanos !== 0) { - var adjustedEnd = endExclusive.with(ChronoField.NANO_OF_SECOND, startNos); - secs = startInclusive.until(adjustedEnd, ChronoUnit.SECONDS); - } - } catch (e) {} - } - - return this.ofSeconds(secs, nanos); - }; - - Duration.parse = function parse(text) { - requireNonNull(text, 'text'); - var PATTERN = new RegExp('([-+]?)P(?:([-+]?[0-9]+)D)?(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?', 'i'); - var matches = PATTERN.exec(text); - - if (matches !== null) { - if ('T' === matches[3] === false) { - var negate = '-' === matches[1]; - var dayMatch = matches[2]; - var hourMatch = matches[4]; - var minuteMatch = matches[5]; - var secondMatch = matches[6]; - var fractionMatch = matches[7]; - - if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null) { - var daysAsSecs = Duration._parseNumber(text, dayMatch, LocalTime.SECONDS_PER_DAY, 'days'); - - var hoursAsSecs = Duration._parseNumber(text, hourMatch, LocalTime.SECONDS_PER_HOUR, 'hours'); - - var minsAsSecs = Duration._parseNumber(text, minuteMatch, LocalTime.SECONDS_PER_MINUTE, 'minutes'); - - var seconds = Duration._parseNumber(text, secondMatch, 1, 'seconds'); - - var negativeSecs = secondMatch != null && secondMatch.charAt(0) === '-'; +function lexSort (a, b) { + return a === b ? 0 : a > b ? 1 : -1 +} - var nanos = Duration._parseFraction(text, fractionMatch, negativeSecs ? -1 : 1); - try { - return Duration._create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos); - } catch (ex) { - throw new DateTimeParseException('Text cannot be parsed to a Duration: overflow', text, 0, ex); - } - } - } - } +/***/ }), - throw new DateTimeParseException('Text cannot be parsed to a Duration', text, 0); - }; +/***/ 35894: +/***/ ((module, exports, __nccwpck_require__) => { - Duration._parseNumber = function _parseNumber(text, parsed, multiplier, errorText) { - if (parsed == null) { - return 0; - } +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); + +var ac = __nccwpck_require__(69775); +var authParams = __nccwpck_require__(74854); +var logging = __nccwpck_require__(92288); +var MemoryCache = __nccwpck_require__(92474); + +exports = {}; + +exports.Logging = logging.Logging; +exports.AuthenticationContext = ac.AuthenticationContext; +exports.setGlobalADALOptions = ac.setGlobalADALOptions; +exports.getGlobalADALOptions = ac.getGlobalADALOptions; +exports.MemoryCache = MemoryCache; +_.extend(exports, authParams); + +/** + * Creates a new AuthenticationContext object. By default the authority will be checked against + * a list of known Azure Active Directory authorities. If the authority is not recognized as + * one of these well known authorities then token acquisition will fail. This behavior can be + * turned off via the validateAuthority parameter below. + * @function + * @param {string} authority A URL that identifies a token authority. + * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true. + * @returns {AuthenticationContext} A new authentication context. + */ +exports.createAuthenticationContext = function(authority, validateAuthority) { + return new ac.AuthenticationContext(authority, validateAuthority); +}; + +module.exports = exports; - try { - if (parsed[0] === '+') { - parsed = parsed.substring(1); - } - return MathUtil.safeMultiply(parseFloat(parsed), multiplier); - } catch (ex) { - throw new DateTimeParseException('Text cannot be parsed to a Duration: ' + errorText, text, 0, ex); - } - }; +/***/ }), - Duration._parseFraction = function _parseFraction(text, parsed, negate) { - if (parsed == null || parsed.length === 0) { - return 0; - } +/***/ 62432: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - parsed = (parsed + '000000000').substring(0, 9); - return parseFloat(parsed) * negate; - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +var constants = __nccwpck_require__(10282); + +var UserCodeResponseFields = constants.UserCodeResponseFields; + +var argumentValidation = { + /** + * Throws if the passed in parameter is not a string. + * @param {string} param The parameter to validate. + * @param {string} name The name of the parameter being validated. + * @throws {Error} If the parameter is not a valid string. + */ + validateStringParameter : function(param, name) { + if (!param) { + throw new Error('The ' + name + ' parameter is required.'); + } + if (!_.isString(param)) { + throw new Error('The ' + name + ' parameter must be of type String.'); + } + }, + + /** + * Validates that the callback passed in {@link AuthenticationContext.acquireToken} is a function + * @param {AcquireTokenCallback} callback + * @throws {Error} If the callback parameter is not a function + */ + validateCallbackType : function(callback) { + if (!callback || !_.isFunction(callback)) { + throw new Error('acquireToken requires a function callback parameter.'); + } + }, + + validateUserCodeInfo : function(userCodeInfo) { + if (!userCodeInfo){ + throw new Error('The userCodeInfo parameter is required'); + } + + if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.DEVICE_CODE)){ + throw new Error('The userCodeInfo is missing device_code'); + } + + if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.INTERVAL)){ + throw new Error('The userCodeInfo is missing interval'); + } + + if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.EXPIRES_IN)){ + throw new Error('The userCodeInfo is missing expires_in'); + } + } +}; + +module.exports = argumentValidation; - Duration._create = function _create() { - if (arguments.length <= 2) { - return Duration._createSecondsNanos(arguments[0], arguments[1]); - } else { - return Duration._createNegateDaysHoursMinutesSecondsNanos(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); - } - }; - Duration._createNegateDaysHoursMinutesSecondsNanos = function _createNegateDaysHoursMinutesSecondsNanos(negate, daysAsSecs, hoursAsSecs, minsAsSecs, secs, nanos) { - var seconds = MathUtil.safeAdd(daysAsSecs, MathUtil.safeAdd(hoursAsSecs, MathUtil.safeAdd(minsAsSecs, secs))); +/***/ }), - if (negate) { - return Duration.ofSeconds(seconds, nanos).negated(); - } +/***/ 69775: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return Duration.ofSeconds(seconds, nanos); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var argument = __nccwpck_require__(62432); +var Authority = __nccwpck_require__(19270)/* .Authority */ .W; +var TokenRequest = __nccwpck_require__(21178); +var CodeRequest = __nccwpck_require__(66576); +var createLogContext = __nccwpck_require__(92288).createLogContext; +var MemoryCache = __nccwpck_require__(92474); +var util = __nccwpck_require__(5336); +var constants = __nccwpck_require__(10282); + +var globalADALOptions = {}; +var globalCache = new MemoryCache(); + + +/** + * This function is used to add or remove entries from a TokenCache + * @typedef {function} ModifyCacheFunction + * @param {Array} entries An array of entries to either add or remove from the TokenCache + * @param {function} callback A callback function to call when the add or remove operation is complete. + * This function can take a single error argument. + */ + +/** + * This function is called by a TokenCache when a find operation completes. + * @callback TokenCacheFindCallback + * @param {Error} [err] If an error occurred during the find operation then it should be passed here. + * @param {Array} [entries] If the find operation was succesful then the matched entries should be returned here. + */ + +/** + * This function is called by ADAL to query a TokenCache. The query parameter is + * a flat object which must be compared against entries in the cache. An entry + * matches if it has all of the fields in the query and the values of those fields match + * the values in the query. A matched object may have more fields than the query object. + * @typedef {function} FindCacheFunction + * @param {object} query This object should be compared to cache entries and matches should be returned. + * @param {TokenCacheFindCallback} callback This callback should be called when the find operation is complete. + */ + +/** + * This is an interface that can be implemented to provide custom token cache persistence. + * @public + * @class TokenCache + * @property {ModifyCacheFunction} add Called by ADAL when entries should be added to the cache. + * @property {ModifyCacheFunction} remove Called by ADAL when entries should be removed from the cache. + * @property {FindCacheFunction} find Called when ADAL needs to find entries in the cache. + */ + + +/** + * Creates a new AuthenticationContext object. By default the authority will be checked against + * a list of known Azure Active Directory authorities. If the authority is not recognized as + * one of these well known authorities then token acquisition will fail. This behavior can be + * turned off via the validateAuthority parameter below. + * @constructor + * @param {string} authority A URL that identifies a token authority. + * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true. + * @param {TokenCache} [cache] Sets the token cache used by this AuthenticationContext instance. If this parameter is not set + * then a default, in memory cache is used. The default in memory cache is global to the process and is + * shared by all AuthenticationContexts that are created with an empty cache parameter. To control the + * scope and lifetime of a cache you can either create a {@link MemoryCache} instance and pass it when + * constructing an AuthenticationContext or implement a custom {@link TokenCache} and pass that. Cache + * instances passed at AuthenticationContext construction time are only used by that instance of + * the AuthenticationContext and are not shared unless it has been manually passed during the + * construction of other AuthenticationContexts. + * + */ +function AuthenticationContext(authority, validateAuthority, cache) { + var validate = (validateAuthority === undefined || validateAuthority === null || validateAuthority); + + this._authority = new Authority(authority, validate); + this._oauth2client = null; + this._correlationId = null; + this._callContext = { options : globalADALOptions }; + this._cache = cache || globalCache; + this._tokenRequestWithUserCode = {}; +} + +/** + * Gets the authority url this AuthenticationContext was constructed with. + * @instance + * @memberOf AuthenticationContext + * @type {string} + * @name authority + */ +Object.defineProperty(AuthenticationContext.prototype, 'authority', { + get: function () { + return this._authority.url; + } +}); + +/** + * Gets/Sets the correlation id that will be used for the next acquireToken request. + * @instance + * @memberOf AuthenticationContext + * @type {string} + * @name correlationId + */ +Object.defineProperty(AuthenticationContext.prototype, 'correlationId', { + get: function () { + return this._correlationId; + }, + set: function (id) { + this._correlationId = id; + } +}); + +/** + * Get/Sets options that are applied to requests generated by this AuthenticationContext instance. + * @instance + * @memberOf AuthenticationContext + * @type {object} + * @name options + */ +Object.defineProperty(AuthenticationContext.prototype, 'options', { + get: function() { + return this._callContext.options; + }, + set: function (value) { + this._callContext.options = value; + } +}); + +/** + * Get the token cache used by this AuthenticationContext instance. + * @instance + * @memberOf AuthenticationContext + * @type {object} + * @name cache + */ +Object.defineProperty(AuthenticationContext.prototype, 'cache', { + get: function() { + return this._cache; + }, +}); + +/** + * This will be returned in case the OAuth 2 service returns an error. + * @typedef ErrorResponse + * @property {string} [error] A server error. + * @property {string} [errorDescription] A description of the error returned. + */ + +/** + * Contains tokens and metadata upon successful completion of an acquireToken call. + * @typedef TokenResponse + * @property {string} tokenType The type of token returned. + * @property {string} accessToken The returned access token. + * @property {string} [refreshToken] A refresh token. + * @property {Date} [createdOn] The date on which the access token was created. + * @property {Date} expiresOn The Date on which the access token expires. + * @property {int} expiresIn The amount of time, in seconds, for which the token is valid. + * @property {string} [userId] An id for the user. May be a displayable value if is_user_id_displayable is true. + * @property {bool} [isUserIdDisplayable] Indicates whether the user_id property will be meaningful if displayed to a user. + * @property {string} [tenantId] The identifier of the tenant under which the access token was issued. + * @property {string} [givenName] The given name of the principal represented by the access token. + * @property {string} [familyName] The family name of the principal represented by the access token. + * @property {string} [identityProvider] Identifies the identity provider that issued the access token. + */ + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback AcquireTokenCallback + * @param {Error} [error] If the request fails this parameter will contain an Error object. + * @param {TokenResponse|ErrorResponse} [response] On a succesful request returns a {@link TokenResposne}. + */ + +/** + * This function implements code that is common to all acquireToken flows. + * @private + * @param {AcquireTokenCallback} callback + * @param {Function} tokenFunction This is the function to call to actually acquire the token after common flow has completed. + */ +AuthenticationContext.prototype._acquireToken = function(callback, tokenFunction) { + var self = this; + this._callContext._logContext = createLogContext(this.correlationId); + this._authority.validate(this._callContext, function(err) { + if (err) { + callback(err); + return; + } + tokenFunction.call(self); + }); +}; + +AuthenticationContext.prototype._acquireUserCode = function (callback, codeFunction) { + var self = this; + this._callContext._logContext = createLogContext(this.correlationId); + this._authority.validate(this._callContext, function (err) { + if (err) { + callback(err); + return; + } + + codeFunction.call(self); + }); +}; + +/** + * Gets a token for a given resource. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} [userId] The username of the user on behalf this application is authenticating. + * @param {string} [clientId] The OAuth client id of the calling application. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireToken = function(resource, userId, clientId, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(clientId, 'clientId'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); + tokenRequest.getTokenFromCacheWithRefresh(userId, callback); + }); +}; + +/** + * Gets a token for a given resource. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} username The username of the user on behalf this application is authenticating. + * @param {string} password The password of the user named in the username parameter. + * @param {string} clientId The OAuth client id of the calling application. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithUsernamePassword = function(resource, username, password, clientId, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(username, 'username'); + argument.validateStringParameter(password, 'password'); + argument.validateStringParameter(clientId, 'clientId'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); + tokenRequest.getTokenWithUsernamePassword(username, password, callback); + }); +}; + +/** + * Gets a token for a given resource. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} clientSecret The OAuth client secret of the calling application. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithClientCredentials = function(resource, clientId, clientSecret, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(clientId, 'clientId'); + argument.validateStringParameter(clientSecret, 'clientSecret'); + } catch (err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); + tokenRequest.getTokenWithClientCredentials(clientSecret, callback); + }); +}; + +/** + * Gets a token for a given resource. + * @param {string} authorizationCode An authorization code returned from a client. + * @param {string} redirectUri The redirect uri that was used in the authorize call. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} clientSecret The OAuth client secret of the calling application. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithAuthorizationCode = function(authorizationCode, redirectUri, resource, clientId, clientSecret, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(authorizationCode, 'authorizationCode'); + argument.validateStringParameter(redirectUri, 'redirectUri'); + argument.validateStringParameter(clientId, 'clientId'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, redirectUri); + tokenRequest.getTokenWithAuthorizationCode(authorizationCode, clientSecret, callback); + }); +}; + +/** + * Gets a new access token via a previously issued refresh token. + * @param {string} refreshToken A refresh token returned in a tokne response from a previous invocation of acquireToken. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} [clientSecret] The OAuth client secret of the calling application. (Note: this parameter is a late addition. + * This parameter may be ommitted entirely so that applications built before this change will continue + * to work unchanged.) + * @param {string} resource The OAuth resource for which a token is being request. This parameter is optional and can be set to null. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithRefreshToken = function(refreshToken, clientId, clientSecret, resource, callback) { + // Fix up the arguments. Older clients may pass fewer arguments as the clientSecret paramter did not always exist. + // The code needs to make adjustments for those clients. + var clientSecretPresent = (5 === arguments.length); + var actualClientSecret = clientSecretPresent ? clientSecret : null; + var actualCallback = clientSecretPresent ? arguments[4] : arguments[3]; + var actualResource = clientSecretPresent ? arguments[3] : arguments[2]; + + argument.validateCallbackType(actualCallback); + try { + argument.validateStringParameter(refreshToken, 'refreshToken'); + argument.validateStringParameter(clientId, 'clientId'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, actualResource); + tokenRequest.getTokenWithRefreshToken(refreshToken, actualClientSecret, actualCallback); + }); +}; + +/** + * Gets a new access token using via a certificate credential. + * @param {string} resource A URI that identifies the resource for which the token is valid. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint A hex encoded thumbprint of the certificate. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithClientCertificate = function(resource, clientId, certificate, thumbprint, callback) { + argument.validateCallbackType(callback); + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(certificate, 'certificate'); + argument.validateStringParameter(thumbprint, 'thumbprint'); + } catch(err) { + callback(err); + return; + } + + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); + tokenRequest.getTokenWithCertificate(certificate, thumbprint, callback); + }); +}; + +/** + * Gets the userCodeInfo which contains user_code, device_code for authenticating user on device. + * @param {string} resource A URI that identifies the resource for which the device_code and user_code is valid for. + * @param {string} clientId The OAuth client id of the calling application. + * @param {string} language The language code specifying how the message should be localized to. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireUserCode = function(resource, clientId, language, callback) { + argument.validateCallbackType(callback); + + try { + argument.validateStringParameter(resource, 'resource'); + argument.validateStringParameter(clientId, 'clientId'); + } catch (err) { + callback(err); + return; + } + + this._acquireUserCode(callback, function () { + var codeRequest = new CodeRequest(this._callContext, this, clientId, resource); + codeRequest.getUserCodeInfo(language, callback); + }); +}; + +/** + * Gets a new access token using via a device code. + * @note This method doesn't look up the cache, it only stores the returned token into cache. To look up cache before making a new request, + * please use acquireToken. + * @param {string} clientId The OAuth client id of the calling application. + * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.acquireTokenWithDeviceCode = function(resource, clientId, userCodeInfo, callback){ + argument.validateCallbackType(callback); + + try{ + argument.validateUserCodeInfo(userCodeInfo); + } catch (err) { + callback(err); + return; + } + + var self = this; + this._acquireToken(callback, function() { + var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, null); + self._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]] = tokenRequest; + tokenRequest.getTokenWithDeviceCode(userCodeInfo, callback); + }) +}; + +/** + * Cancels the polling request to get token with device code. + * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. + * @param {AcquireTokenCallback} callback The callback function. + */ +AuthenticationContext.prototype.cancelRequestToGetTokenWithDeviceCode = function (userCodeInfo, callback) { + argument.validateCallbackType(callback); + + try { + argument.validateUserCodeInfo(userCodeInfo); + } catch (err) { + callback(err); + return; + } + + if (!this._tokenRequestWithUserCode || !this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]) { + callback(new Error('No acquireTokenWithDeviceCodeRequest existed to be cancelled')); + return; + } + + var tokenRequestToBeCancelled = this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]; + tokenRequestToBeCancelled.cancelTokenRequestWithDeviceCode(); + + delete this._tokenRequestWithUserCode[constants.UserCodeResponseFields.DEVICE_CODE]; +}; + +var exports = { + AuthenticationContext : AuthenticationContext, + setGlobalADALOptions : function(options) { + globalADALOptions = options; + }, + getGlobalADALOptions : function() { + return globalADALOptions; + } +}; + +util.adalInit(); +module.exports = exports; - Duration._createSecondsNanos = function _createSecondsNanos(seconds, nanoAdjustment) { - if (seconds === void 0) { - seconds = 0; - } - if (nanoAdjustment === void 0) { - nanoAdjustment = 0; - } +/***/ }), - if (seconds === 0 && nanoAdjustment === 0) { - return Duration.ZERO; - } +/***/ 74854: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return new Duration(seconds, nanoAdjustment); - }; - - var _proto = Duration.prototype; - - _proto.get = function get(unit) { - if (unit === ChronoUnit.SECONDS) { - return this._seconds; - } else if (unit === ChronoUnit.NANOS) { - return this._nanos; - } else { - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } - }; - - _proto.units = function units() { - return [ChronoUnit.SECONDS, ChronoUnit.NANOS]; - }; - - _proto.isZero = function isZero() { - return this._seconds === 0 && this._nanos === 0; - }; - - _proto.isNegative = function isNegative() { - return this._seconds < 0; - }; - - _proto.seconds = function seconds() { - return this._seconds; - }; - - _proto.nano = function nano() { - return this._nanos; - }; - - _proto.withSeconds = function withSeconds(seconds) { - return Duration._create(seconds, this._nanos); - }; - - _proto.withNanos = function withNanos(nanoOfSecond) { - ChronoField.NANO_OF_SECOND.checkValidIntValue(nanoOfSecond); - return Duration._create(this._seconds, nanoOfSecond); - }; - - _proto.plusDuration = function plusDuration(duration) { - requireNonNull(duration, 'duration'); - return this.plus(duration.seconds(), duration.nano()); - }; - - _proto.plus = function plus(durationOrNumber, unitOrNumber) { - if (arguments.length === 1) { - return this.plusDuration(durationOrNumber); - } else if (arguments.length === 2 && unitOrNumber instanceof TemporalUnit) { - return this.plusAmountUnit(durationOrNumber, unitOrNumber); - } else { - return this.plusSecondsNanos(durationOrNumber, unitOrNumber); - } - }; - - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(amountToAdd, 'amountToAdd'); - requireNonNull(unit, 'unit'); - - if (unit === ChronoUnit.DAYS) { - return this.plusSecondsNanos(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_DAY), 0); - } - - if (unit.isDurationEstimated()) { - throw new UnsupportedTemporalTypeException('Unit must not have an estimated duration'); - } - - if (amountToAdd === 0) { - return this; - } - - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this.plusNanos(amountToAdd); - - case ChronoUnit.MICROS: - return this.plusSecondsNanos(MathUtil.intDiv(amountToAdd, 1000000 * 1000) * 1000, MathUtil.intMod(amountToAdd, 1000000 * 1000) * 1000); - - case ChronoUnit.MILLIS: - return this.plusMillis(amountToAdd); - - case ChronoUnit.SECONDS: - return this.plusSeconds(amountToAdd); - } - - return this.plusSecondsNanos(MathUtil.safeMultiply(unit.duration().seconds(), amountToAdd), 0); - } - - var duration = unit.duration().multipliedBy(amountToAdd); - return this.plusSecondsNanos(duration.seconds(), duration.nano()); - }; - - _proto.plusDays = function plusDays(daysToAdd) { - return this.plusSecondsNanos(MathUtil.safeMultiply(daysToAdd, LocalTime.SECONDS_PER_DAY), 0); - }; - - _proto.plusHours = function plusHours(hoursToAdd) { - return this.plusSecondsNanos(MathUtil.safeMultiply(hoursToAdd, LocalTime.SECONDS_PER_HOUR), 0); - }; - - _proto.plusMinutes = function plusMinutes(minutesToAdd) { - return this.plusSecondsNanos(MathUtil.safeMultiply(minutesToAdd, LocalTime.SECONDS_PER_MINUTE), 0); - }; - - _proto.plusSeconds = function plusSeconds(secondsToAdd) { - return this.plusSecondsNanos(secondsToAdd, 0); - }; - - _proto.plusMillis = function plusMillis(millisToAdd) { - return this.plusSecondsNanos(MathUtil.intDiv(millisToAdd, 1000), MathUtil.intMod(millisToAdd, 1000) * 1000000); - }; - - _proto.plusNanos = function plusNanos(nanosToAdd) { - return this.plusSecondsNanos(0, nanosToAdd); - }; - - _proto.plusSecondsNanos = function plusSecondsNanos(secondsToAdd, nanosToAdd) { - requireNonNull(secondsToAdd, 'secondsToAdd'); - requireNonNull(nanosToAdd, 'nanosToAdd'); - - if (secondsToAdd === 0 && nanosToAdd === 0) { - return this; - } - - var epochSec = MathUtil.safeAdd(this._seconds, secondsToAdd); - epochSec = MathUtil.safeAdd(epochSec, MathUtil.intDiv(nanosToAdd, LocalTime.NANOS_PER_SECOND)); - nanosToAdd = MathUtil.intMod(nanosToAdd, LocalTime.NANOS_PER_SECOND); - var nanoAdjustment = MathUtil.safeAdd(this._nanos, nanosToAdd); - return Duration.ofSeconds(epochSec, nanoAdjustment); - }; - - _proto.minus = function minus(durationOrNumber, unit) { - if (arguments.length === 1) { - return this.minusDuration(durationOrNumber); - } else { - return this.minusAmountUnit(durationOrNumber, unit); - } - }; - - _proto.minusDuration = function minusDuration(duration) { - requireNonNull(duration, 'duration'); - var secsToSubtract = duration.seconds(); - var nanosToSubtract = duration.nano(); - - if (secsToSubtract === MIN_SAFE_INTEGER) { - return this.plus(MAX_SAFE_INTEGER, -nanosToSubtract); - } - - return this.plus(-secsToSubtract, -nanosToSubtract); - }; - - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(amountToSubtract, 'amountToSubtract'); - requireNonNull(unit, 'unit'); - return amountToSubtract === MIN_SAFE_INTEGER ? this.plusAmountUnit(MAX_SAFE_INTEGER, unit) : this.plusAmountUnit(-amountToSubtract, unit); - }; - - _proto.minusDays = function minusDays(daysToSubtract) { - return daysToSubtract === MIN_SAFE_INTEGER ? this.plusDays(MAX_SAFE_INTEGER) : this.plusDays(-daysToSubtract); - }; - - _proto.minusHours = function minusHours(hoursToSubtract) { - return hoursToSubtract === MIN_SAFE_INTEGER ? this.plusHours(MAX_SAFE_INTEGER) : this.plusHours(-hoursToSubtract); - }; - - _proto.minusMinutes = function minusMinutes(minutesToSubtract) { - return minutesToSubtract === MIN_SAFE_INTEGER ? this.plusMinutes(MAX_SAFE_INTEGER) : this.plusMinutes(-minutesToSubtract); - }; - - _proto.minusSeconds = function minusSeconds(secondsToSubtract) { - return secondsToSubtract === MIN_SAFE_INTEGER ? this.plusSeconds(MAX_SAFE_INTEGER) : this.plusSeconds(-secondsToSubtract); - }; - - _proto.minusMillis = function minusMillis(millisToSubtract) { - return millisToSubtract === MIN_SAFE_INTEGER ? this.plusMillis(MAX_SAFE_INTEGER) : this.plusMillis(-millisToSubtract); - }; - - _proto.minusNanos = function minusNanos(nanosToSubtract) { - return nanosToSubtract === MIN_SAFE_INTEGER ? this.plusNanos(MAX_SAFE_INTEGER) : this.plusNanos(-nanosToSubtract); - }; - - _proto.multipliedBy = function multipliedBy(multiplicand) { - if (multiplicand === 0) { - return Duration.ZERO; - } - - if (multiplicand === 1) { - return this; - } - - var secs = MathUtil.safeMultiply(this._seconds, multiplicand); - var nos = MathUtil.safeMultiply(this._nanos, multiplicand); - secs = secs + MathUtil.intDiv(nos, LocalTime.NANOS_PER_SECOND); - nos = MathUtil.intMod(nos, LocalTime.NANOS_PER_SECOND); - return Duration.ofSeconds(secs, nos); - }; - - _proto.dividedBy = function dividedBy(divisor) { - if (divisor === 0) { - throw new ArithmeticException('Cannot divide by zero'); - } - - if (divisor === 1) { - return this; - } - - var secs = MathUtil.intDiv(this._seconds, divisor); - var secsMod = MathUtil.roundDown((this._seconds / divisor - secs) * LocalTime.NANOS_PER_SECOND); - var nos = MathUtil.intDiv(this._nanos, divisor); - nos = secsMod + nos; - return Duration.ofSeconds(secs, nos); - }; - - _proto.negated = function negated() { - return this.multipliedBy(-1); - }; - - _proto.abs = function abs() { - return this.isNegative() ? this.negated() : this; - }; - - _proto.addTo = function addTo(temporal) { - requireNonNull(temporal, 'temporal'); - - if (this._seconds !== 0) { - temporal = temporal.plus(this._seconds, ChronoUnit.SECONDS); - } - - if (this._nanos !== 0) { - temporal = temporal.plus(this._nanos, ChronoUnit.NANOS); - } - - return temporal; - }; - - _proto.subtractFrom = function subtractFrom(temporal) { - requireNonNull(temporal, 'temporal'); - - if (this._seconds !== 0) { - temporal = temporal.minus(this._seconds, ChronoUnit.SECONDS); - } - - if (this._nanos !== 0) { - temporal = temporal.minus(this._nanos, ChronoUnit.NANOS); - } - - return temporal; - }; - - _proto.toDays = function toDays() { - return MathUtil.intDiv(this._seconds, LocalTime.SECONDS_PER_DAY); - }; - - _proto.toHours = function toHours() { - return MathUtil.intDiv(this._seconds, LocalTime.SECONDS_PER_HOUR); - }; - - _proto.toMinutes = function toMinutes() { - return MathUtil.intDiv(this._seconds, LocalTime.SECONDS_PER_MINUTE); - }; - - _proto.toMillis = function toMillis() { - var millis = Math.round(MathUtil.safeMultiply(this._seconds, 1000)); - millis = MathUtil.safeAdd(millis, MathUtil.intDiv(this._nanos, 1000000)); - return millis; - }; - - _proto.toNanos = function toNanos() { - var totalNanos = MathUtil.safeMultiply(this._seconds, LocalTime.NANOS_PER_SECOND); - totalNanos = MathUtil.safeAdd(totalNanos, this._nanos); - return totalNanos; - }; - - _proto.compareTo = function compareTo(otherDuration) { - requireNonNull(otherDuration, 'otherDuration'); - requireInstance(otherDuration, Duration, 'otherDuration'); - var cmp = MathUtil.compareNumbers(this._seconds, otherDuration.seconds()); - - if (cmp !== 0) { - return cmp; - } - - return this._nanos - otherDuration.nano(); - }; - - _proto.equals = function equals(otherDuration) { - if (this === otherDuration) { - return true; - } - - if (otherDuration instanceof Duration) { - return this.seconds() === otherDuration.seconds() && this.nano() === otherDuration.nano(); - } - - return false; - }; - - _proto.toString = function toString() { - if (this === Duration.ZERO) { - return 'PT0S'; - } - - var hours = MathUtil.intDiv(this._seconds, LocalTime.SECONDS_PER_HOUR); - var minutes = MathUtil.intDiv(MathUtil.intMod(this._seconds, LocalTime.SECONDS_PER_HOUR), LocalTime.SECONDS_PER_MINUTE); - var secs = MathUtil.intMod(this._seconds, LocalTime.SECONDS_PER_MINUTE); - var rval = 'PT'; - - if (hours !== 0) { - rval += hours + 'H'; - } - - if (minutes !== 0) { - rval += minutes + 'M'; - } - - if (secs === 0 && this._nanos === 0 && rval.length > 2) { - return rval; - } - - if (secs < 0 && this._nanos > 0) { - if (secs === -1) { - rval += '-0'; - } else { - rval += secs + 1; - } - } else { - rval += secs; - } - - if (this._nanos > 0) { - rval += '.'; - var nanoString; - - if (secs < 0) { - nanoString = '' + (2 * LocalTime.NANOS_PER_SECOND - this._nanos); - } else { - nanoString = '' + (LocalTime.NANOS_PER_SECOND + this._nanos); - } - - nanoString = nanoString.slice(1, nanoString.length); - rval += nanoString; - - while (rval.charAt(rval.length - 1) === '0') { - rval = rval.slice(0, rval.length - 1); - } - } - - rval += 'S'; - return rval; - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return Duration; - }(TemporalAmount); - function _init() { - Duration.ZERO = new Duration(0, 0); - } - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE.md in the root directory of this source tree) - */ - var YearConstants = function YearConstants() {}; - function _init$1() { - YearConstants.MIN_VALUE = -999999; - YearConstants.MAX_VALUE = 999999; - } - - var ChronoUnit = function (_TemporalUnit) { - _inheritsLoose(ChronoUnit, _TemporalUnit); - - function ChronoUnit(name, estimatedDuration) { - var _this; - - _this = _TemporalUnit.call(this) || this; - _this._name = name; - _this._duration = estimatedDuration; - return _this; - } - - var _proto = ChronoUnit.prototype; - - _proto.duration = function duration() { - return this._duration; - }; - - _proto.isDurationEstimated = function isDurationEstimated() { - return this.isDateBased() || this === ChronoUnit.FOREVER; - }; - - _proto.isDateBased = function isDateBased() { - return this.compareTo(ChronoUnit.DAYS) >= 0 && this !== ChronoUnit.FOREVER; - }; - - _proto.isTimeBased = function isTimeBased() { - return this.compareTo(ChronoUnit.DAYS) < 0; - }; - - _proto.isSupportedBy = function isSupportedBy(temporal) { - if (this === ChronoUnit.FOREVER) { - return false; - } - - try { - temporal.plus(1, this); - return true; - } catch (e) { - try { - temporal.plus(-1, this); - return true; - } catch (e2) { - return false; - } - } - }; - - _proto.addTo = function addTo(temporal, amount) { - return temporal.plus(amount, this); - }; - - _proto.between = function between(temporal1, temporal2) { - return temporal1.until(temporal2, this); - }; - - _proto.toString = function toString() { - return this._name; - }; - - _proto.compareTo = function compareTo(other) { - return this.duration().compareTo(other.duration()); - }; - - return ChronoUnit; - }(TemporalUnit); - function _init$2() { - ChronoUnit.NANOS = new ChronoUnit('Nanos', Duration.ofNanos(1)); - ChronoUnit.MICROS = new ChronoUnit('Micros', Duration.ofNanos(1000)); - ChronoUnit.MILLIS = new ChronoUnit('Millis', Duration.ofNanos(1000000)); - ChronoUnit.SECONDS = new ChronoUnit('Seconds', Duration.ofSeconds(1)); - ChronoUnit.MINUTES = new ChronoUnit('Minutes', Duration.ofSeconds(60)); - ChronoUnit.HOURS = new ChronoUnit('Hours', Duration.ofSeconds(3600)); - ChronoUnit.HALF_DAYS = new ChronoUnit('HalfDays', Duration.ofSeconds(43200)); - ChronoUnit.DAYS = new ChronoUnit('Days', Duration.ofSeconds(86400)); - ChronoUnit.WEEKS = new ChronoUnit('Weeks', Duration.ofSeconds(7 * 86400)); - ChronoUnit.MONTHS = new ChronoUnit('Months', Duration.ofSeconds(31556952 / 12)); - ChronoUnit.YEARS = new ChronoUnit('Years', Duration.ofSeconds(31556952)); - ChronoUnit.DECADES = new ChronoUnit('Decades', Duration.ofSeconds(31556952 * 10)); - ChronoUnit.CENTURIES = new ChronoUnit('Centuries', Duration.ofSeconds(31556952 * 100)); - ChronoUnit.MILLENNIA = new ChronoUnit('Millennia', Duration.ofSeconds(31556952 * 1000)); - ChronoUnit.ERAS = new ChronoUnit('Eras', Duration.ofSeconds(31556952 * (YearConstants.MAX_VALUE + 1))); - ChronoUnit.FOREVER = new ChronoUnit('Forever', Duration.ofSeconds(MathUtil.MAX_SAFE_INTEGER, 999999999)); - } - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - - var TemporalField = function () { - function TemporalField() {} - - var _proto = TemporalField.prototype; - - _proto.isDateBased = function isDateBased() { - abstractMethodFail('isDateBased'); - }; - - _proto.isTimeBased = function isTimeBased() { - abstractMethodFail('isTimeBased'); - }; - - _proto.baseUnit = function baseUnit() { - abstractMethodFail('baseUnit'); - }; - - _proto.rangeUnit = function rangeUnit() { - abstractMethodFail('rangeUnit'); - }; - - _proto.range = function range() { - abstractMethodFail('range'); - }; - - _proto.rangeRefinedBy = function rangeRefinedBy(temporal) { - abstractMethodFail('rangeRefinedBy'); - }; - - _proto.getFrom = function getFrom(temporal) { - abstractMethodFail('getFrom'); - }; - - _proto.adjustInto = function adjustInto(temporal, newValue) { - abstractMethodFail('adjustInto'); - }; - - _proto.isSupportedBy = function isSupportedBy(temporal) { - abstractMethodFail('isSupportedBy'); - }; - - _proto.displayName = function displayName() { - abstractMethodFail('displayName'); - }; - - _proto.equals = function equals(other) { - abstractMethodFail('equals'); - }; - - _proto.name = function name() { - abstractMethodFail('name'); - }; - - return TemporalField; - }(); - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ValueRange = function () { - function ValueRange(minSmallest, minLargest, maxSmallest, maxLargest) { - assert(!(minSmallest > minLargest), 'Smallest minimum value \'' + minSmallest + '\' must be less than largest minimum value \'' + minLargest + '\'', IllegalArgumentException); - assert(!(maxSmallest > maxLargest), 'Smallest maximum value \'' + maxSmallest + '\' must be less than largest maximum value \'' + maxLargest + '\'', IllegalArgumentException); - assert(!(minLargest > maxLargest), 'Minimum value \'' + minLargest + '\' must be less than maximum value \'' + maxLargest + '\'', IllegalArgumentException); - this._minSmallest = minSmallest; - this._minLargest = minLargest; - this._maxLargest = maxLargest; - this._maxSmallest = maxSmallest; - } - - var _proto = ValueRange.prototype; - - _proto.isFixed = function isFixed() { - return this._minSmallest === this._minLargest && this._maxSmallest === this._maxLargest; - }; - - _proto.minimum = function minimum() { - return this._minSmallest; - }; - - _proto.largestMinimum = function largestMinimum() { - return this._minLargest; - }; - - _proto.maximum = function maximum() { - return this._maxLargest; - }; - - _proto.smallestMaximum = function smallestMaximum() { - return this._maxSmallest; - }; - - _proto.isValidValue = function isValidValue(value) { - return this.minimum() <= value && value <= this.maximum(); - }; - - _proto.checkValidValue = function checkValidValue(value, field) { - var msg; - - if (!this.isValidValue(value)) { - if (field != null) { - msg = 'Invalid value for ' + field + ' (valid values ' + this.toString() + '): ' + value; - } else { - msg = 'Invalid value (valid values ' + this.toString() + '): ' + value; - } - - return assert(false, msg, DateTimeException); - } - - return value; - }; - - _proto.checkValidIntValue = function checkValidIntValue(value, field) { - if (this.isValidIntValue(value) === false) { - throw new DateTimeException('Invalid int value for ' + field + ': ' + value); - } - - return value; - }; - - _proto.isValidIntValue = function isValidIntValue(value) { - return this.isIntValue() && this.isValidValue(value); - }; - - _proto.isIntValue = function isIntValue() { - return this.minimum() >= MathUtil.MIN_SAFE_INTEGER && this.maximum() <= MathUtil.MAX_SAFE_INTEGER; - }; - - _proto.equals = function equals(other) { - if (other === this) { - return true; - } - - if (other instanceof ValueRange) { - return this._minSmallest === other._minSmallest && this._minLargest === other._minLargest && this._maxSmallest === other._maxSmallest && this._maxLargest === other._maxLargest; - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return MathUtil.hashCode(this._minSmallest, this._minLargest, this._maxSmallest, this._maxLargest); - }; - - _proto.toString = function toString() { - var str = this.minimum() + (this.minimum() !== this.largestMinimum() ? '/' + this.largestMinimum() : ''); - str += ' - '; - str += this.smallestMaximum() + (this.smallestMaximum() !== this.maximum() ? '/' + this.maximum() : ''); - return str; - }; - - ValueRange.of = function of() { - if (arguments.length === 2) { - return new ValueRange(arguments[0], arguments[0], arguments[1], arguments[1]); - } else if (arguments.length === 3) { - return new ValueRange(arguments[0], arguments[0], arguments[1], arguments[2]); - } else if (arguments.length === 4) { - return new ValueRange(arguments[0], arguments[1], arguments[2], arguments[3]); - } else { - return assert(false, 'Invalid number of arguments ' + arguments.length, IllegalArgumentException); - } - }; - - return ValueRange; - }(); - - var ChronoField = function (_TemporalField) { - _inheritsLoose(ChronoField, _TemporalField); - - ChronoField.byName = function byName(fieldName) { - for (var prop in ChronoField) { - if (ChronoField[prop]) { - if (ChronoField[prop] instanceof ChronoField && ChronoField[prop].name() === fieldName) { - return ChronoField[prop]; - } - } - } - }; - - function ChronoField(name, baseUnit, rangeUnit, range) { - var _this; - - _this = _TemporalField.call(this) || this; - _this._name = name; - _this._baseUnit = baseUnit; - _this._rangeUnit = rangeUnit; - _this._range = range; - return _this; - } - - var _proto = ChronoField.prototype; - - _proto.name = function name() { - return this._name; - }; - - _proto.baseUnit = function baseUnit() { - return this._baseUnit; - }; - - _proto.rangeUnit = function rangeUnit() { - return this._rangeUnit; - }; - - _proto.range = function range() { - return this._range; - }; - - _proto.displayName = function displayName() { - return this.toString(); - }; - - _proto.checkValidValue = function checkValidValue(value) { - return this.range().checkValidValue(value, this); - }; - - _proto.checkValidIntValue = function checkValidIntValue(value) { - return this.range().checkValidIntValue(value, this); - }; - - _proto.isDateBased = function isDateBased() { - var dateBased = this === ChronoField.DAY_OF_WEEK || this === ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH || this === ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR || this === ChronoField.DAY_OF_MONTH || this === ChronoField.DAY_OF_YEAR || this === ChronoField.EPOCH_DAY || this === ChronoField.ALIGNED_WEEK_OF_MONTH || this === ChronoField.ALIGNED_WEEK_OF_YEAR || this === ChronoField.MONTH_OF_YEAR || this === ChronoField.YEAR_OF_ERA || this === ChronoField.YEAR || this === ChronoField.ERA; - return dateBased; - }; - - _proto.isTimeBased = function isTimeBased() { - var timeBased = this === ChronoField.NANO_OF_SECOND || this === ChronoField.NANO_OF_DAY || this === ChronoField.MICRO_OF_SECOND || this === ChronoField.MICRO_OF_DAY || this === ChronoField.MILLI_OF_SECOND || this === ChronoField.MILLI_OF_DAY || this === ChronoField.SECOND_OF_MINUTE || this === ChronoField.SECOND_OF_DAY || this === ChronoField.MINUTE_OF_HOUR || this === ChronoField.MINUTE_OF_DAY || this === ChronoField.HOUR_OF_AMPM || this === ChronoField.CLOCK_HOUR_OF_AMPM || this === ChronoField.HOUR_OF_DAY || this === ChronoField.CLOCK_HOUR_OF_DAY || this === ChronoField.AMPM_OF_DAY; - return timeBased; - }; - - _proto.rangeRefinedBy = function rangeRefinedBy(temporal) { - return temporal.range(this); - }; - - _proto.getFrom = function getFrom(temporal) { - return temporal.getLong(this); - }; - - _proto.toString = function toString() { - return this.name(); - }; - - _proto.equals = function equals(other) { - return this === other; - }; - - _proto.adjustInto = function adjustInto(temporal, newValue) { - return temporal.with(this, newValue); - }; - - _proto.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(this); - }; - - return ChronoField; - }(TemporalField); - function _init$3() { - ChronoField.NANO_OF_SECOND = new ChronoField('NanoOfSecond', ChronoUnit.NANOS, ChronoUnit.SECONDS, ValueRange.of(0, 999999999)); - ChronoField.NANO_OF_DAY = new ChronoField('NanoOfDay', ChronoUnit.NANOS, ChronoUnit.DAYS, ValueRange.of(0, 86400 * 1000000000 - 1)); - ChronoField.MICRO_OF_SECOND = new ChronoField('MicroOfSecond', ChronoUnit.MICROS, ChronoUnit.SECONDS, ValueRange.of(0, 999999)); - ChronoField.MICRO_OF_DAY = new ChronoField('MicroOfDay', ChronoUnit.MICROS, ChronoUnit.DAYS, ValueRange.of(0, 86400 * 1000000 - 1)); - ChronoField.MILLI_OF_SECOND = new ChronoField('MilliOfSecond', ChronoUnit.MILLIS, ChronoUnit.SECONDS, ValueRange.of(0, 999)); - ChronoField.MILLI_OF_DAY = new ChronoField('MilliOfDay', ChronoUnit.MILLIS, ChronoUnit.DAYS, ValueRange.of(0, 86400 * 1000 - 1)); - ChronoField.SECOND_OF_MINUTE = new ChronoField('SecondOfMinute', ChronoUnit.SECONDS, ChronoUnit.MINUTES, ValueRange.of(0, 59)); - ChronoField.SECOND_OF_DAY = new ChronoField('SecondOfDay', ChronoUnit.SECONDS, ChronoUnit.DAYS, ValueRange.of(0, 86400 - 1)); - ChronoField.MINUTE_OF_HOUR = new ChronoField('MinuteOfHour', ChronoUnit.MINUTES, ChronoUnit.HOURS, ValueRange.of(0, 59)); - ChronoField.MINUTE_OF_DAY = new ChronoField('MinuteOfDay', ChronoUnit.MINUTES, ChronoUnit.DAYS, ValueRange.of(0, 24 * 60 - 1)); - ChronoField.HOUR_OF_AMPM = new ChronoField('HourOfAmPm', ChronoUnit.HOURS, ChronoUnit.HALF_DAYS, ValueRange.of(0, 11)); - ChronoField.CLOCK_HOUR_OF_AMPM = new ChronoField('ClockHourOfAmPm', ChronoUnit.HOURS, ChronoUnit.HALF_DAYS, ValueRange.of(1, 12)); - ChronoField.HOUR_OF_DAY = new ChronoField('HourOfDay', ChronoUnit.HOURS, ChronoUnit.DAYS, ValueRange.of(0, 23)); - ChronoField.CLOCK_HOUR_OF_DAY = new ChronoField('ClockHourOfDay', ChronoUnit.HOURS, ChronoUnit.DAYS, ValueRange.of(1, 24)); - ChronoField.AMPM_OF_DAY = new ChronoField('AmPmOfDay', ChronoUnit.HALF_DAYS, ChronoUnit.DAYS, ValueRange.of(0, 1)); - ChronoField.DAY_OF_WEEK = new ChronoField('DayOfWeek', ChronoUnit.DAYS, ChronoUnit.WEEKS, ValueRange.of(1, 7)); - ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH = new ChronoField('AlignedDayOfWeekInMonth', ChronoUnit.DAYS, ChronoUnit.WEEKS, ValueRange.of(1, 7)); - ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR = new ChronoField('AlignedDayOfWeekInYear', ChronoUnit.DAYS, ChronoUnit.WEEKS, ValueRange.of(1, 7)); - ChronoField.DAY_OF_MONTH = new ChronoField('DayOfMonth', ChronoUnit.DAYS, ChronoUnit.MONTHS, ValueRange.of(1, 28, 31), 'day'); - ChronoField.DAY_OF_YEAR = new ChronoField('DayOfYear', ChronoUnit.DAYS, ChronoUnit.YEARS, ValueRange.of(1, 365, 366)); - ChronoField.EPOCH_DAY = new ChronoField('EpochDay', ChronoUnit.DAYS, ChronoUnit.FOREVER, ValueRange.of(Math.floor(YearConstants.MIN_VALUE * 365.25), Math.floor(YearConstants.MAX_VALUE * 365.25))); - ChronoField.ALIGNED_WEEK_OF_MONTH = new ChronoField('AlignedWeekOfMonth', ChronoUnit.WEEKS, ChronoUnit.MONTHS, ValueRange.of(1, 4, 5)); - ChronoField.ALIGNED_WEEK_OF_YEAR = new ChronoField('AlignedWeekOfYear', ChronoUnit.WEEKS, ChronoUnit.YEARS, ValueRange.of(1, 53)); - ChronoField.MONTH_OF_YEAR = new ChronoField('MonthOfYear', ChronoUnit.MONTHS, ChronoUnit.YEARS, ValueRange.of(1, 12), 'month'); - ChronoField.PROLEPTIC_MONTH = new ChronoField('ProlepticMonth', ChronoUnit.MONTHS, ChronoUnit.FOREVER, ValueRange.of(YearConstants.MIN_VALUE * 12, YearConstants.MAX_VALUE * 12 + 11)); - ChronoField.YEAR_OF_ERA = new ChronoField('YearOfEra', ChronoUnit.YEARS, ChronoUnit.FOREVER, ValueRange.of(1, YearConstants.MAX_VALUE, YearConstants.MAX_VALUE + 1)); - ChronoField.YEAR = new ChronoField('Year', ChronoUnit.YEARS, ChronoUnit.FOREVER, ValueRange.of(YearConstants.MIN_VALUE, YearConstants.MAX_VALUE), 'year'); - ChronoField.ERA = new ChronoField('Era', ChronoUnit.ERAS, ChronoUnit.FOREVER, ValueRange.of(0, 1)); - ChronoField.INSTANT_SECONDS = new ChronoField('InstantSeconds', ChronoUnit.SECONDS, ChronoUnit.FOREVER, ValueRange.of(MIN_SAFE_INTEGER, MAX_SAFE_INTEGER)); - ChronoField.OFFSET_SECONDS = new ChronoField('OffsetSeconds', ChronoUnit.SECONDS, ChronoUnit.FOREVER, ValueRange.of(-18 * 3600, 18 * 3600)); - } - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalQueries = function () { - function TemporalQueries() {} - - TemporalQueries.zoneId = function zoneId() { - return TemporalQueries.ZONE_ID; - }; - - TemporalQueries.chronology = function chronology() { - return TemporalQueries.CHRONO; - }; - - TemporalQueries.precision = function precision() { - return TemporalQueries.PRECISION; - }; - - TemporalQueries.zone = function zone() { - return TemporalQueries.ZONE; - }; - - TemporalQueries.offset = function offset() { - return TemporalQueries.OFFSET; - }; - - TemporalQueries.localDate = function localDate() { - return TemporalQueries.LOCAL_DATE; - }; - - TemporalQueries.localTime = function localTime() { - return TemporalQueries.LOCAL_TIME; - }; - - return TemporalQueries; - }(); - - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalAccessor = function () { - function TemporalAccessor() {} - - var _proto = TemporalAccessor.prototype; - - _proto.query = function query(_query) { - if (_query === TemporalQueries.zoneId() || _query === TemporalQueries.chronology() || _query === TemporalQueries.precision()) { - return null; - } - - return _query.queryFrom(this); - }; - - _proto.get = function get(field) { - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; - - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (this.isSupported(field)) { - return field.range(); - } - - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.rangeRefinedBy(this); - }; - - return TemporalAccessor; - }(); - - var TemporalQuery = function (_Enum) { - _inheritsLoose(TemporalQuery, _Enum); - - function TemporalQuery() { - return _Enum.apply(this, arguments) || this; - } - - var _proto = TemporalQuery.prototype; - - _proto.queryFrom = function queryFrom(temporal) { - abstractMethodFail('queryFrom'); - }; - - return TemporalQuery; - }(Enum); - function createTemporalQuery(name, queryFromFunction) { - var ExtendedTemporalQuery = function (_TemporalQuery) { - _inheritsLoose(ExtendedTemporalQuery, _TemporalQuery); - - function ExtendedTemporalQuery() { - return _TemporalQuery.apply(this, arguments) || this; - } - - return ExtendedTemporalQuery; - }(TemporalQuery); - - ExtendedTemporalQuery.prototype.queryFrom = queryFromFunction; - return new ExtendedTemporalQuery(name); - } - - var DayOfWeek = function (_TemporalAccessor) { - _inheritsLoose(DayOfWeek, _TemporalAccessor); - - function DayOfWeek(ordinal, name) { - var _this; - - _this = _TemporalAccessor.call(this) || this; - _this._ordinal = ordinal; - _this._name = name; - return _this; - } - - var _proto = DayOfWeek.prototype; - - _proto.ordinal = function ordinal() { - return this._ordinal; - }; - - _proto.name = function name() { - return this._name; - }; - - DayOfWeek.values = function values() { - return ENUMS.slice(); - }; - - DayOfWeek.valueOf = function valueOf(name) { - var ordinal = 0; - - for (ordinal; ordinal < ENUMS.length; ordinal++) { - if (ENUMS[ordinal].name() === name) { - break; - } - } - - return DayOfWeek.of(ordinal + 1); - }; - - DayOfWeek.of = function of(dayOfWeek) { - if (dayOfWeek < 1 || dayOfWeek > 7) { - throw new DateTimeException('Invalid value for DayOfWeek: ' + dayOfWeek); - } - - return ENUMS[dayOfWeek - 1]; - }; - - DayOfWeek.from = function from(temporal) { - assert(temporal != null, 'temporal', NullPointerException); - - if (temporal instanceof DayOfWeek) { - return temporal; - } - - try { - return DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); - } catch (ex) { - if (ex instanceof DateTimeException) { - throw new DateTimeException('Unable to obtain DayOfWeek from TemporalAccessor: ' + temporal + ', type ' + (temporal.constructor != null ? temporal.constructor.name : ''), ex); - } else { - throw ex; - } - } - }; - - _proto.value = function value() { - return this._ordinal + 1; - }; - - _proto.displayName = function displayName(style, locale) { - throw new IllegalArgumentException('Pattern using (localized) text not implemented yet!'); - }; - - _proto.isSupported = function isSupported(field) { - if (field instanceof ChronoField) { - return field === ChronoField.DAY_OF_WEEK; - } - - return field != null && field.isSupportedBy(this); - }; - - _proto.range = function range(field) { - if (field === ChronoField.DAY_OF_WEEK) { - return field.range(); - } else if (field instanceof ChronoField) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.rangeRefinedBy(this); - }; - - _proto.get = function get(field) { - if (field === ChronoField.DAY_OF_WEEK) { - return this.value(); - } - - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; - - _proto.getLong = function getLong(field) { - if (field === ChronoField.DAY_OF_WEEK) { - return this.value(); - } else if (field instanceof ChronoField) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.getFrom(this); - }; - - _proto.plus = function plus(days) { - var amount = MathUtil.floorMod(days, 7); - return ENUMS[MathUtil.floorMod(this._ordinal + (amount + 7), 7)]; - }; - - _proto.minus = function minus(days) { - return this.plus(-1 * MathUtil.floorMod(days, 7)); - }; - - _proto.query = function query(_query) { - if (_query === TemporalQueries.precision()) { - return ChronoUnit.DAYS; - } else if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.chronology() || _query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } - - assert(_query != null, 'query', NullPointerException); - return _query.queryFrom(this); - }; - - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - return temporal.with(ChronoField.DAY_OF_WEEK, this.value()); - }; - - _proto.equals = function equals(other) { - return this === other; - }; - - _proto.toString = function toString() { - return this._name; - }; - - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, DayOfWeek, 'other'); - return this._ordinal - other._ordinal; - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return DayOfWeek; - }(TemporalAccessor); - var ENUMS; - function _init$4() { - DayOfWeek.MONDAY = new DayOfWeek(0, 'MONDAY'); - DayOfWeek.TUESDAY = new DayOfWeek(1, 'TUESDAY'); - DayOfWeek.WEDNESDAY = new DayOfWeek(2, 'WEDNESDAY'); - DayOfWeek.THURSDAY = new DayOfWeek(3, 'THURSDAY'); - DayOfWeek.FRIDAY = new DayOfWeek(4, 'FRIDAY'); - DayOfWeek.SATURDAY = new DayOfWeek(5, 'SATURDAY'); - DayOfWeek.SUNDAY = new DayOfWeek(6, 'SUNDAY'); - DayOfWeek.FROM = createTemporalQuery('DayOfWeek.FROM', function (temporal) { - return DayOfWeek.from(temporal); - }); - ENUMS = [DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY]; - } - - var Month = function (_TemporalAccessor) { - _inheritsLoose(Month, _TemporalAccessor); - - function Month(value, name) { - var _this; - - _this = _TemporalAccessor.call(this) || this; - _this._value = MathUtil.safeToInt(value); - _this._name = name; - return _this; - } - - var _proto = Month.prototype; - - _proto.value = function value() { - return this._value; - }; - - _proto.ordinal = function ordinal() { - return this._value - 1; - }; - - _proto.name = function name() { - return this._name; - }; - - _proto.displayName = function displayName(style, locale) { - throw new IllegalArgumentException('Pattern using (localized) text not implemented yet!'); - }; - - _proto.isSupported = function isSupported(field) { - if (null === field) { - return false; - } - - if (field instanceof ChronoField) { - return field === ChronoField.MONTH_OF_YEAR; - } - - return field != null && field.isSupportedBy(this); - }; - - _proto.get = function get(field) { - if (field === ChronoField.MONTH_OF_YEAR) { - return this.value(); - } - - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; - - _proto.getLong = function getLong(field) { - if (field === ChronoField.MONTH_OF_YEAR) { - return this.value(); - } else if (field instanceof ChronoField) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - - return field.getFrom(this); - }; - - _proto.plus = function plus(months) { - var amount = MathUtil.intMod(months, 12) + 12; - var newMonthVal = MathUtil.intMod(this.value() + amount, 12); - newMonthVal = newMonthVal === 0 ? 12 : newMonthVal; - return Month.of(newMonthVal); - }; - - _proto.minus = function minus(months) { - return this.plus(-1 * MathUtil.intMod(months, 12)); - }; - - _proto.length = function length(leapYear) { - switch (this) { - case Month.FEBRUARY: - return leapYear ? 29 : 28; - - case Month.APRIL: - case Month.JUNE: - case Month.SEPTEMBER: - case Month.NOVEMBER: - return 30; - - default: - return 31; - } - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + + +var request = __nccwpck_require__(48699); + +var argument = __nccwpck_require__(62432); +var log = __nccwpck_require__(92288); +var util = __nccwpck_require__(5336); +var HttpErrorCode = __nccwpck_require__(10282).HttpError; + +/* + * Constants + */ +var consts = { + AUTHORIZATION_URI : 'authorization_uri', + RESOURCE : 'resource', + WWW_AUTHENTICATE_HEADER : 'www-authenticate' +}; + +/** + * The AuthenticationParameters class holds the parameters that are parsed from an OAuth challenge + * in the www-authenticate header. + * @constructor + * @param {string} authorizationUri The URI of an authority that can issues tokens for the + * resource that issued the challenge. + * @param {string} resource The resource for a which a token should be requested from the authority. + */ +function AuthenticationParameters(authorizationUri, resource) { + this._authorizationUri = authorizationUri; + this._resource = resource; +} + +/** + * The URI of an authority that can issues tokens for the resource that issued the challenge. + * @instance + * @memberOf AuthenticationParameters + * @type {string} + * @name authorizationUri + */ +Object.defineProperty(AuthenticationParameters.prototype, 'authorizationUri', { + get : function() { + return this._authorizationUri; + } +}); + +/** + * The resource for a which a token should be requested from the authority. + * This property may be undefined if the resource was not returned in the challenge. + * @instance + * @memberOf AuthenticationParameters + * @type {string} + * @name authorizationUri + */ +Object.defineProperty(AuthenticationParameters.prototype, 'resource', { + get : function() { + return this._resource; + } +}); + +var exports = {}; + +// The 401 challenge is a standard defined in RFC6750, which is based in part on RFC2617. +// The challenge has the following form. +// WWW-Authenticate : Bearer authorization_uri="https://login.windows.net/mytenant.com/oauth2/authorize",Resource_id="00000002-0000-0000-c000-000000000000" + +// This regex is used to validate the structure of the challenge header. +// Match whole structure: ^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$ +// ^ Start at the beginning of the string. +// \s*Bearer\s+ Match 'Bearer' surrounded by one or more amount of whitespace. +// ([^,\s="]+?) This cpatures the key which is composed of any characters except comma, whitespace or a quotes. +// = Match the = sign. +// "([^"]*?)" Captures the value can be any number of non quote characters. At this point only the first key value pair as been captured. +// \s* There can be any amount of white space after the first key value pair. +// ( Start a capture group to retrieve the rest of the key value pairs that are separated by commas. +// \s* There can be any amount of whitespace before the comma. +// , There must be a comma. +// \s* There can be any amount of whitespace after the comma. +// (([^,\s="]+?) This will capture the key that comes after the comma. It's made of a series of any character excpet comma, whitespace or quotes. +// = Match the equal sign between the key and value. +// " Match the opening quote of the value. +// ([^"]*?) This will capture the value which can be any number of non quote characters. +// " Match the values closing quote. +// \s* There can be any amount of whitespace before the next comma. +// )* Close the capture group for key value pairs. There can be any number of these. +// $ The rest of the string can be whitespace but nothing else up to the end of the string. +// +// +// In other some other languages the regex above would be all that was needed. However, in JavaScript the RegExp object does not +// return all of the captures in one go. So the regex above needs to be broken up so that captures can be retrieved +// iteratively. +// + +function parseChallenge(challenge) { + // This regex checks the structure of the whole challenge header. The complete + // header needs to be checked for validity before we can be certain that + // we will succeed in pulling out the individual parts. + var bearerChallengeStructureValidation = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$/; + + // This regex pulls out the key and value from the very first pair. + var firstKeyValuePairRegex = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*/; + + // This regex is used to pull out all of the key value pairs after the first one. + // All of these begin with a comma. + var allOtherKeyValuePairRegex = /(?:,\s*([^,\s="]+?)="([^"]*?)"\s*)/g; + + + if (!bearerChallengeStructureValidation.test(challenge)) { + throw new Error('The challenge is not parseable as an RFC6750 OAuth2 challenge'); + } + + var challengeParameters = {}; + for(var match = firstKeyValuePairRegex.exec(challenge); + match; + match = allOtherKeyValuePairRegex.exec(challenge)) { + + challengeParameters[match[1]] = match[2]; + } + + return challengeParameters; +} + +exports.AuthenticationParameters = AuthenticationParameters; + +/** + * Creates an {@link AuthenticationParameters} object from the contents of a + * www-authenticate header received from a HTTP 401 response from a resource server. + * @param {string} challenge The content fo the www-authenticate header. + * @return {AuthenticationParameters} An AuthenticationParameters object containing the parsed values from the header. + */ +exports.createAuthenticationParametersFromHeader = function(challenge) { + argument.validateStringParameter(challenge, 'challenge'); + + var challengeParameters = parseChallenge(challenge); + + var authorizationUri = challengeParameters[consts.AUTHORIZATION_URI]; + if (!authorizationUri) { + throw new Error('Could not find \'authorization_uri\' in challenge header.'); + } + + var resource = challengeParameters[consts.RESOURCE]; + + return new AuthenticationParameters(authorizationUri, resource); +}; + +/** + * Create an {@link AuthenticationParameters} object from a node http.IncomingMessage + * object that was created as a result of a request to a resource server. This function + * expects the response to contain a HTTP 401 error code with a www-authenticate + * header. + * @param {http.IncomingMessage} response A response from a http request to a resource server. + * @return {AuthenticationParameters} + */ +exports.createAuthenticationParametersFromResponse = function(response) { + if (!response) { + throw new Error('Mising required parameter: response'); + } + + if (!response.statusCode) { + throw new Error('The response parameter does not have the expected HTTP statusCode field'); + } + + if (HttpErrorCode.UNAUTHORIZED !== response.statusCode) { + throw new Error('The response status code does not correspond to an OAuth challenge. ' + + 'The statusCode is expected to be 401 but is: ' + response.statusCode); + } + + if (!response.headers) { + throw new Error('There were no headers found in the response.'); + } + + var challenge = response.headers[consts.WWW_AUTHENTICATE_HEADER]; + if (!challenge) { + throw new Error('The response does not contain a WWW-Authenticate header that can be used to determine the authority_uri and resource.'); + } + + return exports.createAuthenticationParametersFromHeader(challenge); +}; + +function validateUrlObject(url) { + if (!url || !url.href) { + throw new Error('Parameter is of wrong type: url'); + } +} + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback CreateAuthenticationParametersCallback + * @memberOf AuthenticationContext + * @param {Error} [error] If the request fails this parameter will contain an Error object. + * @param {AuthenticationParameters} [parameters] On a succesful request returns a {@link AuthenticationParameters}. + */ + +/** + * Creates an {@link AuthenticationParameters} object by sending a get request + * to the url passed to this function, and parsing the resulting http 401 + * response. + * @param {string|url} url The url of a resource server. + * @param {AuthenticationParameters} callback Called on error or request completion. + * @param {string} [correlationId] An optional correlationId to pass along with the request and to include in any logs. + */ +exports.createAuthenticationParametersFromUrl = function(url, callback, correlationId) { + argument.validateCallbackType(callback); + try { + if (!url) { + callback(new Error('Missing required parameter: url')); + return; + } + var challengeUrl; + if ('string' === typeof(url)) { + challengeUrl = url; + } else { + validateUrlObject(url); + challengeUrl = url.href; + } + + var logContext = log.createLogContext(correlationId); + var logger = new log.Logger('AuthenticationParameters', logContext); + + logger.verbose('Attempting to retrieve authentication parameters'); + logger.verbose('Attempting to retrieve authentication parameters from: ' + challengeUrl, true); + var options = util.createRequestOptions( { _callContext : { _logContext: logContext } } ); + request.get(challengeUrl, options, function(err, response) { + if (err) { + logger.error('Authentication parameters http get failed.', err, true); + callback(err); + return; + } + var parameters; + try { + parameters = exports.createAuthenticationParametersFromResponse(response); + } catch(creationErr) { + logger.error('Unable to parse response in to authentication paramaters.', creationErr, true); + callback(creationErr); + return; + } + callback(null, parameters); + }); + } catch(err) { + callback(err); + return; + } +}; + +module.exports = exports; - _proto.minLength = function minLength() { - switch (this) { - case Month.FEBRUARY: - return 28; +/***/ }), - case Month.APRIL: - case Month.JUNE: - case Month.SEPTEMBER: - case Month.NOVEMBER: - return 30; +/***/ 19270: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - default: - return 31; - } - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var request = __nccwpck_require__(48699); +var url = __nccwpck_require__(78835); +var _ = __nccwpck_require__(83571); + +var AADConstants = __nccwpck_require__(10282).AADConstants; +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +/** +* Constructs an Authority object with a specific authority URL. +* @private +* @constructor +* @param {string} authorityUrl A URL that identifies a token authority. +* @param {bool} validateAuthority Indicates whether the Authority url should be validated as an actual AAD +* authority. The default is true. +*/ +function Authority(authorityUrl, validateAuthority) { + this._log = null; + this._url = url.parse(authorityUrl); + this._validateAuthorityUrl(); + + this._validated = !validateAuthority; + this._host = null; + this._tenant = null; + this._parseAuthority(); + + this._authorizationEndpoint = null; + this._tokenEndpoint = null; + this._deviceCodeEndpoint = null; + this._isAdfsAuthority = (this._tenant.toLowerCase() === "adfs"); +} + +/** + * The URL of the authority + * @instance + * @type {string} + * @memberOf Authority + * @name url + */ +Object.defineProperty(Authority.prototype, 'url', { + get: function() { + return url.format(this._url); + } +}); + +/** + * The token endpoint that the authority uses as discovered by instance discovery. + * @instance + * @type {string} + * @memberOf Authority + * @name tokenEndpoint + */ +Object.defineProperty(Authority.prototype, 'tokenEndpoint', { + get: function() { + return this._tokenEndpoint; + } +}); + +Object.defineProperty(Authority.prototype, 'deviceCodeEndpoint', { + get: function() { + return this._deviceCodeEndpoint; + } +}); + +/** + * Checks the authority url to ensure that it meets basic requirements such as being over SSL. If it does not then + * this method will throw if any of the checks fail. + * @private + * @throws {Error} If the authority url fails to pass any validation checks. + */ +Authority.prototype._validateAuthorityUrl = function() { + if (this._url.protocol !== 'https:') { + throw new Error('The authority url must be an https endpoint.'); + } + + if (this._url.query) { + throw new Error('The authority url must not have a query string.'); + } +}; + +/** + * Parse the authority to get the tenant name. The rest of the + * URL is thrown away in favor of one of the endpoints from the validation doc. + * @private + */ +Authority.prototype._parseAuthority = function() { + this._host = this._url.host; + + var pathParts = this._url.pathname.split('/'); + this._tenant = pathParts[1]; + + if (!this._tenant) { + throw new Error('Could not determine tenant.'); + } +}; + +/** + * Performs instance discovery based on a simple match against well known authorities. + * @private + * @return {bool} Returns true if the authority is recognized. + */ +Authority.prototype._performStaticInstanceDiscovery = function() { + this._log.verbose('Performing static instance discovery'); + + var hostIndex = _.indexOf(AADConstants.WELL_KNOWN_AUTHORITY_HOSTS, this._url.hostname); + var found = hostIndex > -1; + + if (found) { + this._log.verbose('Authority validated via static instance discovery.'); + } + + return found; +}; + +Authority.prototype._createAuthorityUrl = function() { + return 'https://' + this._url.host + '/' + encodeURIComponent(this._tenant) + AADConstants.AUTHORIZE_ENDPOINT_PATH; +}; + +/** + * Creates an instance discovery endpoint url for the specific authority that this object represents. + * @private + * @param {string} authorityHost The host name of a well known authority. + * @return {URL} The constructed endpoint url. + */ +Authority.prototype._createInstanceDiscoveryEndpointFromTemplate = function(authorityHost) { + var discoveryEndpoint = AADConstants.INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE; + discoveryEndpoint = discoveryEndpoint.replace('{authorize_host}', authorityHost); + discoveryEndpoint = discoveryEndpoint.replace('{authorize_endpoint}', encodeURIComponent(this._createAuthorityUrl())); + return url.parse(discoveryEndpoint); +}; + +/** + * Performs instance discovery via a network call to well known authorities. + * @private + * @param {Authority.InstanceDiscoveryCallback} callback The callback function. If succesful, + * this function calls the callback with the + * tenantDiscoveryEndpoint returned by the + * server. + */ +Authority.prototype._performDynamicInstanceDiscovery = function(callback) { + try { + var self = this; + var discoveryEndpoint = this._createInstanceDiscoveryEndpointFromTemplate(AADConstants.WORLD_WIDE_AUTHORITY); + + var getOptions = util.createRequestOptions(self); + + this._log.verbose('Attempting instance discover'); + this._log.verbose('Attempting instance discover at: ' + url.format(discoveryEndpoint), true); + request.get(discoveryEndpoint, getOptions, util.createRequestHandler('Instance Discovery', this._log, callback, + function(response, body) { + var discoveryResponse = JSON.parse(body); + + if (discoveryResponse['tenant_discovery_endpoint']) { + callback(null, discoveryResponse['tenant_discovery_endpoint']); + } else { + callback(self._log.createError('Failed to parse instance discovery response')); + } + }) + ); + } catch(e) { + callback(e); + } +}; + +/** + * @callback InstanceDiscoveryCallback + * @private + * @memberOf Authority + * @param {Error} err If an error occurs during instance discovery then it will be returned here. + * @param {string} tenantDiscoveryEndpoint If instance discovery is successful then this will contain the + * tenantDiscoveryEndpoint associated with the authority. + */ + +/** + * Determines whether the authority is recognized as a trusted AAD authority. + * @private + * @param {Authority.InstanceDiscoveryCallback} callback The callback function. + */ +Authority.prototype._validateViaInstanceDiscovery = function(callback) { + if (this._performStaticInstanceDiscovery()) { + callback(); + } else { + this._performDynamicInstanceDiscovery(callback); + } +}; + +/** + * @callback GetOauthEndpointsCallback + * @private + * @memberOf Authority + * @param {Error} error An error if one occurred. + */ + +/** + * Given a tenant discovery endpoint this method will attempt to discover the token endpoint. If the + * tenant discovery endpoint is unreachable for some reason then it will fall back to a algorithmic generation of the + * token endpoint url. + * @private + * @param {string} tenantDiscoveryEndpoint The url of the tenant discovery endpoint for this authority. + * @param {Authority.GetOauthEndpointsCallback} callback The callback function. + */ +Authority.prototype._getOAuthEndpoints = function(tenantDiscoveryEndpoint, callback) { + if (this._tokenEndpoint && this._deviceCodeEndpoint) { + callback(); + return; + } else { + // fallback to the well known token endpoint path. + if (!this._tokenEndpoint){ + this._tokenEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.TOKEN_ENDPOINT_PATH; + } + + if (!this._deviceCodeEndpoint){ + this._deviceCodeEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.DEVICE_ENDPOINT_PATH; + } + + callback(); + return; + } +}; + +/** + * @callback ValidateCallback + * @memberOf Authority + */ + +/** + * Perform validation on the authority represented by this object. In addition to simple validation + * the oauth token endpoint will be retrieved. + * @param {Authority.ValidateCallback} callback The callback function. + */ +Authority.prototype.validate = function(callContext, callback) { + this._log = new Logger('Authority', callContext._logContext); + this._callContext = callContext; + var self = this; + + if (!this._validated) { + this._log.verbose('Performing instance discovery'); + this._log.verbose('Performing instance discovery: ' + url.format(this._url), true); + this._validateViaInstanceDiscovery(function(err, tenantDiscoveryEndpoint) { + if (err) + { + callback(err); + } else { + self._validated = true; + self._getOAuthEndpoints(tenantDiscoveryEndpoint, callback); + return; + } + }); + } else { + this._log.verbose('Instance discovery/validation has either already been completed or is turned off'); + this._log.verbose('Instance discovery/validation has either already been completed or is turned off: ' + url.format(this._url), true); + this._getOAuthEndpoints(null, callback); + return; + } +}; + +module.exports.W = Authority; - _proto.maxLength = function maxLength() { - switch (this) { - case Month.FEBRUARY: - return 29; - case Month.APRIL: - case Month.JUNE: - case Month.SEPTEMBER: - case Month.NOVEMBER: - return 30; +/***/ }), - default: - return 31; - } - }; +/***/ 38289: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.firstDayOfYear = function firstDayOfYear(leapYear) { - var leap = leapYear ? 1 : 0; - - switch (this) { - case Month.JANUARY: - return 1; - - case Month.FEBRUARY: - return 32; - - case Month.MARCH: - return 60 + leap; - - case Month.APRIL: - return 91 + leap; - - case Month.MAY: - return 121 + leap; - - case Month.JUNE: - return 152 + leap; - - case Month.JULY: - return 182 + leap; - - case Month.AUGUST: - return 213 + leap; - - case Month.SEPTEMBER: - return 244 + leap; - - case Month.OCTOBER: - return 274 + leap; - - case Month.NOVEMBER: - return 305 + leap; - - case Month.DECEMBER: - default: - return 335 + leap; - } - }; - - _proto.firstMonthOfQuarter = function firstMonthOfQuarter() { - switch (this) { - case Month.JANUARY: - case Month.FEBRUARY: - case Month.MARCH: - return Month.JANUARY; - - case Month.APRIL: - case Month.MAY: - case Month.JUNE: - return Month.APRIL; - - case Month.JULY: - case Month.AUGUST: - case Month.SEPTEMBER: - return Month.JULY; - - case Month.OCTOBER: - case Month.NOVEMBER: - case Month.DECEMBER: - default: - return Month.OCTOBER; - } - }; - - _proto.query = function query(_query) { - assert(_query != null, 'query() parameter must not be null', DateTimeException); - - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.MONTHS; - } - - return _TemporalAccessor.prototype.query.call(this, _query); - }; - - _proto.toString = function toString() { - switch (this) { - case Month.JANUARY: - return 'JANUARY'; - - case Month.FEBRUARY: - return 'FEBRUARY'; - - case Month.MARCH: - return 'MARCH'; - - case Month.APRIL: - return 'APRIL'; - - case Month.MAY: - return 'MAY'; - - case Month.JUNE: - return 'JUNE'; - - case Month.JULY: - return 'JULY'; - - case Month.AUGUST: - return 'AUGUST'; - - case Month.SEPTEMBER: - return 'SEPTEMBER'; - - case Month.OCTOBER: - return 'OCTOBER'; - - case Month.NOVEMBER: - return 'NOVEMBER'; - - case Month.DECEMBER: - return 'DECEMBER'; - - default: - return 'unknown Month, value: ' + this.value(); - } - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.MONTH_OF_YEAR, this.value()); - }; - - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, Month, 'other'); - return this._value - other._value; - }; - - _proto.equals = function equals(other) { - return this === other; - }; - - Month.valueOf = function valueOf(name) { - var ordinal = 0; - - for (ordinal; ordinal < MONTHS.length; ordinal++) { - if (MONTHS[ordinal].name() === name) { - break; - } - } - - return Month.of(ordinal + 1); - }; - - Month.values = function values() { - return MONTHS.slice(); - }; - - Month.of = function of(month) { - if (month < 1 || month > 12) { - assert(false, 'Invalid value for MonthOfYear: ' + month, DateTimeException); - } - - return MONTHS[month - 1]; - }; - - Month.from = function from(temporal) { - if (temporal instanceof Month) { - return temporal; - } - - try { - return Month.of(temporal.get(ChronoField.MONTH_OF_YEAR)); - } catch (ex) { - throw new DateTimeException('Unable to obtain Month from TemporalAccessor: ' + temporal + ' of type ' + (temporal && temporal.constructor != null ? temporal.constructor.name : ''), ex); - } - }; - - return Month; - }(TemporalAccessor); - var MONTHS; - function _init$5() { - Month.JANUARY = new Month(1, 'JANUARY'); - Month.FEBRUARY = new Month(2, 'FEBRUARY'); - Month.MARCH = new Month(3, 'MARCH'); - Month.APRIL = new Month(4, 'APRIL'); - Month.MAY = new Month(5, 'MAY'); - Month.JUNE = new Month(6, 'JUNE'); - Month.JULY = new Month(7, 'JULY'); - Month.AUGUST = new Month(8, 'AUGUST'); - Month.SEPTEMBER = new Month(9, 'SEPTEMBER'); - Month.OCTOBER = new Month(10, 'OCTOBER'); - Month.NOVEMBER = new Month(11, 'NOVEMBER'); - Month.DECEMBER = new Month(12, 'DECEMBER'); - MONTHS = [Month.JANUARY, Month.FEBRUARY, Month.MARCH, Month.APRIL, Month.MAY, Month.JUNE, Month.JULY, Month.AUGUST, Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER, Month.DECEMBER]; - } - - var PATTERN = /([-+]?)P(?:([-+]?[0-9]+)Y)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)W)?(?:([-+]?[0-9]+)D)?/; - var Period = function (_TemporalAmount) { - _inheritsLoose(Period, _TemporalAmount); - - function Period(years, months, days) { - var _this; - - _this = _TemporalAmount.call(this) || this; - - var _years = MathUtil.safeToInt(years); - - var _months = MathUtil.safeToInt(months); - - var _days = MathUtil.safeToInt(days); - - if (_years === 0 && _months === 0 && _days === 0) { - if (!Period.ZERO) { - _this._years = _years; - _this._months = _months; - _this._days = _days; - Period.ZERO = _assertThisInitialized(_this); - } - - return Period.ZERO || _assertThisInitialized(_this); - } - - _this._years = _years; - _this._months = _months; - _this._days = _days; - return _this; - } - - Period.ofYears = function ofYears(years) { - return Period.create(years, 0, 0); - }; - - Period.ofMonths = function ofMonths(months) { - return Period.create(0, months, 0); - }; - - Period.ofWeeks = function ofWeeks(weeks) { - return Period.create(0, 0, MathUtil.safeMultiply(weeks, 7)); - }; - - Period.ofDays = function ofDays(days) { - return Period.create(0, 0, days); - }; - - Period.of = function of(years, months, days) { - return Period.create(years, months, days); - }; - - Period.from = function from(amount) { - if (amount instanceof Period) { - return amount; - } - - requireNonNull(amount, 'amount'); - var years = 0; - var months = 0; - var days = 0; - var units = amount.units(); - - for (var i = 0; i < units.length; i++) { - var unit = units[i]; - var unitAmount = amount.get(unit); - - if (unit === ChronoUnit.YEARS) { - years = MathUtil.safeToInt(unitAmount); - } else if (unit === ChronoUnit.MONTHS) { - months = MathUtil.safeToInt(unitAmount); - } else if (unit === ChronoUnit.DAYS) { - days = MathUtil.safeToInt(unitAmount); - } else { - throw new DateTimeException('Unit must be Years, Months or Days, but was ' + unit); - } - } - - return Period.create(years, months, days); - }; - - Period.between = function between(startDate, endDate) { - requireNonNull(startDate, 'startDate'); - requireNonNull(endDate, 'endDate'); - requireInstance(startDate, LocalDate, 'startDate'); - requireInstance(endDate, LocalDate, 'endDate'); - return startDate.until(endDate); - }; - - Period.parse = function parse(text) { - requireNonNull(text, 'text'); - - try { - return Period._parse(text); - } catch (ex) { - if (ex instanceof ArithmeticException) { - throw new DateTimeParseException('Text cannot be parsed to a Period', text, 0, ex); - } else { - throw ex; - } - } - }; - - Period._parse = function _parse(text) { - var matches = PATTERN.exec(text); - - if (matches != null) { - var negate = '-' === matches[1] ? -1 : 1; - var yearMatch = matches[2]; - var monthMatch = matches[3]; - var weekMatch = matches[4]; - var dayMatch = matches[5]; - - if (yearMatch != null || monthMatch != null || weekMatch != null || dayMatch != null) { - var years = Period._parseNumber(text, yearMatch, negate); - - var months = Period._parseNumber(text, monthMatch, negate); - - var weeks = Period._parseNumber(text, weekMatch, negate); - - var days = Period._parseNumber(text, dayMatch, negate); - - days = MathUtil.safeAdd(days, MathUtil.safeMultiply(weeks, 7)); - return Period.create(years, months, days); - } - } - - throw new DateTimeParseException('Text cannot be parsed to a Period', text, 0); - }; - - Period._parseNumber = function _parseNumber(text, str, negate) { - if (str == null) { - return 0; - } - - var val = MathUtil.parseInt(str); - return MathUtil.safeMultiply(val, negate); - }; - - Period.create = function create(years, months, days) { - return new Period(years, months, days); - }; - - var _proto = Period.prototype; - - _proto.units = function units() { - return [ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS]; - }; - - _proto.chronology = function chronology() { - return IsoChronology.INSTANCE; - }; - - _proto.get = function get(unit) { - if (unit === ChronoUnit.YEARS) { - return this._years; - } - - if (unit === ChronoUnit.MONTHS) { - return this._months; - } - - if (unit === ChronoUnit.DAYS) { - return this._days; - } - - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - }; - - _proto.isZero = function isZero() { - return this === Period.ZERO; - }; - - _proto.isNegative = function isNegative() { - return this._years < 0 || this._months < 0 || this._days < 0; - }; - - _proto.years = function years() { - return this._years; - }; - - _proto.months = function months() { - return this._months; - }; - - _proto.days = function days() { - return this._days; - }; - - _proto.withYears = function withYears(years) { - if (years === this._years) { - return this; - } - - return Period.create(years, this._months, this._days); - }; - - _proto.withMonths = function withMonths(months) { - if (months === this._months) { - return this; - } - - return Period.create(this._years, months, this._days); - }; - - _proto.withDays = function withDays(days) { - if (days === this._days) { - return this; - } - - return Period.create(this._years, this._months, days); - }; - - _proto.plus = function plus(amountToAdd) { - var amount = Period.from(amountToAdd); - return Period.create(MathUtil.safeAdd(this._years, amount._years), MathUtil.safeAdd(this._months, amount._months), MathUtil.safeAdd(this._days, amount._days)); - }; - - _proto.plusYears = function plusYears(yearsToAdd) { - if (yearsToAdd === 0) { - return this; - } - - return Period.create(MathUtil.safeToInt(MathUtil.safeAdd(this._years, yearsToAdd)), this._months, this._days); - }; - - _proto.plusMonths = function plusMonths(monthsToAdd) { - if (monthsToAdd === 0) { - return this; - } - - return Period.create(this._years, MathUtil.safeToInt(MathUtil.safeAdd(this._months, monthsToAdd)), this._days); - }; - - _proto.plusDays = function plusDays(daysToAdd) { - if (daysToAdd === 0) { - return this; - } - - return Period.create(this._years, this._months, MathUtil.safeToInt(MathUtil.safeAdd(this._days, daysToAdd))); - }; - - _proto.minus = function minus(amountToSubtract) { - var amount = Period.from(amountToSubtract); - return Period.create(MathUtil.safeSubtract(this._years, amount._years), MathUtil.safeSubtract(this._months, amount._months), MathUtil.safeSubtract(this._days, amount._days)); - }; - - _proto.minusYears = function minusYears(yearsToSubtract) { - return this.plusYears(-1 * yearsToSubtract); - }; - - _proto.minusMonths = function minusMonths(monthsToSubtract) { - return this.plusMonths(-1 * monthsToSubtract); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + + +var _ = __nccwpck_require__(83571); +var crypto = __nccwpck_require__(76417); +__nccwpck_require__(1693); // Adds a number of convenience methods to the builtin Date object. + +var Logger = __nccwpck_require__(92288).Logger; +var constants = __nccwpck_require__(10282); +var cacheConstants = constants.Cache; +var TokenResponseFields = constants.TokenResponseFields; + +// TODO: remove this. +// There is a PM requirement that developers be able to look in to the cache and manipulate the cache based on +// the parameters (authority, resource, clientId, userId), in any combination. They must be able find, add, and remove +// tokens based on those parameters. Any default cache that the API supplies must allow for this query pattern. +// This has the following implications: +// The developer must not be required to calculate any special fields, such as hashes or unique keys. +// +// The default cache implementation can not include optimizations that break the previous requirement. +// This means that we can only do complete scans of the data and equality can only be calculated based on +// equality of all of the individual fields. +// +// The cache interface can not make any assumption about the query efficency of the cache nor can +// it help in optimizing those queries. +// +// There is no simple sorting optimization, rather a series of indexes, and index intersection would +// be necessary. +// +// If for some reason the developer tries to update the cache with a new entry that may be a refresh +// token, they will not know that they need to update all of the refresh tokens or they may get strange +// behavior. +// +// Related to the above, there is no definition of a coherent cache. And if there was there would be +// no way for our API to enforce it. What about duplicates? +// +// there be a single cache entry per (authority, resource, clientId) +// tuple, with no special tokens (i.e. MRRT tokens) +// Required cache operations +// + +// Constants +var METADATA_CLIENTID = '_clientId'; +var METADATA_AUTHORITY = '_authority'; + +function nop(placeHolder, callback) { + callback(); +} + +/* + * This is a place holder cache that does nothing. + */ +var nopCache = { + add : nop, + addMany : nop, + remove : nop, + removeMany : nop, + find : nop +}; + +function createTokenHash(token) { + var hashAlg = crypto.createHash(cacheConstants.HASH_ALGORITHM); + hashAlg.update(token, 'utf8'); + return hashAlg.digest('base64'); +} + +function createTokenIdMessage(entry) { + var accessTokenHash = createTokenHash(entry[TokenResponseFields.ACCESS_TOKEN]); + var message = 'AccessTokenId: ' + accessTokenHash; + if (entry[TokenResponseFields.REFRESH_TOKEN]) { + var refreshTokenHash = createTokenHash(entry[TokenResponseFields.REFRESH_TOKEN]); + message += ', RefreshTokenId: ' + refreshTokenHash; + } + return message; +} + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback RefreshEntryFunction + * @memberOf CacheDriver + * @param {object} tokenResponse A token response to refresh. + * @param {string} [resource] The resource for which to obtain the token if it is different from the original token. + * @param {AcquireTokenCallback} callback Called on completion with an error or a new entry to add to the cache. + */ + +/** + * Constructs a new CacheDriver object. + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} authority + * @param {TokenCache} [cache] A token cache to use. If none is passed then the CacheDriver instance + * will not cache. + * @param {RefreshEntryFunction} refreshFunction + */ +function CacheDriver(callContext, authority, resource, clientId, cache, refreshFunction) { + this._callContext = callContext; + this._log = new Logger('CacheDriver', callContext._logContext); + this._authority = authority; + this._resource = resource; + this._clientId = clientId; + this._cache = cache || nopCache; + this._refreshFunction = refreshFunction; +} + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback QueryCallback + * @memberOf CacheDriver + * @param {Error} [error] If the request fails this parameter will contain an Error object. + * @param {Array} [response] On a succesful request returns an array of matched entries. + */ + +/** + * The cache driver query function. Ensures that all queries are authority specific. + * @param {object} query A query object. Can contain a clientId or userId or both. + * @param {QueryCallback} callback + */ +CacheDriver.prototype._find = function(query, callback) { + this._cache.find(query, callback); +}; + +/** + * Queries for all entries that might satisfy a request for a cached token. + * @param {object} query A query object. Can contain a clientId or userId or both. + * @param {QueryCallback} callback + */ +CacheDriver.prototype._getPotentialEntries = function(query, callback) { + var self = this; + var potentialEntriesQuery = {}; + + if (query.clientId) { + potentialEntriesQuery[METADATA_CLIENTID] = query.clientId; + } + if (query.userId) { + potentialEntriesQuery[TokenResponseFields.USER_ID] = query.userId; + } + + this._log.verbose('Looking for potential cache entries:'); + this._log.verbose(JSON.stringify(potentialEntriesQuery), true); + this._find(potentialEntriesQuery, function(err, entries) { + self._log.verbose('Found ' + entries.length + ' potential entries.'); + callback(err, entries); + return; + }); +}; + +/** + * Finds all multi resource refresh tokens in the cache. + * Refresh token is bound to userId, clientId. + * @param {QueryCallback} callback + */ +CacheDriver.prototype._findMRRTTokensForUser = function(user, callback) { + this._find({ isMRRT : true, userId : user, _clientId : this._clientId}, callback); +}; + +/** + * This is the callback that is passed to all acquireToken variants below. + * @callback SingleEntryCallback + * @memberOf CacheDriver + * @param {Error} [error] If the request fails this parameter will contain an Error object. + * @param {object} [response] On a succesful request returns a single cache entry. + */ + + +/** + * Finds a single entry that matches the query. If multiple entries are found that satisfy the query + * then an error will be returned. + * @param {object} query A query object. + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype._loadSingleEntryFromCache = function(query, callback) { + var self = this; + this._getPotentialEntries(query, function(err, potentialEntries) { + if (err) { + callback(err); + return; + } + + var returnVal; + var isResourceTenantSpecific; + + if (potentialEntries && 0 < potentialEntries.length) { + var resourceTenantSpecificEntries = _.where(potentialEntries, { resource : self._resource, _authority : self._authority }); + + if (!resourceTenantSpecificEntries || 0 === resourceTenantSpecificEntries.length) { + self._log.verbose('No resource specific cache entries found.'); + + // There are no resource specific entries. Find an MRRT token. + var mrrtTokens = _.where(potentialEntries, { isMRRT : true }); + if (mrrtTokens && mrrtTokens.length > 0) { + self._log.verbose('Found an MRRT token.'); + returnVal = mrrtTokens[0]; + } else { + self._log.verbose('No MRRT tokens found.'); + } + + } else if (resourceTenantSpecificEntries.length === 1) { + self._log.verbose('Resource specific token found.'); + returnVal = resourceTenantSpecificEntries[0]; + isResourceTenantSpecific = true; + }else { + callback(self._log.createError('More than one token matches the criteria. The result is ambiguous.')); + return; + } + } + if (returnVal) { + self._log.verbose('Returning token from cache lookup'); + self._log.verbose('Returning token from cache lookup, ' + createTokenIdMessage(returnVal), true); + } + callback(null, returnVal, isResourceTenantSpecific); + }); +}; + +/** + * The response from a token refresh request never contains an id_token and therefore no + * userInfo can be created from the response. This function creates a new cache entry + * combining the id_token based info and cache metadata from the cache entry that was refreshed with the + * new tokens in the refresh response. + * @param {object} entry A cache entry corresponding to the resfreshResponse. + * @param {object} refreshResponse The response from a token refresh request for the entry parameter. + * @return {object} A new cache entry. + */ +CacheDriver.prototype._createEntryFromRefresh = function(entry, refreshResponse) { + var newEntry = _.clone(entry); + newEntry = _.extend(newEntry, refreshResponse); + + if (entry.isMRRT && this._authority !== entry[METADATA_AUTHORITY]) { + newEntry[METADATA_AUTHORITY] = this._authority; + } + + this._log.verbose('Created new cache entry from refresh response.'); + return newEntry; +}; + +CacheDriver.prototype._replaceEntry = function(entryToReplace, newEntry, callback) { + var self = this; + this.remove(entryToReplace, function(err) { + if (err) { + callback(err); + return; + } + self.add(newEntry, callback); + }); +}; + +/** + * Given an expired cache entry refreshes it and updates the cache. + * @param {object} entry A cache entry with an MRRT to refresh for another resource. + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype._refreshExpiredEntry = function(entry, callback) { + var self = this; + this._refreshFunction(entry, null, function(err, tokenResponse) { + if (err) { + callback(err); + return; + } + + var newEntry = self._createEntryFromRefresh(entry, tokenResponse); + self._replaceEntry(entry, newEntry, function(err) { + if (err) { + self._log.error('error refreshing expired token', err, true); + } else { + self._log.info('Returning token refreshed after expiry.'); + } + callback(err, newEntry); + }); + }); +}; + +/** + * Given a cache entry with an MRRT will acquire a new token for a new resource via the MRRT, and cache it. + * @param {object} entry A cache entry with an MRRT to refresh for another resource. + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype._acquireNewTokenFromMrrt = function(entry, callback) { + var self = this; + this._refreshFunction(entry, this._resource, function(err, tokenResponse) { + if (err) { + callback(err); + return; + } + + var newEntry = self._createEntryFromRefresh(entry, tokenResponse); + self.add(newEntry, function(err) { + if (err) { + self._log.error('error refreshing mrrt', err, true); + } else { + self._log.info('Returning token derived from mrrt refresh.'); + } + callback(err, newEntry); + }); + }); +}; + +/** + * Given a token this function will refresh it if it is either expired, or an MRRT. + * @param {object} entry A cache entry to refresh if necessary. + * @param {Boolean} isResourceSpecific Indicates whether this token is appropriate for the resource for which + * it was requested or whether it is possibly an MRRT token for which + * a resource specific access token should be acquired. + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype._refreshEntryIfNecessary = function(entry, isResourceSpecific, callback) { + var expiryDate = entry[TokenResponseFields.EXPIRES_ON]; + + // Add some buffer in to the time comparison to account for clock skew or latency. + var nowPlusBuffer = (new Date()).addMinutes(constants.Misc.CLOCK_BUFFER); + + if (isResourceSpecific && nowPlusBuffer.isAfter(expiryDate)) { + this._log.info('Cached token is expired. Refreshing: ' + expiryDate); + this._refreshExpiredEntry(entry, callback); + return; + } else if (!isResourceSpecific && entry.isMRRT) { + this._log.info('Acquiring new access token from MRRT token.'); + this._acquireNewTokenFromMrrt(entry, callback); + return; + } else { + callback(null, entry); + } +}; + +/** + * Finds a single entry in the cache that matches the query or fails if more than one match is found. + * @param {object} query A query object + * @param {SingleEntryCallback} callback + */ +CacheDriver.prototype.find = function(query, callback) { + var self = this; + query = query || {}; + this._log.verbose('finding using query'); + this._log.verbose('finding with query:' + JSON.stringify(query), true); + this._loadSingleEntryFromCache(query, function(err, entry, isResourceTenantSpecific) { + if (err) { + callback(err); + return; + } + + if (!entry) { + callback(); + return; + } + + self._refreshEntryIfNecessary(entry, isResourceTenantSpecific, function(err, newEntry) { + callback(err, newEntry); + return; + }); + }); +}; + +/** + * Removes a single entry from the cache. + * @param {object} entry The entry to remove. + * @param {Function} callback Called on completion. The first parameter may contain an error. + */ +CacheDriver.prototype.remove = function(entry, callback) { + this._log.verbose('Removing entry.'); + return this._cache.remove([entry], function(err) { + callback(err); + return; + }); +}; + +/** + * Removes a collection of entries from the cache in a single batch operation. + * @param {Array} entries An array of cache entries to remove. + * @param {Function} callback This function is called when the operation is complete. Any error is provided as the + * first parameter. + */ +CacheDriver.prototype._removeMany = function(entries, callback) { + this._log.verbose('Remove many: ' + entries.length); + this._cache.remove(entries, function(err) { + callback(err); + return; + }); +}; + +/** + * Adds a collection of entries to the cache in a single batch operation. + * @param {Array} entries An array of entries to add to the cache. + * @param {Function} callback This function is called when the operation is complete. Any error is provided as the + * first parameter. + */ +CacheDriver.prototype._addMany = function(entries, callback) { + this._log.verbose('Add many: ' + entries.length); + this._cache.add(entries, function(err) { + callback(err); + return; + }); +}; + +/* + * Tests whether the passed entry is a multi resource refresh token. + * Somewhat mysteriously the presense of a resource field in a returned + * token response indicates that the response is an MRRT. + * @param {object} entry + * @return {Boolean} true if the entry is an MRRT. + */ +function isMRRT(entry) { + return entry.resource ? true : false; +} + +/** + * Given an cache entry this function finds all of the MRRT tokens already in the cache + * and updates them with the refresh_token of the passed in entry. + * @param {object} entry The entry from which to get an updated refresh_token + * @param {Function} callback Called back on completion. The first parameter may contain an error. + */ +CacheDriver.prototype._updateRefreshTokens = function(entry, callback) { + var self = this; + if (isMRRT(entry)) { + this._findMRRTTokensForUser(entry.userId, function(err, mrrtTokens) { + if (err) { + callback(err); + return; + } + + if (!mrrtTokens || 0 === mrrtTokens.length) { + callback(); + return; + } + + self._log.verbose('Updating ' + mrrtTokens.length + ' cached refresh tokens.'); + self._removeMany(mrrtTokens, function(err) { + if (err) { + callback(err); + return; + } + + for (var i = 0; i < mrrtTokens.length; i++) { + mrrtTokens[i][TokenResponseFields.REFRESH_TOKEN] = entry[TokenResponseFields.REFRESH_TOKEN]; + } + + self._addMany(mrrtTokens, function(err) { + callback(err); + return; + }); + }); + }); + } else { + callback(); + return; + } +}; + +/** + * Checks to see if the entry has cache metadata already. If it does + * then it probably came from a refresh operation and the metadata + * was copied from the originating entry. + * @param {object} entry The entry to check + * @return {bool} Returns true if the entry has already been augmented + * with cache metadata. + */ +CacheDriver.prototype._entryHasMetadata = function(entry) { + return (_.has(entry, METADATA_CLIENTID) && _.has(entry, METADATA_AUTHORITY)); +}; + +CacheDriver.prototype._augmentEntryWithCacheMetadata = function(entry) { + if (this._entryHasMetadata(entry)) { + return; + } + + if (isMRRT(entry)) { + this._log.verbose('Added entry is MRRT'); + entry.isMRRT = true; + } else { + entry.resource = this._resource; + } + + entry[METADATA_CLIENTID] = this._clientId; + entry[METADATA_AUTHORITY] = this._authority; +}; + +/** + * Adds a single entry to the cache. + * @param {object} entry The entry to add. + * @param {string} clientId The id of this client app. + * @param {string} resource The id of the resource for which the cached token was obtained. + * @param {Function} callback Called back on completion. The first parameter may contain an error. + */ +CacheDriver.prototype.add = function(entry, callback) { + var self = this; + this._log.verbose('Adding entry'); + this._log.verbose('Adding entry, ' + createTokenIdMessage(entry)); + + this._augmentEntryWithCacheMetadata(entry); + + this._updateRefreshTokens(entry, function(err) { + if (err) { + callback(err); + return; + } + + self._cache.add([entry], function(err) { + callback(err); + return; + }); + }); +}; + +module.exports = CacheDriver; - _proto.minusDays = function minusDays(daysToSubtract) { - return this.plusDays(-1 * daysToSubtract); - }; +/***/ }), - _proto.multipliedBy = function multipliedBy(scalar) { - if (this === Period.ZERO || scalar === 1) { - return this; - } +/***/ 66576: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return Period.create(MathUtil.safeMultiply(this._years, scalar), MathUtil.safeMultiply(this._months, scalar), MathUtil.safeMultiply(this._days, scalar)); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var constants = __nccwpck_require__(10282); +var Logger = __nccwpck_require__(92288).Logger; +var Mex = __nccwpck_require__(27078); +var OAuth2Client = __nccwpck_require__(41602); + +var OAuth2Parameters = constants.OAuth2.Parameters; +var TokenResponseFields = constants.TokenResponseFields; +var OAuth2GrantType = constants.OAuth2.GrantType; +var OAuth2Scope = constants.OAuth2.Scope; + +/** + * Constructs a new CodeRequest object. + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {AuthenticationContext} authenticationContext + * @param {string} resource + * @param {string} clientId + */ +// TODO: probably need to modify the parameter list. +function CodeRequest(callContext, authenticationContext, clientId, resource) { + this._log = new Logger('DeviceCodeRequest', callContext._logContext); + this._callContext = callContext; + this._authenticationContext = authenticationContext; + this._resource = resource; + this._clientId = clientId; + + // This should be set at the beginning of getToken + // functions that have a userId. + this._userId = null; +}; + +/** + * Get user code info. + * @private + * @param {object} oauthParameters containing all the parameters needed to get the user code info. + * @param {callback} callback + */ +CodeRequest.prototype._getUserCodeInfo = function (oauthParameters, callback) { + var oauth2Client = this._createOAuth2Client(); + oauth2Client.getUserCodeInfo(oauthParameters, callback); +}; + +CodeRequest.prototype._createOAuth2Client = function () { + return new OAuth2Client(this._callContext, this._authenticationContext._authority); +}; + +/** + * Creates a set of basic, common, OAuthParameters based on values that the CodeRequest was created with. + * @private + * @return {object} containing all the basic parameters. + */ +CodeRequest.prototype._createOAuthParameters = function () { + var oauthParameters = {}; + + oauthParameters[OAuth2Parameters.CLIENT_ID] = this._clientId; + oauthParameters[OAuth2Parameters.RESOURCE] = this._resource; + + return oauthParameters; +}; + +/** + * Get the user code information. + * @param {string} language optional parameter used to get the user code info. + * @param {callback} callback + */ +CodeRequest.prototype.getUserCodeInfo = function(language, callback) { + this._log.info('Getting user code info.'); + + var oauthParameters = this._createOAuthParameters(); + if (language){ + oauthParameters[OAuth2Parameters.LANGUAGE] = language; + } + + this._getUserCodeInfo(oauthParameters, callback); +}; +module.exports = CodeRequest; - _proto.negated = function negated() { - return this.multipliedBy(-1); - }; +/***/ }), - _proto.normalized = function normalized() { - var totalMonths = this.toTotalMonths(); - var splitYears = MathUtil.intDiv(totalMonths, 12); - var splitMonths = MathUtil.intMod(totalMonths, 12); +/***/ 10282: +/***/ ((module) => { - if (splitYears === this._years && splitMonths === this._months) { - return this; - } +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var Constants = { + OAuth2 : { + Parameters : { + GRANT_TYPE : 'grant_type', + CLIENT_ASSERTION : 'client_assertion', + CLIENT_ASSERTION_TYPE : 'client_assertion_type', + CLIENT_ID : 'client_id', + CLIENT_SECRET : 'client_secret', + REDIRECT_URI : 'redirect_uri', + RESOURCE : 'resource', + CODE : 'code', + SCOPE : 'scope', + ASSERTION : 'assertion', + AAD_API_VERSION : 'api-version', + USERNAME : 'username', + PASSWORD : 'password', + REFRESH_TOKEN : 'refresh_token', + LANGUAGE : 'mkt', + DEVICE_CODE : 'device_code', + }, + + GrantType : { + AUTHORIZATION_CODE : 'authorization_code', + REFRESH_TOKEN : 'refresh_token', + CLIENT_CREDENTIALS : 'client_credentials', + JWT_BEARER : 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', + PASSWORD : 'password', + SAML1 : 'urn:ietf:params:oauth:grant-type:saml1_1-bearer', + SAML2 : 'urn:ietf:params:oauth:grant-type:saml2-bearer', + DEVICE_CODE: 'device_code' + }, + + ResponseParameters : { + CODE : 'code', + TOKEN_TYPE : 'token_type', + ACCESS_TOKEN : 'access_token', + ID_TOKEN : 'id_token', + REFRESH_TOKEN : 'refresh_token', + CREATED_ON : 'created_on', + EXPIRES_ON : 'expires_on', + EXPIRES_IN : 'expires_in', + RESOURCE : 'resource', + ERROR : 'error', + ERROR_DESCRIPTION : 'error_description' + }, + + DeviceCodeResponseParameters : { + USER_CODE : 'user_code', + DEVICE_CODE : 'device_code', + VERIFICATION_URL : 'verification_url', + EXPIRES_IN : 'expires_in', + INTERVAL: 'interval', + MESSAGE: 'message', + ERROR: 'error', + ERROR_DESCRIPTION: 'error_description' + }, + + Scope : { + OPENID : 'openid' + }, + + IdTokenMap : { + 'tid' : 'tenantId', + 'given_name' : 'givenName', + 'family_name' : 'familyName', + 'idp' : 'identityProvider', + 'oid': 'oid' + } + }, + + TokenResponseFields : { + TOKEN_TYPE : 'tokenType', + ACCESS_TOKEN : 'accessToken', + REFRESH_TOKEN : 'refreshToken', + CREATED_ON : 'createdOn', + EXPIRES_ON : 'expiresOn', + EXPIRES_IN : 'expiresIn', + RESOURCE : 'resource', + USER_ID : 'userId', + ERROR : 'error', + ERROR_DESCRIPTION : 'errorDescription' + }, + + UserCodeResponseFields : { + USER_CODE : 'userCode', + DEVICE_CODE: 'deviceCode', + VERIFICATION_URL: 'verificationUrl', + EXPIRES_IN: 'expiresIn', + INTERVAL: 'interval', + MESSAGE: 'message', + ERROR: 'error', + ERROR_DESCRIPTION: 'errorDescription' + }, + + IdTokenFields : { + USER_ID : 'userId', + IS_USER_ID_DISPLAYABLE : 'isUserIdDisplayable', + TENANT_ID : 'tenantId', + GIVE_NAME : 'givenName', + FAMILY_NAME : 'familyName', + IDENTITY_PROVIDER : 'identityProvider' + }, + + Misc : { + MAX_DATE : 0xffffffff, + CLOCK_BUFFER : 5 // In minutes. + }, + + Jwt : { + SELF_SIGNED_JWT_LIFETIME : 10, // 10 mins in mins + AUDIENCE : 'aud', + ISSUER : 'iss', + SUBJECT : 'sub', + NOT_BEFORE : 'nbf', + EXPIRES_ON : 'exp', + JWT_ID : 'jti' + }, + + AADConstants : { + WORLD_WIDE_AUTHORITY : 'login.windows.net', + WELL_KNOWN_AUTHORITY_HOSTS : ['login.windows.net', 'login.microsoftonline.com', 'login.chinacloudapi.cn', 'login-us.microsoftonline.com', 'login.microsoftonline.de', 'login.microsoftonline.us'], + INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE : 'https://{authorize_host}/common/discovery/instance?authorization_endpoint={authorize_endpoint}&api-version=1.0', + AUTHORIZE_ENDPOINT_PATH : '/oauth2/authorize', + TOKEN_ENDPOINT_PATH : '/oauth2/token', + DEVICE_ENDPOINT_PATH : '/oauth2/devicecode' + }, + + UserRealm : { + FederationProtocolType : { + WSFederation : 'wstrust', + SAML2 : 'saml20', + Unknown : 'unknown' + }, + + AccountType : { + Federated : 'federated', + Managed : 'managed', + Unknown : 'unknown' + } + }, + + Saml : { + TokenTypeV1 : 'urn:oasis:names:tc:SAML:1.0:assertion', + TokenTypeV2 : 'urn:oasis:names:tc:SAML:2.0:assertion' + }, + + XmlNamespaces : { + wsdl : 'http://schemas.xmlsoap.org/wsdl/', + sp : 'http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702', + sp2005 : 'http://schemas.xmlsoap.org/ws/2005/07/securitypolicy', + wsu : 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd', + wsa10 : 'http://www.w3.org/2005/08/addressing', + http : 'http://schemas.microsoft.com/ws/06/2004/policy/http', + soap12 : 'http://schemas.xmlsoap.org/wsdl/soap12/', + wsp : 'http://schemas.xmlsoap.org/ws/2004/09/policy', + s : 'http://www.w3.org/2003/05/soap-envelope', + wsa : 'http://www.w3.org/2005/08/addressing', + wst : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512', + t : 'http://schemas.xmlsoap.org/ws/2005/02/trust' + }, + + Cache : { + HASH_ALGORITHM : 'sha256' + }, + + HttpError : { + UNAUTHORIZED : 401 + }, + + AdalIdParameters : { + SKU : 'x-client-SKU', + VERSION : 'x-client-Ver', + OS : 'x-client-OS', + CPU : 'x-client-CPU', + NODE_SKU : 'Node' + }, + + WSTrustVersion : { + UNDEFINED : 'undefined', + WSTRUST13 : 'wstrust13', + WSTRUST2005 : 'wstrust2005' + } + }; + +module.exports = Constants; - return Period.create(MathUtil.safeToInt(splitYears), splitMonths, this._days); - }; - _proto.toTotalMonths = function toTotalMonths() { - return this._years * 12 + this._months; - }; +/***/ }), - _proto.addTo = function addTo(temporal) { - requireNonNull(temporal, 'temporal'); +/***/ 92288: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this._years !== 0) { - if (this._months !== 0) { - temporal = temporal.plus(this.toTotalMonths(), ChronoUnit.MONTHS); - } else { - temporal = temporal.plus(this._years, ChronoUnit.YEARS); - } - } else if (this._months !== 0) { - temporal = temporal.plus(this._months, ChronoUnit.MONTHS); - } - - if (this._days !== 0) { - temporal = temporal.plus(this._days, ChronoUnit.DAYS); - } - - return temporal; - }; - - _proto.subtractFrom = function subtractFrom(temporal) { - requireNonNull(temporal, 'temporal'); - - if (this._years !== 0) { - if (this._months !== 0) { - temporal = temporal.minus(this.toTotalMonths(), ChronoUnit.MONTHS); - } else { - temporal = temporal.minus(this._years, ChronoUnit.YEARS); - } - } else if (this._months !== 0) { - temporal = temporal.minus(this._months, ChronoUnit.MONTHS); - } - - if (this._days !== 0) { - temporal = temporal.minus(this._days, ChronoUnit.DAYS); - } - - return temporal; - }; - - _proto.equals = function equals(obj) { - if (this === obj) { - return true; - } - - if (obj instanceof Period) { - var other = obj; - return this._years === other._years && this._months === other._months && this._days === other._days; - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return MathUtil.hashCode(this._years, this._months, this._days); - }; - - _proto.toString = function toString() { - if (this === Period.ZERO) { - return 'P0D'; - } else { - var buf = 'P'; - - if (this._years !== 0) { - buf += '' + this._years + 'Y'; - } - - if (this._months !== 0) { - buf += '' + this._months + 'M'; - } - - if (this._days !== 0) { - buf += '' + this._days + 'D'; - } - - return buf; - } - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return Period; - }(TemporalAmount); - function _init$6() { - Period.ofDays(0); - } - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ParsePosition = function () { - function ParsePosition(index) { - this._index = index; - this._errorIndex = -1; - } - - var _proto = ParsePosition.prototype; - - _proto.getIndex = function getIndex() { - return this._index; - }; - - _proto.setIndex = function setIndex(index) { - this._index = index; - }; - - _proto.getErrorIndex = function getErrorIndex() { - return this._errorIndex; - }; - - _proto.setErrorIndex = function setErrorIndex(errorIndex) { - this._errorIndex = errorIndex; - }; - - return ParsePosition; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var EnumMap = function () { - function EnumMap() { - this._map = {}; - } - - var _proto = EnumMap.prototype; - - _proto.putAll = function putAll(otherMap) { - for (var key in otherMap._map) { - this._map[key] = otherMap._map[key]; - } - - return this; - }; - - _proto.containsKey = function containsKey(key) { - return this._map.hasOwnProperty(key.name()) && this.get(key) !== undefined; - }; - - _proto.get = function get(key) { - return this._map[key.name()]; - }; - - _proto.put = function put(key, val) { - return this.set(key, val); - }; - - _proto.set = function set(key, val) { - this._map[key.name()] = val; - return this; - }; - - _proto.retainAll = function retainAll(keyList) { - var map = {}; - - for (var i = 0; i < keyList.length; i++) { - var key = keyList[i].name(); - map[key] = this._map[key]; - } - - this._map = map; - return this; - }; - - _proto.remove = function remove(key) { - var keyName = key.name(); - var val = this._map[keyName]; - this._map[keyName] = undefined; - return val; - }; - - _proto.keySet = function keySet() { - return this._map; - }; - - _proto.clear = function clear() { - this._map = {}; - }; - - return EnumMap; - }(); - - var ResolverStyle = function (_Enum) { - _inheritsLoose(ResolverStyle, _Enum); - - function ResolverStyle() { - return _Enum.apply(this, arguments) || this; - } - - return ResolverStyle; - }(Enum); - ResolverStyle.STRICT = new ResolverStyle('STRICT'); - ResolverStyle.SMART = new ResolverStyle('SMART'); - ResolverStyle.LENIENT = new ResolverStyle('LENIENT'); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var TemporalAdjuster = function () { - function TemporalAdjuster() {} - - var _proto = TemporalAdjuster.prototype; - - _proto.adjustInto = function adjustInto(temporal) { - abstractMethodFail('adjustInto'); - }; - - return TemporalAdjuster; - }(); - - var Temporal = function (_TemporalAccessor) { - _inheritsLoose(Temporal, _TemporalAccessor); - - function Temporal() { - return _TemporalAccessor.apply(this, arguments) || this; - } - - var _proto = Temporal.prototype; - - _proto.isSupported = function isSupported(unit) { - abstractMethodFail('isSupported'); - }; - - _proto.minus = function minus(p1, p2) { - if (arguments.length < 2) { - return this.minusAmount(p1); - } else { - return this.minusAmountUnit(p1, p2); - } - }; - - _proto.minusAmount = function minusAmount(amount) { - abstractMethodFail('minusAmount'); - }; - - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - abstractMethodFail('minusAmountUnit'); - }; - - _proto.plus = function plus(p1, p2) { - if (arguments.length < 2) { - return this.plusAmount(p1); - } else { - return this.plusAmountUnit(p1, p2); - } - }; - - _proto.plusAmount = function plusAmount(amount) { - abstractMethodFail('plusAmount'); - }; - - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - abstractMethodFail('plusAmountUnit'); - }; - - _proto.until = function until(endTemporal, unit) { - abstractMethodFail('until'); - }; - - _proto.with = function _with(p1, p2) { - if (arguments.length < 2) { - return this.withAdjuster(p1); - } else { - return this.withFieldValue(p1, p2); - } - }; - - _proto.withAdjuster = function withAdjuster(adjuster) { - abstractMethodFail('withAdjuster'); - }; - - _proto.withFieldValue = function withFieldValue(field, newValue) { - abstractMethodFail('withFieldValue'); - }; - - return Temporal; - }(TemporalAccessor); - - var DefaultInterfaceTemporal = function (_Temporal) { - _inheritsLoose(DefaultInterfaceTemporal, _Temporal); - - function DefaultInterfaceTemporal() { - return _Temporal.apply(this, arguments) || this; - } - - var _proto = DefaultInterfaceTemporal.prototype; - - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); - requireInstance(adjuster, TemporalAdjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; - - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.addTo(this); - }; - - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.subtractFrom(this); - }; - - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(amountToSubtract, 'amountToSubtract'); - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit, 'unit'); - return amountToSubtract === MIN_SAFE_INTEGER ? this.plusAmountUnit(MAX_SAFE_INTEGER, unit).plusAmountUnit(1, unit) : this.plusAmount(-amountToSubtract, unit); - }; - - return DefaultInterfaceTemporal; - }(Temporal); - - var ChronoLocalDate = function (_DefaultInterfaceTemp) { - _inheritsLoose(ChronoLocalDate, _DefaultInterfaceTemp); - - function ChronoLocalDate() { - return _DefaultInterfaceTemp.apply(this, arguments) || this; - } - - var _proto = ChronoLocalDate.prototype; - - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isDateBased(); - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isDateBased(); - } - - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; - - _proto.query = function query(_query) { - if (_query === TemporalQueries.chronology()) { - return this.chronology(); - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.DAYS; - } else if (_query === TemporalQueries.localDate()) { - return LocalDate.ofEpochDay(this.toEpochDay()); - } else if (_query === TemporalQueries.localTime() || _query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } - - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; - - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.EPOCH_DAY, this.toEpochDay()); - }; - - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.format(this); - }; - - return ChronoLocalDate; - }(DefaultInterfaceTemporal); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var StringUtil = function () { - function StringUtil() {} - - StringUtil.startsWith = function startsWith(text, pattern) { - return text.indexOf(pattern) === 0; - }; - - StringUtil.hashCode = function hashCode(text) { - var len = text.length; - - if (len === 0) { - return 0; - } - - var hash = 0; - - for (var i = 0; i < len; i++) { - var chr = text.charCodeAt(i); - hash = (hash << 5) - hash + chr; - hash |= 0; - } - - return MathUtil.smi(hash); - }; - - return StringUtil; - }(); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ZoneId = function () { - function ZoneId() {} - - ZoneId.systemDefault = function systemDefault() { - throw new DateTimeException('not supported operation'); - }; - - ZoneId.getAvailableZoneIds = function getAvailableZoneIds() { - throw new DateTimeException('not supported operation'); - }; - - ZoneId.of = function of(zoneId) { - throw new DateTimeException('not supported operation' + zoneId); - }; - - ZoneId.ofOffset = function ofOffset(prefix, offset) { - throw new DateTimeException('not supported operation' + prefix + offset); - }; - - ZoneId.from = function from(temporal) { - throw new DateTimeException('not supported operation' + temporal); - }; - - var _proto = ZoneId.prototype; - - _proto.id = function id() { - abstractMethodFail('ZoneId.id'); - }; - - _proto.rules = function rules() { - abstractMethodFail('ZoneId.rules'); - }; - - _proto.normalized = function normalized() { - var rules = this.rules(); - - if (rules.isFixedOffset()) { - return rules.offset(Instant.EPOCH); - } - - return this; - }; - - _proto.equals = function equals(other) { - if (this === other) { - return true; - } - - if (other instanceof ZoneId) { - return this.id() === other.id(); - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return StringUtil.hashCode(this.id()); - }; - - _proto.toString = function toString() { - return this.id(); - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return ZoneId; - }(); - - var ZoneRules = function () { - function ZoneRules() {} - - ZoneRules.of = function of(offset) { - requireNonNull(offset, 'offset'); - return new Fixed(offset); - }; - - var _proto = ZoneRules.prototype; - - _proto.isFixedOffset = function isFixedOffset() { - abstractMethodFail('ZoneRules.isFixedOffset'); - }; - - _proto.offset = function offset(instantOrLocalDateTime) { - if (instantOrLocalDateTime instanceof Instant) { - return this.offsetOfInstant(instantOrLocalDateTime); - } else { - return this.offsetOfLocalDateTime(instantOrLocalDateTime); - } - }; - - _proto.offsetOfInstant = function offsetOfInstant(instant) { - abstractMethodFail('ZoneRules.offsetInstant'); - }; - - _proto.offsetOfEpochMilli = function offsetOfEpochMilli(epochMilli) { - abstractMethodFail('ZoneRules.offsetOfEpochMilli'); - }; - - _proto.offsetOfLocalDateTime = function offsetOfLocalDateTime(localDateTime) { - abstractMethodFail('ZoneRules.offsetLocalDateTime'); - }; - - _proto.validOffsets = function validOffsets(localDateTime) { - abstractMethodFail('ZoneRules.validOffsets'); - }; - - _proto.transition = function transition(localDateTime) { - abstractMethodFail('ZoneRules.transition'); - }; - - _proto.standardOffset = function standardOffset(instant) { - abstractMethodFail('ZoneRules.standardOffset'); - }; - - _proto.daylightSavings = function daylightSavings(instant) { - abstractMethodFail('ZoneRules.daylightSavings'); - }; - - _proto.isDaylightSavings = function isDaylightSavings(instant) { - abstractMethodFail('ZoneRules.isDaylightSavings'); - }; - - _proto.isValidOffset = function isValidOffset(localDateTime, offset) { - abstractMethodFail('ZoneRules.isValidOffset'); - }; - - _proto.nextTransition = function nextTransition(instant) { - abstractMethodFail('ZoneRules.nextTransition'); - }; - - _proto.previousTransition = function previousTransition(instant) { - abstractMethodFail('ZoneRules.previousTransition'); - }; - - _proto.transitions = function transitions() { - abstractMethodFail('ZoneRules.transitions'); - }; - - _proto.transitionRules = function transitionRules() { - abstractMethodFail('ZoneRules.transitionRules'); - }; - - _proto.toString = function toString() { - abstractMethodFail('ZoneRules.toString'); - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - return ZoneRules; - }(); - - var Fixed = function (_ZoneRules) { - _inheritsLoose(Fixed, _ZoneRules); - - function Fixed(offset) { - var _this; - - _this = _ZoneRules.call(this) || this; - _this._offset = offset; - return _this; - } - - var _proto2 = Fixed.prototype; - - _proto2.isFixedOffset = function isFixedOffset() { - return true; - }; - - _proto2.offsetOfInstant = function offsetOfInstant() { - return this._offset; - }; - - _proto2.offsetOfEpochMilli = function offsetOfEpochMilli() { - return this._offset; - }; - - _proto2.offsetOfLocalDateTime = function offsetOfLocalDateTime() { - return this._offset; - }; - - _proto2.validOffsets = function validOffsets() { - return [this._offset]; - }; - - _proto2.transition = function transition() { - return null; - }; - - _proto2.standardOffset = function standardOffset() { - return this._offset; - }; - - _proto2.daylightSavings = function daylightSavings() { - return Duration.ZERO; - }; - - _proto2.isDaylightSavings = function isDaylightSavings() { - return false; - }; - - _proto2.isValidOffset = function isValidOffset(localDateTime, offset) { - return this._offset.equals(offset); - }; - - _proto2.nextTransition = function nextTransition() { - return null; - }; - - _proto2.previousTransition = function previousTransition() { - return null; - }; - - _proto2.transitions = function transitions() { - return []; - }; - - _proto2.transitionRules = function transitionRules() { - return []; - }; - - _proto2.equals = function equals(other) { - if (this === other) { - return true; - } - - if (other instanceof Fixed) { - return this._offset.equals(other._offset); - } - - return false; - }; - - _proto2.toString = function toString() { - return 'FixedRules:' + this._offset.toString(); - }; - - return Fixed; - }(ZoneRules); - - var SECONDS_CACHE = {}; - var ID_CACHE = {}; - var ZoneOffset = function (_ZoneId) { - _inheritsLoose(ZoneOffset, _ZoneId); - - function ZoneOffset(totalSeconds) { - var _this; - - _this = _ZoneId.call(this) || this; - - ZoneOffset._validateTotalSeconds(totalSeconds); - - _this._totalSeconds = MathUtil.safeToInt(totalSeconds); - _this._rules = ZoneRules.of(_assertThisInitialized(_this)); - _this._id = ZoneOffset._buildId(totalSeconds); - return _this; - } - - var _proto = ZoneOffset.prototype; - - _proto.totalSeconds = function totalSeconds() { - return this._totalSeconds; - }; - - _proto.id = function id() { - return this._id; - }; - - ZoneOffset._buildId = function _buildId(totalSeconds) { - if (totalSeconds === 0) { - return 'Z'; - } else { - var absTotalSeconds = Math.abs(totalSeconds); - var absHours = MathUtil.intDiv(absTotalSeconds, LocalTime.SECONDS_PER_HOUR); - var absMinutes = MathUtil.intMod(MathUtil.intDiv(absTotalSeconds, LocalTime.SECONDS_PER_MINUTE), LocalTime.MINUTES_PER_HOUR); - var buf = '' + (totalSeconds < 0 ? '-' : '+') + (absHours < 10 ? '0' : '') + absHours + (absMinutes < 10 ? ':0' : ':') + absMinutes; - var absSeconds = MathUtil.intMod(absTotalSeconds, LocalTime.SECONDS_PER_MINUTE); - - if (absSeconds !== 0) { - buf += (absSeconds < 10 ? ':0' : ':') + absSeconds; - } - - return buf; - } - }; - - ZoneOffset._validateTotalSeconds = function _validateTotalSeconds(totalSeconds) { - if (Math.abs(totalSeconds) > ZoneOffset.MAX_SECONDS) { - throw new DateTimeException('Zone offset not in valid range: -18:00 to +18:00'); - } - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +var uuid = __nccwpck_require__(19744); // want to replace with this in the future: https://gist.github.com/jed/982883 + + + +var LEVEL_STRING_MAP = { + 0 : 'ERROR:', + 1 : 'WARNING:', + 2 : 'INFO:', + 3 : 'VERBOSE:' +}; + +/** + * Methods for controling global logging options for ADAL + * @namespace + */ +var Logging = { + + /** + * @callback LoggingCallback + * @memberOf Logging + * @param {Logging.LOGGING_LEVEL} level The level of this log entry. + * @param {string} message The text content of the log entry. + * @param {Error} [error] An Error object if this is an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry. + */ + + /** + * @typedef LoggingOptions + * @memberOf Logging + * @property {LoggingCallback} [log] The function to call when ADAL generates a log entry. + * @property {Logging.LOGGING_LEVEL} [level] The maximum level of log entries to generate. + */ + + /** + * Describes the available logging levels. + * @enum + * @type {Number} + */ + LOGGING_LEVEL : { + ERROR : 0, + WARN : 1, + INFO : 2, + VERBOSE : 3 + }, + + /** + * Sets global logging options for ADAL. + * @param {LoggingOptions} options + */ + setLoggingOptions : function(options) { + if (!options) { + options = {}; + } + + if (options.log) { + if (!_.isFunction(options.log)) { + throw new Error('setLogOptions expects the log key in the options parameter to be a function'); + } + } else { + // if no log function was passed set it to a default no op function. + options.log = function() {}; + } + + if (options.level) { + var level = options.level; + if (level < 0 || level > 3) { + throw new Error('setLogOptions expects the level key to be in the range 0 to 3 inclusive'); + } + } else { + options.level = this.LOGGING_LEVEL.ERROR; + } + + if (options.loggingWithPII != true) { + options.loggingWithPII = false; + } + + this.LogOptions = options; + }, + + /** + * Get's the current global logging options. + * @return {LoggingOptions} + */ + getLoggingOptions : function() { + return this.LogOptions; + }, + + /** + * Stores the current global logging options. + * @private + * @type {LoggingOptions} + */ + LogOptions : { + log : function() {}, + level : 0, + loggingWithPII: false + } +}; + +/** + * An internal logging object. + * @class + * @private + * @param {string} componentName The name of the component that created this instance. This name will be + * prepended to the beginning of all log entries generated by this instance. + */ +function Logger(componentName, logContext) { + if (!logContext) { + throw new Error('Logger: logContext is a required parameter'); + } + this._componentName = componentName; + this._logContext = logContext; +} + +Object.defineProperty(Logger.prototype, 'context', { + get: function () { + return this._logContext; + } +}); + +/** + * Generates a log entry + * @param {Logging.LOGGING_LEVEL} level The level of this log entry + * @param {string|function} message A message string, or a function that returns a message string, to log. + * @param {Error} [error] If this is a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry then the caller + * should pass an error object in this parameter. + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.log = function (level, message, error, containsPII) { + if (containsPII == true && !Logging.LogOptions.loggingWithPII) { + return; + } + + if (level <= Logging.LogOptions.level) { + if (_.isFunction(message)) { + message = message(); + } + + var correlationId = this._logContext.correlationId || ''; + var timeStamp = new Date().toUTCString(); + + var formattedMessage = timeStamp + ':' + correlationId + ' - ' + this._componentName + ': ' + LEVEL_STRING_MAP[level] + ' ' + message; + if (error) { + formattedMessage += '\nStack:\n' + error.stack; + } + Logging.LogOptions.log(level, formattedMessage, error); + } +}; + +/** + * Generate an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry. + * @param {string} message A message to log + * @param {Error} error The Error object associated with this log entry + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.error = function (message, error, containsPII) { + this.log(Logging.LOGGING_LEVEL.ERROR, message, error, containsPII); +}; + +/** + * Generate an {@link Logging.LOGGING_LEVEL.WARN|WARN} level log entry. + * @param {string} message A message to log + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.warn = function (message, containsPII) { + this.log(Logging.LOGGING_LEVEL.WARN, message, null, containsPII); +}; + +/** + * Generate an {@link Logging.LOGGING_LEVEL.INFO|INFO} level log entry. + * @param {string} message A message to log + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.info = function (message, containsPII) { + this.log(Logging.LOGGING_LEVEL.INFO, message, null, containsPII); +}; + +/** + * Generate an {@link Logging.LOGGING_LEVEL.VERBOSE|VERBOSE} level log entry. + * @param {string} message A message to log + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.verbose = function (message, containsPII) { + this.log(Logging.LOGGING_LEVEL.VERBOSE, message, null, containsPII); +}; + +/** + * Generate a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry, as well as an + * Error object to go with it. This is a convenience method for throwing logged errors. + * @param {string} message A message to log + * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. + */ +Logger.prototype.createError = function(message, containsPII) { + var err = new Error(message); + this.error(message, err, containsPII); + return err; +}; + +/** + * Creates a new log context based on the correlationId passed in. If no correlationId is passed in + * then one is generated, by the function uuid.v4() + * @private + */ +function createLogContext(correlationId) { + var id = correlationId || uuid.v4(); + return { correlationId : id }; +} + +var exports = { + Logging : Logging, + Logger : Logger, + createLogContext : createLogContext +}; + +module.exports = exports; - ZoneOffset._validate = function _validate(hours, minutes, seconds) { - if (hours < -18 || hours > 18) { - throw new DateTimeException('Zone offset hours not in valid range: value ' + hours + ' is not in the range -18 to 18'); - } +/***/ }), - if (hours > 0) { - if (minutes < 0 || seconds < 0) { - throw new DateTimeException('Zone offset minutes and seconds must be positive because hours is positive'); - } - } else if (hours < 0) { - if (minutes > 0 || seconds > 0) { - throw new DateTimeException('Zone offset minutes and seconds must be negative because hours is negative'); - } - } else if (minutes > 0 && seconds < 0 || minutes < 0 && seconds > 0) { - throw new DateTimeException('Zone offset minutes and seconds must have the same sign'); - } +/***/ 92474: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (Math.abs(minutes) > 59) { - throw new DateTimeException('Zone offset minutes not in valid range: abs(value) ' + Math.abs(minutes) + ' is not in the range 0 to 59'); - } +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + + +var _ = __nccwpck_require__(83571); + +/** + * Constructs a new in memory token cache. + * @constructor + */ +function MemoryCache() { + this._entries = []; +} + +/** + * Removes a collection of entries from the cache in a single batch operation. + * @param {Array} entries An array of cache entries to remove. + * @param {Function} callback This function is called when the operation is complete. Any error is provided as the + * first parameter. + */ +MemoryCache.prototype.remove = function(entries, callback) { + var updatedEntries = _.filter(this._entries, function(element) { + if (_.findWhere(entries, element)) { + return false; + } + return true; + }); + + this._entries = updatedEntries; + callback(); +}; + +/** + * Adds a collection of entries to the cache in a single batch operation. + * @param {Array} entries An array of entries to add to the cache. + * @param {Function} callback This function is called when the operation is complete. Any error is provided as the + * first parameter. + */ +MemoryCache.prototype.add = function(entries, callback) { + // Remove any entries that are duplicates of the existing + // cache elements. + _.each(this._entries, function(element) { + _.each(entries, function(addElement, index) { + if (_.isEqual(element, addElement)) { + entries[index] = null; + } + }); + }); + + // Add the new entries to the end of the cache. + entries = _.compact(entries); + for (var i = 0; i < entries.length; i++) { + this._entries.push(entries[i]); + } + + callback(null, true); +}; + +/** + * Finds all entries in the cache that match all of the passed in values. + * @param {object} query This object will be compared to each entry in the cache. Any entries that + * match all of the values in this object will be returned. All the values + * in the passed in object must match values in a potentialy returned object + * exactly. The returned object may have more values than the passed in query + * object. + * @param {TokenCacheFindCallback} callback + */ +MemoryCache.prototype.find = function(query, callback) { + var results = _.where(this._entries, query); + callback(null, results); +}; + +module.exports = MemoryCache; - if (Math.abs(seconds) > 59) { - throw new DateTimeException('Zone offset seconds not in valid range: abs(value) ' + Math.abs(seconds) + ' is not in the range 0 to 59'); - } +/***/ }), - if (Math.abs(hours) === 18 && (Math.abs(minutes) > 0 || Math.abs(seconds) > 0)) { - throw new DateTimeException('Zone offset not in valid range: -18:00 to +18:00'); - } - }; +/***/ 27078: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - ZoneOffset.of = function of(offsetId) { - requireNonNull(offsetId, 'offsetId'); - var offset = ID_CACHE[offsetId]; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + +var request = __nccwpck_require__(48699); +var url = __nccwpck_require__(78835); +var DOMParser = __nccwpck_require__(57286).DOMParser; +var _ = __nccwpck_require__(83571); +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +var xmlutil = __nccwpck_require__(27387); +var select = xmlutil.xpathSelect; + +var Namespaces = __nccwpck_require__(10282).XmlNamespaces; + +var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; + +/** + * Create a new Mex object. + * @private + * @constructor + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} url The url of the mex endpoint. + */ +function Mex(callContext, url) { + this._log = new Logger('MEX', callContext._logContext); + this._callContext = callContext; + this._url = url; + this._dom = null; + this._mexDoc = null; + this._usernamePasswordPolicy = {}; + this._log.verbose('Mex created'); + this._log.verbose('Mex created with url: ' + url, true); +} + +/** +* Returns the policy containing IDP url and wstrust version from which a username passwowrd can be exchanged for a token. +* @instance +* @memberOf Mex +* @name usernamePasswordPolicy +*/ +Object.defineProperty(Mex.prototype, 'usernamePasswordPolicy', { + get: function() { + return this._usernamePasswordPolicy; + } +}); + +/** +* @callback DiscoverCallback +* @memberOf Mex +* @param {object} error +*/ + +/** +* Performs Mex discovery. This method will retrieve the mex document, parse it, and extract +* the username password ws-trust endpoint. +* @private +* @param {Mex.DiscoverCallback} callback Called when discover is complete. +*/ +Mex.prototype.discover = function (callback) { + this._log.verbose('Retrieving mex'); + this._log.verbose('Retrieving mex at: ' + this._url); + var self = this; + var options = util.createRequestOptions(self, { headers : { 'Content-Type' : 'application/soap+xml'} }); + request.get(this._url, options, util.createRequestHandler('Mex Get', this._log, callback, + function(response, body) { + try { + self._mexDoc = body; + var options = { + errorHandler : self._log.error + }; + self._dom = new DOMParser(options).parseFromString(self._mexDoc); + self._parse(callback); + return; + } catch (err) { + self._log.error('Failed to parse mex response in to DOM', err, true); + callback(err); + } + }) + ); +}; + +var TRANSPORT_BINDING_XPATH = 'wsp:ExactlyOne/wsp:All/sp:TransportBinding'; +var TRANSPORT_BINDING_2005_XPATH = 'wsp:ExactlyOne/wsp:All/sp2005:TransportBinding'; +/** +* Checks a DOM policy node that is a potentialy appplicable username password policy +* to ensure that it has the correct transport. +* @private +* @param {object} policyNode The policy node to check. +* @returns {string} If the policy matches the desired transport then the id of the policy is returned. +* If not then null is returned. +*/ +Mex.prototype._checkPolicy = function(policyNode) { + var policyId = null; + var id = policyNode.getAttributeNS(Namespaces.wsu, 'Id'); + var transportBindingNodes = select(policyNode, TRANSPORT_BINDING_XPATH); + if (0 === transportBindingNodes.length) { + transportBindingNodes = select(policyNode, TRANSPORT_BINDING_2005_XPATH); + } + if (0 !== transportBindingNodes.length) { + if (id) { + policyId = id; + } + } + if (policyId) { + this._log.verbose('found matching policy id'); + this._log.verbose('found matching policy id: ' + policyId, true); + } else { + if (!id) { + id = ''; + } + this._log.verbose('potential policy did not match required transport binding'); + this._log.verbose('potential policy did not match required transport binding: ' + id, true); + } + return policyId; +}; + +/** +* Finds all username password policies within the mex document. +* @private +* @param xpath The xpath expression for selecting username token nodes. +* @returns {object} A map object that contains objects containing the id of username password polices. +*/ +Mex.prototype._selectUsernamePasswordPolicies = function(xpath) { + var policies = {}; + var usernameTokenNodes = select(this._dom, xpath); + if (!usernameTokenNodes.length) { + this._log.warn('no username token policy nodes found'); + return; + } + for (var i=0; i < usernameTokenNodes.length; i++) { + var policyNode = usernameTokenNodes[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode; + var id = this._checkPolicy(policyNode); + if (id) { + var idRef = '#' + id; + policies[idRef] = { id : idRef }; + } + } + return _.isEmpty(policies) ? null : policies; +}; + +var SOAP_ACTION_XPATH = 'wsdl:operation/soap12:operation/@soapAction'; +var RST_SOAP_ACTION_13 = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; +var RST_SOAP_ACTION_2005 = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'; +var SOAP_TRANSPORT_XPATH = 'soap12:binding/@transport'; +var SOAP_HTTP_TRANSPORT_VALUE = 'http://schemas.xmlsoap.org/soap/http'; +/** +* Given a DOM binding node determines whether it matches the correct soap action and transport. +* @private +* @param {object} bindingNode The DOM node to check. +* @returns {bool} +*/ +Mex.prototype._checkSoapActionAndTransport = function(bindingNode) { + var soapTransportAttributes; + var soapAction; + var soapTransport; + var bindingName = bindingNode.getAttribute('name'); + var soapActionAttributes = select(bindingNode, SOAP_ACTION_XPATH); + if (soapActionAttributes.length) { + soapAction = soapActionAttributes[0].value; + soapTransportAttributes = select(bindingNode, SOAP_TRANSPORT_XPATH); + } + if (soapTransportAttributes.length) { + soapTransport = soapTransportAttributes[0].value; + } + + if (soapTransport === SOAP_HTTP_TRANSPORT_VALUE) { + if (soapAction === RST_SOAP_ACTION_13) { + this._log.verbose('foud binding matching Action and Transport: ' + bindingName); + return WSTrustVersion.WSTRUST13; + } + else if (soapAction === RST_SOAP_ACTION_2005) { + this._log.verbose('found binding matching Action and Transport: ' + bindingName); + return WSTrustVersion.WSTRUST2005; + } + } + + this._log.verbose('binding node did not match soap Action or Transport: ' + bindingName); + return WSTrustVersion.UNDEFINED; +}; + +/** +* Given a map with policy id keys, finds the bindings in the mex document that are linked to thos policies. +* @private +* @param {object} policies A map with policy id keys. +* @returns {object} a map of bindings id's to policy id's. +*/ +Mex.prototype._getMatchingBindings = function(policies) { + var bindings = {}; + var bindingPolicyRefNodes = select(this._dom, '//wsdl:definitions/wsdl:binding/wsp:PolicyReference'); + for (var i=0; i < bindingPolicyRefNodes.length; i++) { + var node = bindingPolicyRefNodes[i]; + var uri = node.getAttribute('URI'); + var policy = policies[uri]; + if (policy) { + var bindingNode = node.parentNode; + var bindingName = bindingNode.getAttribute('name'); + var version = this._checkSoapActionAndTransport(bindingNode); + if (version !== WSTrustVersion.UNDEFINED) { + var bindingPolicy = {}; + bindingPolicy.url = uri; + bindingPolicy.version = version; + + bindings[bindingName] = bindingPolicy; + } + } + } + return _.isEmpty(bindings) ? null : bindings; +}; + +/** +* Ensures that a url points to an SSL endpoint. +* @private +* @param {string} endpointUrl The url to check. +* @returns {bool} +*/ +Mex.prototype._urlIsSecure = function(endpointUrl) { + var parsedUrl = url.parse(endpointUrl); + return parsedUrl.protocol === 'https:'; +}; + +var PORT_XPATH = '//wsdl:definitions/wsdl:service/wsdl:port'; +var ADDRESS_XPATH = 'wsa10:EndpointReference/wsa10:Address'; +/** +* Finds all of the wsdl ports in the mex document that are associated with username password policies. Augments +* the passed in bindings with the endpoint url of the correct port. +* @private +* @param {object} bindings A map of binding id's to policy id's. +*/ +Mex.prototype._getPortsForPolicyBindings = function(bindings, policies) { + var portNodes = select(this._dom, PORT_XPATH); + if (0 === portNodes.length) { + this._log.warning('no ports found'); + } + for (var i=0; i < portNodes.length; i++) { + var portNode = portNodes[i]; + var bindingId = portNode.getAttribute('binding'); + + // Clear any prefix + var bindingIdParts = bindingId.split(':'); + bindingId = bindingIdParts[bindingIdParts.length - 1]; + + var trustPolicy = bindings[bindingId]; + if (trustPolicy) { + var bindingPolicy = policies[trustPolicy.url]; + + if (bindingPolicy && !bindingPolicy.url) { + bindingPolicy.version = trustPolicy.version; + var addressNode = select(portNode, ADDRESS_XPATH); + if (0 === addressNode) { + throw this._log.createError('no address nodes on port.'); + } + var address = xmlutil.findElementText(addressNode[0]); + if (this._urlIsSecure(address)) { + bindingPolicy.url = address; + } else { + this._log.warn('skipping insecure endpoint: ' + address); + } + } + } + } +}; + +/** +* Given a list of username password policies chooses one of them at random as the policy chosen by this Mex instance. +* @private +* @param {object} policies A map of policy id's to an object containing username password ws-trust endpoint addresses. +*/ +Mex.prototype._selectSingleMatchingPolicy = function(policies) { + // if both wstrust13 and wstrust2005 policy exists, then choose wstrust13, otherwise choose whatever exists. + var matchingPolicies = _.filter(policies, function(policy) { return policy.url ? true : false; }); + if (!matchingPolicies) { + this._log.warn('no policies found with an url'); + return; + } + + var wstrust13Policy = null, wstrust2005Policy = null; + for(var i = 0; i < matchingPolicies.length; ++i) { + var matchingPolicy = matchingPolicies[i]; + if (WSTrustVersion.WSTRUST13 === matchingPolicy.version) { + wstrust13Policy = matchingPolicy; + } + else if (WSTrustVersion.WSTRUST2005 === matchingPolicy.version) { + wstrust2005Policy = matchingPolicy; + } + } + + if (!wstrust13Policy && !wstrust2005Policy) { + this._log.warn('no policies found with an url'); + this._usernamePasswordPolicy = null; + return; + } + + this._usernamePasswordPolicy = wstrust13Policy ? wstrust13Policy : wstrust2005Policy; +}; + +/** +* Parses the mex document previously retrieved. +* @private +* @param {Mex.DiscoverCallback} callback +*/ +Mex.prototype._parse = function(callback) { + var self = this; + var xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp:SignedEncryptedSupportingTokens/wsp:Policy/sp:UsernameToken/wsp:Policy/sp:WssUsernameToken10'; + var policies = self._selectUsernamePasswordPolicies(xpathExpression); + + xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp2005:SignedSupportingTokens/wsp:Policy/sp2005:UsernameToken/wsp:Policy/sp2005:WssUsernameToken10'; + + if (policies) { + _.extend(policies, self._selectUsernamePasswordPolicies(xpathExpression)); + } + else { + policies = self._selectUsernamePasswordPolicies(xpathExpression); + } + + if (!policies) { + callback(self._log.createError('No matching policies')); + return; + } + var bindings = self._getMatchingBindings(policies); + if (!bindings) { + callback(self._log.createError('No matching bindings')); + return; + } + self._getPortsForPolicyBindings(bindings, policies); + self._selectSingleMatchingPolicy(policies); + var err = this._url ? undefined : this._log.createError('No ws-trust endpoints match requirements.'); + callback(err); +}; + +module.exports = Mex; - if (offset != null) { - return offset; - } +/***/ }), - var hours, minutes, seconds; +/***/ 41602: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - switch (offsetId.length) { - case 2: - offsetId = offsetId[0] + '0' + offsetId[1]; - - case 3: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = 0; - seconds = 0; - break; - - case 5: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = ZoneOffset._parseNumber(offsetId, 3, false); - seconds = 0; - break; - - case 6: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = ZoneOffset._parseNumber(offsetId, 4, true); - seconds = 0; - break; - - case 7: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = ZoneOffset._parseNumber(offsetId, 3, false); - seconds = ZoneOffset._parseNumber(offsetId, 5, false); - break; - - case 9: - hours = ZoneOffset._parseNumber(offsetId, 1, false); - minutes = ZoneOffset._parseNumber(offsetId, 4, true); - seconds = ZoneOffset._parseNumber(offsetId, 7, true); - break; - - default: - throw new DateTimeException('Invalid ID for ZoneOffset, invalid format: ' + offsetId); - } - - var first = offsetId[0]; - - if (first !== '+' && first !== '-') { - throw new DateTimeException('Invalid ID for ZoneOffset, plus/minus not found when expected: ' + offsetId); - } - - if (first === '-') { - return ZoneOffset.ofHoursMinutesSeconds(-hours, -minutes, -seconds); - } else { - return ZoneOffset.ofHoursMinutesSeconds(hours, minutes, seconds); - } - }; - - ZoneOffset._parseNumber = function _parseNumber(offsetId, pos, precededByColon) { - if (precededByColon && offsetId[pos - 1] !== ':') { - throw new DateTimeException('Invalid ID for ZoneOffset, colon not found when expected: ' + offsetId); - } - - var ch1 = offsetId[pos]; - var ch2 = offsetId[pos + 1]; - - if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') { - throw new DateTimeException('Invalid ID for ZoneOffset, non numeric characters found: ' + offsetId); - } - - return (ch1.charCodeAt(0) - 48) * 10 + (ch2.charCodeAt(0) - 48); - }; - - ZoneOffset.ofHours = function ofHours(hours) { - return ZoneOffset.ofHoursMinutesSeconds(hours, 0, 0); - }; - - ZoneOffset.ofHoursMinutes = function ofHoursMinutes(hours, minutes) { - return ZoneOffset.ofHoursMinutesSeconds(hours, minutes, 0); - }; - - ZoneOffset.ofHoursMinutesSeconds = function ofHoursMinutesSeconds(hours, minutes, seconds) { - ZoneOffset._validate(hours, minutes, seconds); - - var totalSeconds = hours * LocalTime.SECONDS_PER_HOUR + minutes * LocalTime.SECONDS_PER_MINUTE + seconds; - return ZoneOffset.ofTotalSeconds(totalSeconds); - }; - - ZoneOffset.ofTotalMinutes = function ofTotalMinutes(totalMinutes) { - var totalSeconds = totalMinutes * LocalTime.SECONDS_PER_MINUTE; - return ZoneOffset.ofTotalSeconds(totalSeconds); - }; - - ZoneOffset.ofTotalSeconds = function ofTotalSeconds(totalSeconds) { - if (totalSeconds % (15 * LocalTime.SECONDS_PER_MINUTE) === 0) { - var totalSecs = totalSeconds; - var result = SECONDS_CACHE[totalSecs]; - - if (result == null) { - result = new ZoneOffset(totalSeconds); - SECONDS_CACHE[totalSecs] = result; - ID_CACHE[result.id()] = result; - } - - return result; - } else { - return new ZoneOffset(totalSeconds); - } - }; - - _proto.rules = function rules() { - return this._rules; - }; - - _proto.get = function get(field) { - return this.getLong(field); - }; - - _proto.getLong = function getLong(field) { - if (field === ChronoField.OFFSET_SECONDS) { - return this._totalSeconds; - } else if (field instanceof ChronoField) { - throw new DateTimeException('Unsupported field: ' + field); - } - - return field.getFrom(this); - }; - - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - - if (_query === TemporalQueries.offset() || _query === TemporalQueries.zone()) { - return this; - } else if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.precision() || _query === TemporalQueries.chronology() || _query === TemporalQueries.zoneId()) { - return null; - } - - return _query.queryFrom(this); - }; - - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.OFFSET_SECONDS, this._totalSeconds); - }; - - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - return other._totalSeconds - this._totalSeconds; - }; - - _proto.equals = function equals(obj) { - if (this === obj) { - return true; - } - - if (obj instanceof ZoneOffset) { - return this._totalSeconds === obj._totalSeconds; - } - - return false; - }; - - _proto.hashCode = function hashCode() { - return this._totalSeconds; - }; - - _proto.toString = function toString() { - return this._id; - }; - - return ZoneOffset; - }(ZoneId); - function _init$7() { - ZoneOffset.MAX_SECONDS = 18 * LocalTime.SECONDS_PER_HOUR; - ZoneOffset.UTC = ZoneOffset.ofTotalSeconds(0); - ZoneOffset.MIN = ZoneOffset.ofTotalSeconds(-ZoneOffset.MAX_SECONDS); - ZoneOffset.MAX = ZoneOffset.ofTotalSeconds(ZoneOffset.MAX_SECONDS); - } - - var DateTimeBuilder = function (_TemporalAccessor) { - _inheritsLoose(DateTimeBuilder, _TemporalAccessor); - - DateTimeBuilder.create = function create(field, value) { - var dtb = new DateTimeBuilder(); - - dtb._addFieldValue(field, value); - - return dtb; - }; - - function DateTimeBuilder() { - var _this; - - _this = _TemporalAccessor.call(this) || this; - _this.fieldValues = new EnumMap(); - _this.chrono = null; - _this.zone = null; - _this.date = null; - _this.time = null; - _this.leapSecond = false; - _this.excessDays = null; - return _this; - } - - var _proto = DateTimeBuilder.prototype; - - _proto.getFieldValue0 = function getFieldValue0(field) { - return this.fieldValues.get(field); - }; - - _proto._addFieldValue = function _addFieldValue(field, value) { - requireNonNull(field, 'field'); - var old = this.getFieldValue0(field); - - if (old != null && old !== value) { - throw new DateTimeException('Conflict found: ' + field + ' ' + old + ' differs from ' + field + ' ' + value + ': ' + this); - } - - return this._putFieldValue0(field, value); - }; - - _proto._putFieldValue0 = function _putFieldValue0(field, value) { - this.fieldValues.put(field, value); - return this; - }; - - _proto.resolve = function resolve(resolverStyle, resolverFields) { - if (resolverFields != null) { - this.fieldValues.retainAll(resolverFields); - } - - this._mergeDate(resolverStyle); - - this._mergeTime(resolverStyle); - - this._resolveTimeInferZeroes(resolverStyle); - - if (this.excessDays != null && this.excessDays.isZero() === false && this.date != null && this.time != null) { - this.date = this.date.plus(this.excessDays); - this.excessDays = Period.ZERO; - } - - this._resolveInstant(); - - return this; - }; - - _proto._mergeDate = function _mergeDate(resolverStyle) { - this._checkDate(IsoChronology.INSTANCE.resolveDate(this.fieldValues, resolverStyle)); - }; - - _proto._checkDate = function _checkDate(date) { - if (date != null) { - this._addObject(date); - - for (var fieldName in this.fieldValues.keySet()) { - var field = ChronoField.byName(fieldName); - - if (field) { - if (this.fieldValues.get(field) !== undefined) { - if (field.isDateBased()) { - var val1 = void 0; - - try { - val1 = date.getLong(field); - } catch (ex) { - if (ex instanceof DateTimeException) { - continue; - } else { - throw ex; - } - } - - var val2 = this.fieldValues.get(field); - - if (val1 !== val2) { - throw new DateTimeException('Conflict found: Field ' + field + ' ' + val1 + ' differs from ' + field + ' ' + val2 + ' derived from ' + date); - } - } - } - } - } - } - }; - - _proto._mergeTime = function _mergeTime(resolverStyle) { - if (this.fieldValues.containsKey(ChronoField.CLOCK_HOUR_OF_DAY)) { - var ch = this.fieldValues.remove(ChronoField.CLOCK_HOUR_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (resolverStyle === ResolverStyle.SMART && ch === 0) ; else { - ChronoField.CLOCK_HOUR_OF_DAY.checkValidValue(ch); - } - } - - this._addFieldValue(ChronoField.HOUR_OF_DAY, ch === 24 ? 0 : ch); - } - - if (this.fieldValues.containsKey(ChronoField.CLOCK_HOUR_OF_AMPM)) { - var _ch = this.fieldValues.remove(ChronoField.CLOCK_HOUR_OF_AMPM); - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (resolverStyle === ResolverStyle.SMART && _ch === 0) ; else { - ChronoField.CLOCK_HOUR_OF_AMPM.checkValidValue(_ch); - } - } - - this._addFieldValue(ChronoField.HOUR_OF_AMPM, _ch === 12 ? 0 : _ch); - } - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (this.fieldValues.containsKey(ChronoField.AMPM_OF_DAY)) { - ChronoField.AMPM_OF_DAY.checkValidValue(this.fieldValues.get(ChronoField.AMPM_OF_DAY)); - } - - if (this.fieldValues.containsKey(ChronoField.HOUR_OF_AMPM)) { - ChronoField.HOUR_OF_AMPM.checkValidValue(this.fieldValues.get(ChronoField.HOUR_OF_AMPM)); - } - } - - if (this.fieldValues.containsKey(ChronoField.AMPM_OF_DAY) && this.fieldValues.containsKey(ChronoField.HOUR_OF_AMPM)) { - var ap = this.fieldValues.remove(ChronoField.AMPM_OF_DAY); - var hap = this.fieldValues.remove(ChronoField.HOUR_OF_AMPM); - - this._addFieldValue(ChronoField.HOUR_OF_DAY, ap * 12 + hap); - } - - if (this.fieldValues.containsKey(ChronoField.NANO_OF_DAY)) { - var nod = this.fieldValues.remove(ChronoField.NANO_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.NANO_OF_DAY.checkValidValue(nod); - } - - this._addFieldValue(ChronoField.SECOND_OF_DAY, MathUtil.intDiv(nod, 1000000000)); - - this._addFieldValue(ChronoField.NANO_OF_SECOND, MathUtil.intMod(nod, 1000000000)); - } - - if (this.fieldValues.containsKey(ChronoField.MICRO_OF_DAY)) { - var cod = this.fieldValues.remove(ChronoField.MICRO_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.MICRO_OF_DAY.checkValidValue(cod); - } - - this._addFieldValue(ChronoField.SECOND_OF_DAY, MathUtil.intDiv(cod, 1000000)); - - this._addFieldValue(ChronoField.MICRO_OF_SECOND, MathUtil.intMod(cod, 1000000)); - } - - if (this.fieldValues.containsKey(ChronoField.MILLI_OF_DAY)) { - var lod = this.fieldValues.remove(ChronoField.MILLI_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.MILLI_OF_DAY.checkValidValue(lod); - } - - this._addFieldValue(ChronoField.SECOND_OF_DAY, MathUtil.intDiv(lod, 1000)); - - this._addFieldValue(ChronoField.MILLI_OF_SECOND, MathUtil.intMod(lod, 1000)); - } - - if (this.fieldValues.containsKey(ChronoField.SECOND_OF_DAY)) { - var sod = this.fieldValues.remove(ChronoField.SECOND_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.SECOND_OF_DAY.checkValidValue(sod); - } - - this._addFieldValue(ChronoField.HOUR_OF_DAY, MathUtil.intDiv(sod, 3600)); - - this._addFieldValue(ChronoField.MINUTE_OF_HOUR, MathUtil.intMod(MathUtil.intDiv(sod, 60), 60)); - - this._addFieldValue(ChronoField.SECOND_OF_MINUTE, MathUtil.intMod(sod, 60)); - } - - if (this.fieldValues.containsKey(ChronoField.MINUTE_OF_DAY)) { - var mod = this.fieldValues.remove(ChronoField.MINUTE_OF_DAY); - - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.MINUTE_OF_DAY.checkValidValue(mod); - } - - this._addFieldValue(ChronoField.HOUR_OF_DAY, MathUtil.intDiv(mod, 60)); - - this._addFieldValue(ChronoField.MINUTE_OF_HOUR, MathUtil.intMod(mod, 60)); - } - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (this.fieldValues.containsKey(ChronoField.MILLI_OF_SECOND)) { - ChronoField.MILLI_OF_SECOND.checkValidValue(this.fieldValues.get(ChronoField.MILLI_OF_SECOND)); - } - - if (this.fieldValues.containsKey(ChronoField.MICRO_OF_SECOND)) { - ChronoField.MICRO_OF_SECOND.checkValidValue(this.fieldValues.get(ChronoField.MICRO_OF_SECOND)); - } - } - - if (this.fieldValues.containsKey(ChronoField.MILLI_OF_SECOND) && this.fieldValues.containsKey(ChronoField.MICRO_OF_SECOND)) { - var los = this.fieldValues.remove(ChronoField.MILLI_OF_SECOND); - var cos = this.fieldValues.get(ChronoField.MICRO_OF_SECOND); - - this._putFieldValue0(ChronoField.MICRO_OF_SECOND, los * 1000 + MathUtil.intMod(cos, 1000)); - } - - if (this.fieldValues.containsKey(ChronoField.MICRO_OF_SECOND) && this.fieldValues.containsKey(ChronoField.NANO_OF_SECOND)) { - var nos = this.fieldValues.get(ChronoField.NANO_OF_SECOND); - - this._putFieldValue0(ChronoField.MICRO_OF_SECOND, MathUtil.intDiv(nos, 1000)); - - this.fieldValues.remove(ChronoField.MICRO_OF_SECOND); - } - - if (this.fieldValues.containsKey(ChronoField.MILLI_OF_SECOND) && this.fieldValues.containsKey(ChronoField.NANO_OF_SECOND)) { - var _nos = this.fieldValues.get(ChronoField.NANO_OF_SECOND); - - this._putFieldValue0(ChronoField.MILLI_OF_SECOND, MathUtil.intDiv(_nos, 1000000)); - - this.fieldValues.remove(ChronoField.MILLI_OF_SECOND); - } - - if (this.fieldValues.containsKey(ChronoField.MICRO_OF_SECOND)) { - var _cos = this.fieldValues.remove(ChronoField.MICRO_OF_SECOND); - - this._putFieldValue0(ChronoField.NANO_OF_SECOND, _cos * 1000); - } else if (this.fieldValues.containsKey(ChronoField.MILLI_OF_SECOND)) { - var _los = this.fieldValues.remove(ChronoField.MILLI_OF_SECOND); - - this._putFieldValue0(ChronoField.NANO_OF_SECOND, _los * 1000000); - } - }; - - _proto._resolveTimeInferZeroes = function _resolveTimeInferZeroes(resolverStyle) { - var hod = this.fieldValues.get(ChronoField.HOUR_OF_DAY); - var moh = this.fieldValues.get(ChronoField.MINUTE_OF_HOUR); - var som = this.fieldValues.get(ChronoField.SECOND_OF_MINUTE); - var nos = this.fieldValues.get(ChronoField.NANO_OF_SECOND); - - if (hod == null) { - return; - } - - if (moh == null && (som != null || nos != null)) { - return; - } - - if (moh != null && som == null && nos != null) { - return; - } - - if (resolverStyle !== ResolverStyle.LENIENT) { - if (hod != null) { - if (resolverStyle === ResolverStyle.SMART && hod === 24 && (moh == null || moh === 0) && (som == null || som === 0) && (nos == null || nos === 0)) { - hod = 0; - this.excessDays = Period.ofDays(1); - } - - var hodVal = ChronoField.HOUR_OF_DAY.checkValidIntValue(hod); - - if (moh != null) { - var mohVal = ChronoField.MINUTE_OF_HOUR.checkValidIntValue(moh); - - if (som != null) { - var somVal = ChronoField.SECOND_OF_MINUTE.checkValidIntValue(som); - - if (nos != null) { - var nosVal = ChronoField.NANO_OF_SECOND.checkValidIntValue(nos); - - this._addObject(LocalTime.of(hodVal, mohVal, somVal, nosVal)); - } else { - this._addObject(LocalTime.of(hodVal, mohVal, somVal)); - } - } else { - if (nos == null) { - this._addObject(LocalTime.of(hodVal, mohVal)); - } - } - } else { - if (som == null && nos == null) { - this._addObject(LocalTime.of(hodVal, 0)); - } - } - } - } else { - if (hod != null) { - var _hodVal = hod; - - if (moh != null) { - if (som != null) { - if (nos == null) { - nos = 0; - } - - var totalNanos = MathUtil.safeMultiply(_hodVal, 3600000000000); - totalNanos = MathUtil.safeAdd(totalNanos, MathUtil.safeMultiply(moh, 60000000000)); - totalNanos = MathUtil.safeAdd(totalNanos, MathUtil.safeMultiply(som, 1000000000)); - totalNanos = MathUtil.safeAdd(totalNanos, nos); - var excessDays = MathUtil.floorDiv(totalNanos, 86400000000000); - var nod = MathUtil.floorMod(totalNanos, 86400000000000); - - this._addObject(LocalTime.ofNanoOfDay(nod)); - - this.excessDays = Period.ofDays(excessDays); - } else { - var totalSecs = MathUtil.safeMultiply(_hodVal, 3600); - totalSecs = MathUtil.safeAdd(totalSecs, MathUtil.safeMultiply(moh, 60)); - - var _excessDays = MathUtil.floorDiv(totalSecs, 86400); - - var sod = MathUtil.floorMod(totalSecs, 86400); - - this._addObject(LocalTime.ofSecondOfDay(sod)); - - this.excessDays = Period.ofDays(_excessDays); - } - } else { - var _excessDays2 = MathUtil.safeToInt(MathUtil.floorDiv(_hodVal, 24)); - - _hodVal = MathUtil.floorMod(_hodVal, 24); - - this._addObject(LocalTime.of(_hodVal, 0)); - - this.excessDays = Period.ofDays(_excessDays2); - } - } - } - - this.fieldValues.remove(ChronoField.HOUR_OF_DAY); - this.fieldValues.remove(ChronoField.MINUTE_OF_HOUR); - this.fieldValues.remove(ChronoField.SECOND_OF_MINUTE); - this.fieldValues.remove(ChronoField.NANO_OF_SECOND); - }; - - _proto._addObject = function _addObject(dateOrTime) { - if (dateOrTime instanceof ChronoLocalDate) { - this.date = dateOrTime; - } else if (dateOrTime instanceof LocalTime) { - this.time = dateOrTime; - } - }; - - _proto._resolveInstant = function _resolveInstant() { - if (this.date != null && this.time != null) { - var offsetSecs = this.fieldValues.get(ChronoField.OFFSET_SECONDS); - - if (offsetSecs != null) { - var offset = ZoneOffset.ofTotalSeconds(offsetSecs); - var instant = this.date.atTime(this.time).atZone(offset).getLong(ChronoField.INSTANT_SECONDS); - this.fieldValues.put(ChronoField.INSTANT_SECONDS, instant); - } else if (this.zone != null) { - var _instant = this.date.atTime(this.time).atZone(this.zone).getLong(ChronoField.INSTANT_SECONDS); - - this.fieldValues.put(ChronoField.INSTANT_SECONDS, _instant); - } - } - }; - - _proto.build = function build(type) { - return type.queryFrom(this); - }; - - _proto.isSupported = function isSupported(field) { - if (field == null) { - return false; - } - - return this.fieldValues.containsKey(field) && this.fieldValues.get(field) !== undefined || this.date != null && this.date.isSupported(field) || this.time != null && this.time.isSupported(field); - }; - - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); - var value = this.getFieldValue0(field); - - if (value == null) { - if (this.date != null && this.date.isSupported(field)) { - return this.date.getLong(field); - } - - if (this.time != null && this.time.isSupported(field)) { - return this.time.getLong(field); - } - - throw new DateTimeException('Field not found: ' + field); - } - - return value; - }; - - _proto.query = function query(_query) { - if (_query === TemporalQueries.zoneId()) { - return this.zone; - } else if (_query === TemporalQueries.chronology()) { - return this.chrono; - } else if (_query === TemporalQueries.localDate()) { - return this.date != null ? LocalDate.from(this.date) : null; - } else if (_query === TemporalQueries.localTime()) { - return this.time; - } else if (_query === TemporalQueries.zone() || _query === TemporalQueries.offset()) { - return _query.queryFrom(this); - } else if (_query === TemporalQueries.precision()) { - return null; - } - - return _query.queryFrom(this); - }; - - return DateTimeBuilder; - }(TemporalAccessor); - - var DateTimeParseContext = function () { - function DateTimeParseContext() { - if (arguments.length === 1) { - if (arguments[0] instanceof DateTimeParseContext) { - this._constructorSelf.apply(this, arguments); - - return; - } else { - this._constructorFormatter.apply(this, arguments); - } - } else { - this._constructorParam.apply(this, arguments); - } - - this._caseSensitive = true; - this._strict = true; - this._parsed = [new Parsed(this)]; - } - - var _proto = DateTimeParseContext.prototype; - - _proto._constructorParam = function _constructorParam(locale, symbols, chronology) { - this._locale = locale; - this._symbols = symbols; - this._overrideChronology = chronology; - }; - - _proto._constructorFormatter = function _constructorFormatter(formatter) { - this._locale = formatter.locale(); - this._symbols = formatter.decimalStyle(); - this._overrideChronology = formatter.chronology(); - }; - - _proto._constructorSelf = function _constructorSelf(other) { - this._locale = other._locale; - this._symbols = other._symbols; - this._overrideChronology = other._overrideChronology; - this._overrideZone = other._overrideZone; - this._caseSensitive = other._caseSensitive; - this._strict = other._strict; - this._parsed = [new Parsed(this)]; - }; - - _proto.copy = function copy() { - return new DateTimeParseContext(this); - }; - - _proto.symbols = function symbols() { - return this._symbols; - }; - - _proto.isStrict = function isStrict() { - return this._strict; - }; - - _proto.setStrict = function setStrict(strict) { - this._strict = strict; - }; - - _proto.locale = function locale() { - return this._locale; - }; - - _proto.setLocale = function setLocale(locale) { - this._locale = locale; - }; - - _proto.startOptional = function startOptional() { - this._parsed.push(this.currentParsed().copy()); - }; - - _proto.endOptional = function endOptional(successful) { - if (successful) { - this._parsed.splice(this._parsed.length - 2, 1); - } else { - this._parsed.splice(this._parsed.length - 1, 1); - } - }; - - _proto.isCaseSensitive = function isCaseSensitive() { - return this._caseSensitive; - }; - - _proto.setCaseSensitive = function setCaseSensitive(caseSensitive) { - this._caseSensitive = caseSensitive; - }; - - _proto.subSequenceEquals = function subSequenceEquals(cs1, offset1, cs2, offset2, length) { - if (offset1 + length > cs1.length || offset2 + length > cs2.length) { - return false; - } - - if (!this.isCaseSensitive()) { - cs1 = cs1.toLowerCase(); - cs2 = cs2.toLowerCase(); - } - - for (var i = 0; i < length; i++) { - var ch1 = cs1[offset1 + i]; - var ch2 = cs2[offset2 + i]; - - if (ch1 !== ch2) { - return false; - } - } - - return true; - }; - - _proto.charEquals = function charEquals(ch1, ch2) { - if (this.isCaseSensitive()) { - return ch1 === ch2; - } - - return this.charEqualsIgnoreCase(ch1, ch2); - }; - - _proto.charEqualsIgnoreCase = function charEqualsIgnoreCase(c1, c2) { - return c1 === c2 || c1.toLowerCase() === c2.toLowerCase(); - }; - - _proto.setParsedField = function setParsedField(field, value, errorPos, successPos) { - var currentParsedFieldValues = this.currentParsed().fieldValues; - var old = currentParsedFieldValues.get(field); - currentParsedFieldValues.set(field, value); - return old != null && old !== value ? ~errorPos : successPos; - }; - - _proto.setParsedZone = function setParsedZone(zone) { - requireNonNull(zone, 'zone'); - this.currentParsed().zone = zone; - }; - - _proto.getParsed = function getParsed(field) { - return this.currentParsed().fieldValues.get(field); - }; - - _proto.toParsed = function toParsed() { - return this.currentParsed(); - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +__nccwpck_require__(1693); // Adds a number of convenience methods to the builtin Date object. +var querystring = __nccwpck_require__(71191); +var uuid = __nccwpck_require__(19744); +var request = __nccwpck_require__(48699); +var url = __nccwpck_require__(78835); +var async = __nccwpck_require__(57888); + +var constants = __nccwpck_require__(10282); +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +var OAuth2Parameters = constants.OAuth2.Parameters; +var OAuth2ResponseParameters = constants.OAuth2.ResponseParameters; +var DeviceCodeResponseParameters = constants.OAuth2.DeviceCodeResponseParameters; +var IdTokenMap = constants.OAuth2.IdTokenMap; +var TokenResponseFields = constants.TokenResponseFields; +var UserCodeResponseFields = constants.UserCodeResponseFields; +var IdTokenFields = constants.IdTokenFields; + +var TOKEN_RESPONSE_MAP = {}; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.TOKEN_TYPE] = TokenResponseFields.TOKEN_TYPE; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ACCESS_TOKEN] = TokenResponseFields.ACCESS_TOKEN; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.REFRESH_TOKEN] = TokenResponseFields.REFRESH_TOKEN; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.CREATED_ON] = TokenResponseFields.CREATED_ON; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_ON] = TokenResponseFields.EXPIRES_ON; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_IN] = TokenResponseFields.EXPIRES_IN; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.RESOURCE] = TokenResponseFields.RESOURCE; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR] = TokenResponseFields.ERROR; +TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR_DESCRIPTION] = TokenResponseFields.ERROR_DESCRIPTION; + + +var DEVICE_CODE_RESPONSE_MAP = {}; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.DEVICE_CODE] = UserCodeResponseFields.DEVICE_CODE; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.USER_CODE] = UserCodeResponseFields.USER_CODE; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.VERIFICATION_URL] = UserCodeResponseFields.VERIFICATION_URL; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.INTERVAL] = UserCodeResponseFields.INTERVAL; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.EXPIRES_IN] = UserCodeResponseFields.EXPIRES_IN; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.MESSAGE] = UserCodeResponseFields.MESSAGE; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR] = UserCodeResponseFields.ERROR; +DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR_DESCRIPTION] = UserCodeResponseFields.ERROR_DESCRIPTION; + +/** + * Constructs an instances of OAuth2Client + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {string|url} authority An url that points to an authority. + */ +function OAuth2Client(callContext, authority) { + this._tokenEndpoint = authority.tokenEndpoint; + this._deviceCodeEndpoint = authority.deviceCodeEndpoint; + + this._log = new Logger('OAuth2Client', callContext._logContext); + this._callContext = callContext; + this._cancelPollingRequest = false; +} + +/** + * Constructs an OAuth 2.0 token request url. + * @private + * @return {URL} + */ +OAuth2Client.prototype._createTokenUrl = function () { + var tokenUrl = url.parse(this._tokenEndpoint); + + var parameters = {}; + parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0'; + + tokenUrl.search = querystring.stringify(parameters); + return tokenUrl; +}; + +/** + * Constructs the user code info request url. + * @private + * @return {URL} + */ +OAuth2Client.prototype._createDeviceCodeUrl = function () { + var deviceCodeUrl = url.parse(this._deviceCodeEndpoint); + + var parameters = {}; + parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0'; + + deviceCodeUrl.search = querystring.stringify(parameters); + + return deviceCodeUrl; +}; + +/** + * @private + * @param {object} obj An object in which integer values may reside. + * @param {array} keys An array of strings that specify keys in which integers may need parsing. + */ +OAuth2Client.prototype._parseOptionalInts = function (obj, keys) { + var self = this; + keys.forEach(function(element) { + if (_.has(obj, element)) { + obj[element] = parseInt(obj[element], 10); + if (isNaN(obj[element])) { + throw self._log.createError(element + ' could not be parsed as an int.'); + } + } + }); +}; + +/** + * Parses a JWS encoded JWT into it's three parts. + * @param {string} jwtToken The token to parse. + * @return {object} The three JWS parts, header, JWSPayload, and JWSSig, or undefined. + */ +OAuth2Client.prototype._crackJwt = function(jwtToken) { + var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; + + var matches = idTokenPartsRegex.exec(jwtToken); + if (!matches || matches.length < 4) { + this._log.warn('The returned id_token is not parseable.'); + return; + } + + var crackedToken = { + header : matches[1], + JWSPayload : matches[2], + JWSSig : matches[3] + }; + + return crackedToken; +}; + +/** + * Finds the value that should be used as the userId value. + * @param {object} idToken The id token that parsed. + * @returns {object} An object with a userId field and maybe a userIdIsDisplayable field. + */ +OAuth2Client.prototype._getUserId = function(idToken) { + var userId; + var isDisplayable; + + if (idToken.upn) { + userId = idToken.upn; + isDisplayable = true; + } else if (idToken.email) { + userId = idToken.email; + isDisplayable = true; + } else if (idToken.sub) { + userId = idToken.sub; + } + + if (!userId) { + // generate a random GUID. + userId = uuid.v4(); + } + + var userIdVals = {}; + userIdVals[IdTokenFields.USER_ID] = userId; + if (isDisplayable) { + userIdVals[IdTokenFields.IS_USER_ID_DISPLAYABLE] = true; + } + + return userIdVals; +}; + +function mapFields(inObj, outObj, map) { + for (var key in inObj) { + if (map[key]) { + var mappedKey = map[key]; + outObj[mappedKey] = inObj[key]; + } + } +} + +/** + * Given a decoded id token off the wire, this function extracts the values that + * ADAL commonly returns to callers and translates the names to more user + * friendly names. + * @param {Object} idToken A decoded id token. + * @return {Object} The set of extracted values with their new names. + */ +OAuth2Client.prototype._extractIdTokenValues = function(idToken) { + var extractedValues = {}; + _.extend(extractedValues, this._getUserId(idToken)); + + mapFields(idToken, extractedValues, IdTokenMap); + + return extractedValues; +}; + +/** + * Parses the value of the id_token OAuth 2 Reponse. + * @param {string} encodedIdToken An unencrypted JWT token. + * @return {object} returns the decoded id_token or undefined. + */ +OAuth2Client.prototype._parseIdToken = function(encodedIdToken) { + var crackedToken = this._crackJwt(encodedIdToken); + if (!crackedToken) { + return; + } + + var idToken; + try { + var base64IdToken = crackedToken.JWSPayload; + var base64Decoded = util.base64DecodeStringUrlSafe(base64IdToken); + if (!base64Decoded) { + this._log.warn('The returned id_token could not be base64 url safe decoded.'); + return; + } + + idToken = JSON.parse(base64Decoded); + } catch (err) { + this._log.warn('the returned id_token could not be decoded'); + this._log.warn('The returned id_token could not be decoded: ' + err.stack, true); + return; + } + + return this._extractIdTokenValues(idToken); +}; + +/** + * Validates the response returned from an OAuth 2.0 token request. + * @private + * @param {string} body The response as a string encoded JSON object. + * @return {object} The parsed response. + */ +OAuth2Client.prototype._validateTokenResponse = function(body) { + var wireResponse; + var tokenResponse = {}; + + try { + wireResponse = JSON.parse(body); + } catch(e) { + throw new Error('The token response returned from the server is unparseable as JSON'); + } + + var intKeys = [ + OAuth2ResponseParameters.EXPIRES_ON, + OAuth2ResponseParameters.EXPIRES_IN, + OAuth2ResponseParameters.CREATED_ON + ]; + + this._parseOptionalInts(wireResponse, intKeys); + + if (wireResponse[OAuth2ResponseParameters.EXPIRES_IN]) { + var expiresIn = wireResponse[OAuth2ResponseParameters.EXPIRES_IN]; + var now = new Date(); + wireResponse[OAuth2ResponseParameters.EXPIRES_ON] = now.add( { seconds : expiresIn }); + } + + if (wireResponse[OAuth2ResponseParameters.CREATED_ON]) { + var tempDate = new Date(); + var createdOn = wireResponse[OAuth2ResponseParameters.CREATED_ON]; + tempDate.setTime(createdOn); + wireResponse[OAuth2ResponseParameters.CREATED_ON] = tempDate; + } + + if (!wireResponse[OAuth2ResponseParameters.TOKEN_TYPE]) { + throw this._log.createError('wireResponse is missing token_type'); + } + if (!wireResponse[OAuth2ResponseParameters.ACCESS_TOKEN]) { + throw this._log.createError('wireResponse missing access_token'); + } + + mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); + + if (wireResponse[OAuth2ResponseParameters.ID_TOKEN]) { + var idToken = this._parseIdToken(wireResponse[OAuth2ResponseParameters.ID_TOKEN]); + if (idToken) { + _.extend(tokenResponse, idToken); + } + } + + return tokenResponse; +}; + +/** + * Validates the response returned from an OAuth 2.0 device code request. + * @private + * @param {string} body The response as a string encoded JSON object. + * @return {object} The parsed response. + */ +OAuth2Client.prototype._validateDeviceCodeResponse = function(body) { + var wireResponse; + var deviceCodeResponse = {}; + + try { + wireResponse = JSON.parse(body); + } catch(e) { + throw new Error('The device code response returned from the server is unparseable as JSON.'); + } + + var intKeys = [ + DeviceCodeResponseParameters.EXPIRES_IN, + DeviceCodeResponseParameters.INTERVAL + ]; + + this._parseOptionalInts(wireResponse, intKeys); + + if (!wireResponse[DeviceCodeResponseParameters.EXPIRES_IN]){ + throw this._log.createError('wireResponse is missing expires_in'); + } + + if (!wireResponse[DeviceCodeResponseParameters.DEVICE_CODE]) { + throw this._log.createError('wireResponse is missing device code'); + } + + if (!wireResponse[DeviceCodeResponseParameters.USER_CODE]) { + throw this._log.createError('wireResponse is missing user code'); + } + + mapFields(wireResponse, deviceCodeResponse, DEVICE_CODE_RESPONSE_MAP); + + return deviceCodeResponse; +}; + +/** + * @private + * @param {string} body The body of a http token response. + */ +OAuth2Client.prototype._handlePollingResponse = function(body) { + //handle token error response + var tokenResponse = this._handlePollingRequestErrorResponse(body); + if (_.isEmpty(tokenResponse)){ + tokenResponse = this._validateTokenResponse(body); + } + + return tokenResponse; +}; + +/** + * @private + * @param {string} body The body of a http token response. + */ +OAuth2Client.prototype._handlePollingRequestErrorResponse = function(body) { + var wireResponse; + var tokenResponse = {}; + + try { + wireResponse = JSON.parse(body); + } catch (e) { + throw new Error ('The token response returned from the server is unparsable as JSON'); + } + + if (wireResponse[OAuth2ResponseParameters.ERROR]) { + mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); + } + + return tokenResponse; +}; + +/** + * @private + * @param {object} response An http response object. + * @param {string} body The body of a http token response. + * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed + * into this function. + */ +OAuth2Client.prototype._handleGetTokenResponse = function(response, body, callback) { + var tokenResponse; + try { + tokenResponse = this._validateTokenResponse(body); + } catch (e) { + this._log.error('Error validating get token response', e, true); + callback(e); + return; + } + callback(null, tokenResponse); +}; + +OAuth2Client.prototype._handleGetDeviceCodeResponse = function(response, body, callback) { + var deviceCodeResponse; + try { + deviceCodeResponse = this._validateDeviceCodeResponse(body); + } catch (e) { + this._log.error('Error validating get user code response', e, true); + callback(e); + return; + } + + callback(null, deviceCodeResponse); +}; + +OAuth2Client.prototype._getTokenWithPolling = function (postOptions, callback) { + var self = this; + if (self._cancelPollingRequest === true) { + callback(null, new Error('Polling_Request_Cancelled')); + return; + } + + request.post(postOptions, util.createRequestHandler('Get Token', this._log, function(response, body) { + //error response callback, for error response, it's already parsed as Json. + if (body && body.hasOwnProperty(TokenResponseFields.ERROR) && body[TokenResponseFields.ERROR] === 'authorization_pending') { + callback(new Error(body[TokenResponseFields.ERROR]), body); + } + else { + callback(null, body); + } + }, + // success response callback + function (response, body) { + var tokenResponse; + try { + tokenResponse = self._handlePollingResponse(body); + } catch (e) { + self._log.error('Error validating get token response', e, true); + callback(null, e); + return; + } + + callback(null, tokenResponse); + }) + ); +}; + +OAuth2Client.prototype._createPostOption = function (postUrl, urlEncodedRequestForm) { + var postOptions = util.createRequestOptions( + this, + { + 'url' : url.format(postUrl), + body : urlEncodedRequestForm, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + followRedirect : false, + encoding : 'utf8' + } + ); + + return postOptions; +}; + +/** + * @callback GetTokenCallback + * @memberOf OAuth2Client + * @param {Error} [error] In case of an error this will hold the associated Error object. + * @param {TokenResponse} tokenResponse Contains the parsed result of a get token request. + */ + +/** +* @param {object} oauthParameters An object whose keys come from +* Constants.OAuth2.Parameters +* @param {OAuth2Client.GetTokenCallback} callback The callback function. +*/ +OAuth2Client.prototype.getToken = function(oauthParameters, callback) { + var self = this; + var tokenUrl = self._createTokenUrl(); + + var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); + + var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); + + request.post(postOptions, util.createRequestHandler('Get Token', this._log, callback, + function (response, body) { + self._handleGetTokenResponse(response, body, callback); + }) + ); +}; + +/** + * @param {object} oauthParameters An object whose keys come from + * Constants.OAuth2.Parameters + * @param {integer} refresh_interval The interval for polling request. + * @param {integer} exipres_in The timeout for polling request. + * @param {OAuth2Client.GetTokenCallback} callback The callback function. + */ +OAuth2Client.prototype.getTokenWithPolling = function(oauthParameters, refresh_interval, expires_in, callback){ + var self = this; + var maxTimesForRetry = Math.floor(expires_in / refresh_interval); + + var tokenUrl = self._createTokenUrl(); + var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); + var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); + + var optionsForRetry = {times: maxTimesForRetry, interval: refresh_interval * 1000}; + + async.retry(optionsForRetry, function(retryCallback, response) { + self._getTokenWithPolling(postOptions, retryCallback); + }, function(err, response) { + if (response && response instanceof Error) { + callback(response); + return; + } + else if (response && response.hasOwnProperty(DeviceCodeResponseParameters.ERROR)) { + callback(response); + return; + } + callback(err, response); + }); +}; + +OAuth2Client.prototype.getUserCodeInfo = function(oauthParameters, callback) { + // for now make it as a post request + var self = this; + var deviceCodeUrl = self._createDeviceCodeUrl(); + + var urlEncodedDeviceCodeRequestForm = querystring.stringify(oauthParameters); + + var postOptions = self._createPostOption(deviceCodeUrl, urlEncodedDeviceCodeRequestForm); + + request.post(postOptions, util.createRequestHandler('Get Device Code ', this._log, callback, + function (response, body) { + self._handleGetDeviceCodeResponse(response, body, callback); + }) + ); +}; + +/** + * Cancel the polling request made for acquiring token by device code. + */ +OAuth2Client.prototype.cancelPollingRequest = function() { + this._cancelPollingRequest = true; +}; + +module.exports = OAuth2Client; - _proto.currentParsed = function currentParsed() { - return this._parsed[this._parsed.length - 1]; - }; - _proto.setParsedLeapSecond = function setParsedLeapSecond() { - this.currentParsed().leapSecond = true; - }; +/***/ }), - _proto.getEffectiveChronology = function getEffectiveChronology() { - var chrono = this.currentParsed().chrono; +/***/ 60772: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (chrono == null) { - chrono = this._overrideChronology; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var jwtConstants = __nccwpck_require__(10282).Jwt; +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +__nccwpck_require__(1693); +var jws = __nccwpck_require__(4636); +var uuid = __nccwpck_require__(19744); + +/** + * JavaScript dates are in milliseconds, but JWT dates are in seconds. + * This function does the conversion. + * @param {Date} date + * @return {string} + */ +function dateGetTimeInSeconds(date) { + return Math.floor(date.getTime()/1000); +} + +/** + * Constructs a new SelfSignedJwt object. + * @param {object} callContext Context specific to this token request. + * @param {Authority} authority The authority to be used as the JWT audience. + * @param {string} clientId The client id of the calling app. + */ +function SelfSignedJwt(callContext, authority, clientId) { + this._log = new Logger('SelfSignedJwt', callContext._logContext); + this._callContext = callContext; + + this._authority = authority; + this._tokenEndpoint = authority.tokenEndpoint; + this._clientId = clientId; +} + +/** + * This wraps date creation in order to make unit testing easier. + * @return {Date} + */ +SelfSignedJwt.prototype._getDateNow = function() { + return new Date(); +}; + +SelfSignedJwt.prototype._getNewJwtId = function() { + return uuid.v4(); +}; + +/** + * A regular certificate thumbprint is a hex encode string of the binary certificate + * hash. For some reason teh x5t value in a JWT is a url save base64 encoded string + * instead. This function does the conversion. + * @param {string} thumbprint A hex encoded certificate thumbprint. + * @return {string} A url safe base64 encoded certificate thumbprint. + */ +SelfSignedJwt.prototype._createx5tValue = function(thumbprint) { + var hexString = thumbprint.replace(/:/g, '').replace(/ /g, ''); + var base64 = (new Buffer(hexString, 'hex')).toString('base64'); + return util.convertRegularToUrlSafeBase64EncodedString(base64); +}; + +/** + * Creates the JWT header. + * @param {string} thumbprint A hex encoded certificate thumbprint. + * @return {object} + */ +SelfSignedJwt.prototype._createHeader = function(thumbprint) { + var x5t = this._createx5tValue(thumbprint); + var header = { typ: 'JWT', alg: 'RS256', x5t : x5t }; + + this._log.verbose('Creating self signed JWT header'); + this._log.verbose('Creating self signed JWT header. x5t: ' + x5t, true); + + return header; +}; + +/** + * Creates the JWT payload. + * @return {object} + */ +SelfSignedJwt.prototype._createPayload = function() { + var now = this._getDateNow(); + var expires = (new Date(now.getTime())).addMinutes(jwtConstants.SELF_SIGNED_JWT_LIFETIME); + + this._log.verbose('Creating self signed JWT payload. Expires: ' + expires + ' NotBefore: ' + now); + + var jwtPayload = {}; + jwtPayload[jwtConstants.AUDIENCE] = this._tokenEndpoint; + jwtPayload[jwtConstants.ISSUER] = this._clientId; + jwtPayload[jwtConstants.SUBJECT] = this._clientId; + jwtPayload[jwtConstants.NOT_BEFORE] = dateGetTimeInSeconds(now); + jwtPayload[jwtConstants.EXPIRES_ON] = dateGetTimeInSeconds(expires); + jwtPayload[jwtConstants.JWT_ID] = this._getNewJwtId(); + + return jwtPayload; +}; + +SelfSignedJwt.prototype._throwOnInvalidJwtSignature = function(jwt) { + var jwtSegments = jwt.split('.'); + + if (3 > jwtSegments.length || !jwtSegments[2]) { + throw this._log.createError('Failed to sign JWT. This is most likely due to an invalid certificate.'); + } + + return; +}; + +SelfSignedJwt.prototype._signJwt = function(header, payload, certificate) { + var jwt; + try { + jwt = jws.sign({ header : header, payload : payload, secret : certificate }); + } + catch (err) { + this._log.error(err, true); + throw this._log.createError('Failed to sign JWT.This is most likely due to an invalid certificate.'); + } + + this._throwOnInvalidJwtSignature(jwt); + return jwt; +}; + +SelfSignedJwt.prototype._reduceThumbprint = function(thumbprint) { + var canonical = thumbprint.toLowerCase().replace(/ /g, '').replace(/:/g, ''); + this._throwOnInvalidThumbprint(canonical); + return canonical; +}; + +var numCharIn128BitHexString = 128/8*2; +var numCharIn160BitHexString = 160/8*2; +var thumbprintSizes = {}; +thumbprintSizes[numCharIn128BitHexString] = true; +thumbprintSizes[numCharIn160BitHexString] = true; +var thumbprintRegExp = /^[a-f\d]*$/; + +SelfSignedJwt.prototype._throwOnInvalidThumbprint = function(thumbprint) { + if (!thumbprintSizes[thumbprint.length] || !thumbprintRegExp.test(thumbprint)) { + throw this._log.createError('The thumbprint does not match a known format'); + } +}; + +/** + * Creates a self signed JWT that can be used as a client_assertion. + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint A hex encoded thumbprint of the certificate. + * @return {string} A self signed JWT token. + */ +SelfSignedJwt.prototype.create = function(certificate, thumbprint) { + thumbprint = this._reduceThumbprint(thumbprint); + var header = this._createHeader(thumbprint); + + var payload = this._createPayload(); + + var jwt = this._signJwt(header, payload, certificate); + return jwt; +}; + +module.exports = SelfSignedJwt; - if (chrono == null) { - chrono = IsoChronology.INSTANCE; - } - } +/***/ }), - return chrono; - }; +/***/ 21178: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return DateTimeParseContext; - }(); - - var Parsed = function (_Temporal) { - _inheritsLoose(Parsed, _Temporal); - - function Parsed(dateTimeParseContext) { - var _this; - - _this = _Temporal.call(this) || this; - _this.chrono = null; - _this.zone = null; - _this.fieldValues = new EnumMap(); - _this.leapSecond = false; - _this.dateTimeParseContext = dateTimeParseContext; - return _this; - } - - var _proto2 = Parsed.prototype; - - _proto2.copy = function copy() { - var cloned = new Parsed(); - cloned.chrono = this.chrono; - cloned.zone = this.zone; - cloned.fieldValues.putAll(this.fieldValues); - cloned.leapSecond = this.leapSecond; - cloned.dateTimeParseContext = this.dateTimeParseContext; - return cloned; - }; - - _proto2.toString = function toString() { - return this.fieldValues + ", " + this.chrono + ", " + this.zone; - }; - - _proto2.isSupported = function isSupported(field) { - return this.fieldValues.containsKey(field); - }; - - _proto2.get = function get(field) { - var val = this.fieldValues.get(field); - assert(val != null); - return val; - }; - - _proto2.query = function query(_query) { - if (_query === TemporalQueries.chronology()) { - return this.chrono; - } - - if (_query === TemporalQueries.zoneId() || _query === TemporalQueries.zone()) { - return this.zone; - } - - return _Temporal.prototype.query.call(this, _query); - }; - - _proto2.toBuilder = function toBuilder() { - var builder = new DateTimeBuilder(); - builder.fieldValues.putAll(this.fieldValues); - builder.chrono = this.dateTimeParseContext.getEffectiveChronology(); - - if (this.zone != null) { - builder.zone = this.zone; - } else { - builder.zone = this.overrideZone; - } - - builder.leapSecond = this.leapSecond; - builder.excessDays = this.excessDays; - return builder; - }; - - return Parsed; - }(Temporal); - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var DateTimePrintContext = function () { - function DateTimePrintContext(temporal, localeOrFormatter, symbols) { - if (arguments.length === 2 && arguments[1] instanceof DateTimeFormatter) { - this._temporal = DateTimePrintContext.adjust(temporal, localeOrFormatter); - this._locale = localeOrFormatter.locale(); - this._symbols = localeOrFormatter.decimalStyle(); - } else { - this._temporal = temporal; - this._locale = localeOrFormatter; - this._symbols = symbols; - } - - this._optional = 0; - } - - DateTimePrintContext.adjust = function adjust(temporal, formatter) { - return temporal; - }; - - var _proto = DateTimePrintContext.prototype; - - _proto.symbols = function symbols() { - return this._symbols; - }; - - _proto.startOptional = function startOptional() { - this._optional++; - }; - - _proto.endOptional = function endOptional() { - this._optional--; - }; - - _proto.getValueQuery = function getValueQuery(query) { - var result = this._temporal.query(query); - - if (result == null && this._optional === 0) { - throw new DateTimeException('Unable to extract value: ' + this._temporal); - } - - return result; - }; - - _proto.getValue = function getValue(field) { - try { - return this._temporal.getLong(field); - } catch (ex) { - if (ex instanceof DateTimeException && this._optional > 0) { - return null; - } - - throw ex; - } - }; - - _proto.temporal = function temporal() { - return this._temporal; - }; - - _proto.locale = function locale() { - return this._locale; - }; - - _proto.setDateTime = function setDateTime(temporal) { - this._temporal = temporal; - }; - - _proto.setLocale = function setLocale(locale) { - this._locale = locale; - }; - - return DateTimePrintContext; - }(); - - var IsoFields = {}; - var QUARTER_DAYS = [0, 90, 181, 273, 0, 91, 182, 274]; - - var Field = function (_TemporalField) { - _inheritsLoose(Field, _TemporalField); - - function Field() { - return _TemporalField.apply(this, arguments) || this; - } - - var _proto = Field.prototype; - - _proto.isDateBased = function isDateBased() { - return true; - }; - - _proto.isTimeBased = function isTimeBased() { - return false; - }; - - _proto._isIso = function _isIso() { - return true; - }; - - Field._getWeekRangeByLocalDate = function _getWeekRangeByLocalDate(date) { - var wby = Field._getWeekBasedYear(date); - - return ValueRange.of(1, Field._getWeekRangeByYear(wby)); - }; - - Field._getWeekRangeByYear = function _getWeekRangeByYear(wby) { - var date = LocalDate.of(wby, 1, 1); - - if (date.dayOfWeek() === DayOfWeek.THURSDAY || date.dayOfWeek() === DayOfWeek.WEDNESDAY && date.isLeapYear()) { - return 53; - } - - return 52; - }; - - Field._getWeek = function _getWeek(date) { - var dow0 = date.dayOfWeek().ordinal(); - var doy0 = date.dayOfYear() - 1; - var doyThu0 = doy0 + (3 - dow0); - var alignedWeek = MathUtil.intDiv(doyThu0, 7); - var firstThuDoy0 = doyThu0 - alignedWeek * 7; - var firstMonDoy0 = firstThuDoy0 - 3; - - if (firstMonDoy0 < -3) { - firstMonDoy0 += 7; - } - - if (doy0 < firstMonDoy0) { - return Field._getWeekRangeByLocalDate(date.withDayOfYear(180).minusYears(1)).maximum(); - } - - var week = MathUtil.intDiv(doy0 - firstMonDoy0, 7) + 1; - - if (week === 53) { - if ((firstMonDoy0 === -3 || firstMonDoy0 === -2 && date.isLeapYear()) === false) { - week = 1; - } - } - - return week; - }; - - Field._getWeekBasedYear = function _getWeekBasedYear(date) { - var year = date.year(); - var doy = date.dayOfYear(); - - if (doy <= 3) { - var dow = date.dayOfWeek().ordinal(); - - if (doy - dow < -2) { - year--; - } - } else if (doy >= 363) { - var _dow = date.dayOfWeek().ordinal(); - - doy = doy - 363 - (date.isLeapYear() ? 1 : 0); - - if (doy - _dow >= 0) { - year++; - } - } - - return year; - }; - - _proto.displayName = function displayName() { - return this.toString(); - }; - - _proto.resolve = function resolve() { - return null; - }; - - _proto.name = function name() { - return this.toString(); - }; - - return Field; - }(TemporalField); - - var DAY_OF_QUARTER_FIELD = function (_Field) { - _inheritsLoose(DAY_OF_QUARTER_FIELD, _Field); - - function DAY_OF_QUARTER_FIELD() { - return _Field.apply(this, arguments) || this; - } - - var _proto2 = DAY_OF_QUARTER_FIELD.prototype; - - _proto2.toString = function toString() { - return 'DayOfQuarter'; - }; - - _proto2.baseUnit = function baseUnit() { - return ChronoUnit.DAYS; - }; - - _proto2.rangeUnit = function rangeUnit() { - return QUARTER_YEARS; - }; - - _proto2.range = function range() { - return ValueRange.of(1, 90, 92); - }; - - _proto2.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.DAY_OF_YEAR) && temporal.isSupported(ChronoField.MONTH_OF_YEAR) && temporal.isSupported(ChronoField.YEAR) && this._isIso(temporal); - }; - - _proto2.rangeRefinedBy = function rangeRefinedBy(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: DayOfQuarter'); - } - - var qoy = temporal.getLong(QUARTER_OF_YEAR); - - if (qoy === 1) { - var year = temporal.getLong(ChronoField.YEAR); - return IsoChronology.isLeapYear(year) ? ValueRange.of(1, 91) : ValueRange.of(1, 90); - } else if (qoy === 2) { - return ValueRange.of(1, 91); - } else if (qoy === 3 || qoy === 4) { - return ValueRange.of(1, 92); - } - - return this.range(); - }; - - _proto2.getFrom = function getFrom(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: DayOfQuarter'); - } - - var doy = temporal.get(ChronoField.DAY_OF_YEAR); - var moy = temporal.get(ChronoField.MONTH_OF_YEAR); - var year = temporal.getLong(ChronoField.YEAR); - return doy - QUARTER_DAYS[MathUtil.intDiv(moy - 1, 3) + (IsoChronology.isLeapYear(year) ? 4 : 0)]; - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var constants = __nccwpck_require__(10282); +var CacheDriver = __nccwpck_require__(38289); +var Logger = __nccwpck_require__(92288).Logger; +var Mex = __nccwpck_require__(27078); +var OAuth2Client = __nccwpck_require__(41602); +var SelfSignedJwt = __nccwpck_require__(60772); +var UserRealm = __nccwpck_require__(58663); +var WSTrustRequest = __nccwpck_require__(39035); + +var OAuth2Parameters = constants.OAuth2.Parameters; +var TokenResponseFields = constants.TokenResponseFields; +var OAuth2GrantType = constants.OAuth2.GrantType; +var OAuth2Scope = constants.OAuth2.Scope; +var Saml = constants.Saml; +var AccountType = constants.UserRealm.AccountType; +var WSTrustVersion = constants.WSTrustVersion; +var DeviceCodeResponseParameters = constants.UserCodeResponseFields; + +/** + * Constructs a new TokenRequest object. + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {AuthenticationContext} authenticationContext + * @param {string} resource + * @param {string} clientId + * @param {string} redirectUri + */ +function TokenRequest(callContext, authenticationContext, clientId, resource, redirectUri) { + this._log = new Logger('TokenRequest', callContext._logContext); + this._callContext = callContext; + this._authenticationContext = authenticationContext; + this._resource = resource; + this._clientId = clientId; + this._redirectUri = redirectUri; + + // This should be set at the beginning of getToken + // functions that have a userId. + this._userId = null; + + this._userRealm = null; + this._pollingClient = {}; +} + +TokenRequest.prototype._createUserRealmRequest = function(username) { + return new UserRealm(this._callContext, username, this._authenticationContext.authority); +}; + +TokenRequest.prototype._createMex = function(mexEndpoint) { + return new Mex(this._callContext, mexEndpoint); +}; + +TokenRequest.prototype._createWSTrustRequest = function(wstrustEndpoint, appliesTo, wstrustEndpointVersion) { + return new WSTrustRequest(this._callContext, wstrustEndpoint, appliesTo, wstrustEndpointVersion); +}; + +TokenRequest.prototype._createOAuth2Client = function() { + return new OAuth2Client(this._callContext, this._authenticationContext._authority); +}; + +TokenRequest.prototype._createSelfSignedJwt = function() { + return new SelfSignedJwt(this._callContext, this._authenticationContext._authority, this._clientId); +}; + +TokenRequest.prototype._oauthGetToken = function(oauthParameters, callback) { + var client = this._createOAuth2Client(); + client.getToken(oauthParameters, callback); +}; + +TokenRequest.prototype._oauthGetTokenByPolling = function(oauthParameters, refresh_interval, expires_in, callback){ + var client = this._createOAuth2Client(); + client.getTokenWithPolling(oauthParameters, refresh_interval, expires_in, callback); + this._pollingClient = client; +} + +TokenRequest.prototype._createCacheDriver = function() { + return new CacheDriver( + this._callContext, + this._authenticationContext.authority, + this._resource, + this._clientId, + this._authenticationContext.cache, + this._getTokenWithTokenResponse.bind(this) + ); +}; + +/** + * Used by the cache driver to refresh tokens. + * @param {TokenResponse} entry A token response to refresh. + * @param {string} resource The resource for which to get the token. + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype._getTokenWithTokenResponse = function(entry, resource, callback) { + this._log.verbose('Called to refresh a token from the cache.'); + var refreshToken = entry[TokenResponseFields.REFRESH_TOKEN]; + this._getTokenWithRefreshToken(refreshToken, resource, null, callback); +}; + +TokenRequest.prototype._createCacheQuery = function() { + var query = { + clientId : this._clientId + }; + + if (this._userId) { + query.userId = this._userId; + } else { + this._log.verbose('No userId passed for cache query.'); + } + + return query; +}; + + +TokenRequest.prototype._getTokenWithCacheWrapper = function(callback, getTokenFunc) { + var self = this; + this._cacheDriver = this._createCacheDriver(); + var cacheQuery = this._createCacheQuery(); + this._cacheDriver.find(cacheQuery, function(err, token) { + if (err) { + self._log.warn('Attempt to look for token in cahce resulted in Error'); + self._log.warn('Attempt to look for token in cache resulted in Error: ' + err.stack, true); + } + + if (!token) { + self._log.verbose('No appropriate cached token found.'); + getTokenFunc.call(self, function(err, tokenResponse) { + if (err) { + self._log.verbose('getTokenFunc returned with err'); + callback(err, tokenResponse); + return; + } + + self._log.verbose('Successfully retrieved token from authority'); + self._cacheDriver.add(tokenResponse, function() { + callback(null, tokenResponse); + }); + }); + } else { + self._log.info('Returning cached token.'); + callback(err, token); + } + }); +}; + +/** + * Store token into cache. + * @param {object} tokenResponse Token response to be added into the cache. + */ +TokenRequest.prototype._addTokenIntoCache = function(tokenResponse, callback) { + this._cacheDriver = this._createCacheDriver(); + this._log.verbose('Storing retrieved token into cache'); + this._cacheDriver.add(tokenResponse, function(err) { + callback(err, tokenResponse); + }); +}; + +/** + * Adds an OAuth parameter to the paramters object if the parameter is + * not null or undefined. + * @private + * @param {object} parameters OAuth parameters object. + * @param {string} key A member of the OAuth2Parameters constants. + * @param {object} value + */ +function _addParameterIfAvailable(parameters, key, value) { + if (value) { + parameters[key] = value; + } +} + +/** + * Creates a set of basic, common, OAuthParameters based on values that the TokenRequest + * was created with. + * @private + * @param {string} grantType A member of the OAuth2GrantType constants. + * @return {object} + */ +TokenRequest.prototype._createOAuthParameters = function(grantType) { + var oauthParameters = {}; + oauthParameters[OAuth2Parameters.GRANT_TYPE] = grantType; + + if (OAuth2GrantType.AUTHORIZATION_CODE !== grantType && + OAuth2GrantType.CLIENT_CREDENTIALS !== grantType && + OAuth2GrantType.DEVICE_CODE != grantType) { + oauthParameters[OAuth2Parameters.SCOPE] = OAuth2Scope.OPENID; + } + + _addParameterIfAvailable(oauthParameters, OAuth2Parameters.CLIENT_ID, this._clientId); + _addParameterIfAvailable(oauthParameters, OAuth2Parameters.RESOURCE, this._resource); + _addParameterIfAvailable(oauthParameters, OAuth2Parameters.REDIRECT_URI, this._redirectUri); + + return oauthParameters; +}; + +/** + * Get's a token from AAD using a username and password + * @private + * @param {string} username + * @param {string} password + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype._getTokenUsernamePasswordManaged = function(username, password, callback) { + this._log.verbose('Acquiring token with username password for managed user'); + + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.PASSWORD); + + oauthParameters[OAuth2Parameters.PASSWORD] = password; + oauthParameters[OAuth2Parameters.USERNAME] = username; + + this._oauthGetToken(oauthParameters, callback); +}; + +/** + * Determines the OAuth SAML grant type to use based on the passed in TokenType + * that was returned from a RSTR. + * @param {string} wstrustResponse RSTR token type. + * @return {string} An OAuth grant type. + */ +TokenRequest.prototype._getSamlGrantType = function(wstrustResponse) { + var tokenType = wstrustResponse.tokenType; + switch (tokenType) { + case Saml.TokenTypeV1: + return OAuth2GrantType.SAML1; + case Saml.TokenTypeV2: + return OAuth2GrantType.SAML2; + default: + throw this._log.createError('RSTR returned unknown token type: ' + tokenType); + } +}; + +/** + * Performs an OAuth SAML Assertion grant type exchange. Uses a SAML token as the credential for getting + * an OAuth access token. + * @param {WSTrustResponse} wstrustResponse A response from a WSTrustRequest + * @param {AcquireTokenCallback} callback callback + */ +TokenRequest.prototype._performWSTrustAssertionOAuthExchange = function(wstrustResponse, callback) { + this._log.verbose('Performing OAuth assertion grant type exchange.'); + + var oauthParameters; + try { + var grantType = this._getSamlGrantType(wstrustResponse); + var assertion = new Buffer(wstrustResponse.token).toString('base64'); + oauthParameters = this._createOAuthParameters(grantType); + oauthParameters[OAuth2Parameters.ASSERTION] = assertion; + } catch (err) { + callback(err); + return; + } + + this._oauthGetToken(oauthParameters, callback); +}; + +/** + * Exchange a username and password for a SAML token from an ADFS instance via WSTrust. + * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint. + * @param {string} wstrustEndpointVersion The version of the wstrust endpoint. + * @param {string} username username + * @param {string} password password + * @param {AcquireTokenCallback} callback callback + */ +TokenRequest.prototype._performWSTrustExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) { + var self = this; + var wstrust = this._createWSTrustRequest(wstrustEndpoint, 'urn:federation:MicrosoftOnline', wstrustEndpointVersion); + wstrust.acquireToken(username, password, function(rstErr, response) { + if (rstErr) { + callback(rstErr); + return; + } + + if (!response.token) { + var rstrErr = self._log.createError('Unsucessful RSTR.\n\terror code: ' + response.errorCode + '\n\tfaultMessage: ' + response.faultMessage, true); + callback(rstrErr); + return; + } + + callback(null, response); + }); +}; + +/** + * Given a username and password this method invokes a WSTrust and OAuth exchange to get an access token. + * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint. + * @param {string} username username + * @param {string} password password + * @param {AcquireTokenCallback} callback callback + */ +TokenRequest.prototype._performUsernamePasswordForAccessTokenExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) { + var self = this; + this._performWSTrustExchange(wstrustEndpoint, wstrustEndpointVersion, username, password, function(err, wstrustResponse) { + if (err) { + callback(err); + return; + } + + self._performWSTrustAssertionOAuthExchange(wstrustResponse, callback); + }); +}; + +/** + * Returns an Error object indicating that AAD did not return a WSTrust endpoint. + * @return {Error} + */ +TokenRequest.prototype._createADWSTrustEndpointError = function() { + return this._log.createError('AAD did not return a WSTrust endpoint. Unable to proceed.'); +}; + +/** + * Gets an OAuth access token using a username and password via a federated ADFS instance. + * @param {string} username username + * @param {string} password password + * @param {AcquireTokenCallback} callback callback + */ +TokenRequest.prototype._getTokenUsernamePasswordFederated = function(username, password, callback) { + this._log.verbose('Acquiring token with username password for federated user'); + + var self = this; + if (!this._userRealm.federationMetadataUrl) { + this._log.warn('Unable to retrieve federationMetadataUrl from AAD. Attempting fallback to AAD supplied endpoint.'); + + if (!this._userRealm.federationActiveAuthUrl) { + callback(this._createADWSTrustEndpointError()); + return; + } + + var wstrustVersion = this._parseWStrustVersionFromFederationActiveAuthUrl(this._userRealm.federationActiveAuthUrl); + this._log.verbose('Wstrust endpoint version is: ' + wstrustVersion); + this._performUsernamePasswordForAccessTokenExchange(this._userRealm.federationActiveAuthUrl, wstrustVersion, username, password, callback); + return; + } else { + var mexEndpoint = this._userRealm.federationMetadataUrl; + this._log.verbose('Attempting mex'); + this._log.verbose('Attempting mex at: ' + mexEndpoint, true); + var mex = this._createMex(mexEndpoint); + mex.discover(function(mexErr) { + var wstrustEndpoint; + wstrustVersion = WSTrustVersion.UNDEFINED; + if (mexErr) { + self._log.warn('MEX exchange failed. Attempting fallback to AAD supplied endpoint.'); + + wstrustEndpoint = self._userRealm.federationActiveAuthUrl; + wstrustVersion = self._parseWStrustVersionFromFederationActiveAuthUrl(self._userRealm.federationActiveAuthUrl); + if (!wstrustEndpoint) { + callback(self._createADWSTrustEndpointError()); + return; + } + } else { + wstrustEndpoint = mex.usernamePasswordPolicy.url; + wstrustVersion = mex.usernamePasswordPolicy.version; + } + + self._performUsernamePasswordForAccessTokenExchange(wstrustEndpoint, wstrustVersion, username, password, callback); + return; + }); + } +}; + +/** + * Gets wstrust endpoint version from the federation active auth url. + * @private + * @param {string} federationActiveAuthUrl federationActiveAuthUrl + * @return {object} The wstrust endpoint version. + */ +TokenRequest.prototype._parseWStrustVersionFromFederationActiveAuthUrl = function(federationActiveAuthUrl) { + var wstrust2005Regex = /[/trust]?[2005][/usernamemixed]?/; + var wstrust13Regex = /[/trust]?[13][/usernamemixed]?/; + + if (wstrust2005Regex.exec(federationActiveAuthUrl)) { + return WSTrustVersion.WSTRUST2005; + } + else if (wstrust13Regex.exec(federationActiveAuthUrl)) { + return WSTrustVersion.WSTRUST13; + } + + return WSTrustVersion.UNDEFINED; +}; + +/** + * Decides whether the username represents a managed or a federated user and then + * obtains a token using the appropriate protocol flow. + * @private + * @param {string} username + * @param {string} password + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithUsernamePassword = function(username, password, callback) { + this._log.info('Acquiring token with username password'); + this._userId = username; + + this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { + var self = this; + + if(this._authenticationContext._authority._isAdfsAuthority) { + this._log.info('Skipping user realm discovery for ADFS authority'); + + self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback); + return; + } + + this._userRealm = this._createUserRealmRequest(username); + this._userRealm.discover(function(err) { + if (err) { + getTokenCompleteCallback(err); + return; + } + + switch(self._userRealm.accountType) { + case AccountType.Managed: + self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback); + return; + case AccountType.Federated: + self._getTokenUsernamePasswordFederated(username, password, getTokenCompleteCallback); + return; + default: + getTokenCompleteCallback(self._log.createError('Server returned an unknown AccountType: ' + self._userRealm.AccountType)); + } + }); + }); +}; + +/** + * Obtains a token using client credentials + * @private + * @param {string} clientSecret + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithClientCredentials = function(clientSecret, callback) { + this._log.info('Getting token with client credentials.'); + + this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS); + + oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; + + this._oauthGetToken(oauthParameters, getTokenCompleteCallback); + }); +}; + +/** + * Obtains a token using an authorization code. + * @private + * @param {string} authorizationCode + * @param {string} clientSecret + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithAuthorizationCode = function(authorizationCode, clientSecret, callback) { + this._log.info('Getting token with auth code.'); + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.AUTHORIZATION_CODE); + + oauthParameters[OAuth2Parameters.CODE] = authorizationCode; + oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; + + this._oauthGetToken(oauthParameters, callback); +}; + +/** + * Obtains a token using a refresh token. + * @param {string} refreshToken + * @param {string} resource + * @param {string} [clientSecret] + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype._getTokenWithRefreshToken = function(refreshToken, resource, clientSecret, callback) { + this._log.info('Getting a new token from a refresh token.'); + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.REFRESH_TOKEN); + + if (resource) { + oauthParameters[OAuth2Parameters.RESOURCE] = resource; + } + + if (clientSecret) { + oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; + } + + oauthParameters[OAuth2Parameters.REFRESH_TOKEN] = refreshToken; + + this._oauthGetToken(oauthParameters, callback); +}; + +/** + * Obtains a token using a refresh token. + * @param {string} refreshToken + * @param {string} [clientSecret] + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithRefreshToken = function(refreshToken, clientSecret, callback) { + this._getTokenWithRefreshToken(refreshToken, null, clientSecret, callback); +}; + +/** + * Obtains a token from the cache, refreshing it or using a MRRT if necessary. + * @param {string} [userId] The user associated with the cached token. + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenFromCacheWithRefresh = function(userId, callback) { + var self = this; + this._log.info('Getting token from cache with refresh if necessary.'); + + this._userId = userId; + this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { + // If this method was called then no cached entry was found. Since + // this particular version of acquireToken can only retrieve tokens + // from the cache, return an error. + getTokenCompleteCallback(self._log.createError('Entry not found in cache.')); + }); +}; + +/** + * Creates a self signed jwt. + * @param {string} authorityUrl + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint + * @return {string} A self signed JWT + */ +TokenRequest.prototype._createJwt = function(authorityUrl, certificate, thumbprint) { + var jwt; + var ssj = this._createSelfSignedJwt(); + jwt = ssj.create(certificate, thumbprint); + if (!jwt) { + throw this._log.createError('Failed to create JWT'); + } + + return jwt; +}; + +/** + * Obtains a token via a certificate. The certificate is used to generate a self signed + * JWT token that is passed as a client_assertion. + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint A hex encoded thumbprint of the certificate. + * @param {AcquireTokenCallback} callback + */ +TokenRequest.prototype.getTokenWithCertificate = function(certificate, thumbprint, callback) { + + this._log.info('Getting a token via certificate.'); + + var authorityUrl = this._authenticationContext._authority; + + var jwt; + try { + jwt = this._createJwt(authorityUrl, certificate, thumbprint); + } catch (err) { + callback(err); + return; + } + + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS); + oauthParameters[OAuth2Parameters.CLIENT_ASSERTION_TYPE] = OAuth2GrantType.JWT_BEARER; + oauthParameters[OAuth2Parameters.CLIENT_ASSERTION] = jwt; + + this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { + this._oauthGetToken(oauthParameters, getTokenCompleteCallback); + }); +}; + +TokenRequest.prototype.getTokenWithDeviceCode = function(userCodeInfo, callback) { + this._log.info('Getting a token via device code'); + var self = this; + + var oauthParameters = this._createOAuthParameters(OAuth2GrantType.DEVICE_CODE); + oauthParameters[OAuth2Parameters.CODE] = userCodeInfo[DeviceCodeResponseParameters.DEVICE_CODE]; + + var interval = userCodeInfo[DeviceCodeResponseParameters.INTERVAL]; + var expires_in = userCodeInfo[DeviceCodeResponseParameters.EXPIRES_IN]; + + if (interval <= 0) { + callback(new Error('invalid refresh interval')); + } + + this._oauthGetTokenByPolling(oauthParameters, interval, expires_in, function(err, tokenResponse) { + if (err) { + self._log.verbose('Token polling request returend with err.'); + callback(err, tokenResponse); + } + else { + self._addTokenIntoCache(tokenResponse, callback); + } + }); +}; + +TokenRequest.prototype.cancelTokenRequestWithDeviceCode = function() { + this._pollingClient.cancelPollingRequest(); +}; + +module.exports = TokenRequest; - _proto2.adjustInto = function adjustInto(temporal, newValue) { - var curValue = this.getFrom(temporal); - this.range().checkValidValue(newValue, this); - return temporal.with(ChronoField.DAY_OF_YEAR, temporal.getLong(ChronoField.DAY_OF_YEAR) + (newValue - curValue)); - }; - _proto2.resolve = function resolve(fieldValues, partialTemporal, resolverStyle) { - var yearLong = fieldValues.get(ChronoField.YEAR); - var qoyLong = fieldValues.get(QUARTER_OF_YEAR); +/***/ }), - if (yearLong == null || qoyLong == null) { - return null; - } +/***/ 58663: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var y = ChronoField.YEAR.checkValidIntValue(yearLong); - var doq = fieldValues.get(DAY_OF_QUARTER); - var date; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var querystring = __nccwpck_require__(71191); +var request = __nccwpck_require__(48699); +var _ = __nccwpck_require__(83571); +var url = __nccwpck_require__(78835); + +var constants = __nccwpck_require__(10282); +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); + +var AccountType = constants.UserRealm.AccountType; +var FederationProtocolType = constants.UserRealm.FederationProtocolType; + +var USER_REALM_PATH_TEMPLATE = 'common/UserRealm/'; + +/** + * Create a new UserRealm object + * @private + * @constructor + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} userPrinciple The username for which a realm needs to be discovered. + * @param {string} authority The string url of the authority that owns the userPrinciple. + */ +function UserRealm(callContext, userPrinciple, authority) { + this._log = new Logger('UserRealm', callContext._logContext); + this._callContext = callContext; + this._apiVersion = '1.0'; + this._federationProtocol = null; + this._accountType = null; + this._federationMetadataUrl = null; + this._federationActiveAuthUrl = null; + this._userPrinciple = userPrinciple; + this._authority = authority; +} + +/** +* The API version requested by UserRealm. +* @type {string} +* @instance +* @memberOf UserRealm +* @name apiVersion +*/ +Object.defineProperty(UserRealm.prototype, 'apiVersion', { + get : function() { + return this._apiVersion; + } +}); + +/** +* The federation protocol used by the users realm. +* @type {string} +* @instance +* @memberOf UserRealm +* @name federationProtocol +*/ +Object.defineProperty(UserRealm.prototype, 'federationProtocol', { + get : function() { + return this._federationProtocol; + } +}); + +/** +* The Type of account. Either managed or federated. +* @type {string} +* @instance +* @memberOf UserRealm +* @name accountType +*/ +Object.defineProperty(UserRealm.prototype, 'accountType', { + get : function() { + return this._accountType; + } +}); + +/** +* If this is a federated account then this property will contain the mex url. +* @type {string} +* @instance +* @memberOf UserRealm +* @name federationsMetadataUrl +*/ +Object.defineProperty(UserRealm.prototype, 'federationMetadataUrl', { + get : function() { + return this._federationMetadataUrl; + } +}); + +/** +* If the account is federated this will contain the authentication endpoint. +* @type {string} +* @instance +* @memberOf UserRealm +* @name federationActiveAuthUrl +*/ +Object.defineProperty(UserRealm.prototype, 'federationActiveAuthUrl', { + get : function() { + return this._federationActiveAuthUrl; + } +}); + +/** +* Given the authority url this method constructs a full user realm discovery url. +* @private +* @returns A full user realm discovery url including path and query string. +*/ +UserRealm.prototype._getUserRealmUrl = function() { + var userRealmUrl = util.copyUrl(this._authority); + var urlEncodedUser = encodeURIComponent(this._userPrinciple); + userRealmUrl.pathname = USER_REALM_PATH_TEMPLATE.replace('', urlEncodedUser); + + var userRealmQuery = { + 'api-version' : this._apiVersion + }; + + userRealmUrl.search = querystring.stringify(userRealmQuery); + + userRealmUrl = util.copyUrl(userRealmUrl); + + return userRealmUrl; +}; + +/** +* Given a constants object and a value, validates that the value is a key in the constants object. +* @private +* @param {object} constants An object containing constant key value pairs. +* @param {string} value A value to check against the constants +* @param {bool} caseSensitive set to true if comparisons should be made as case sensitive. Defaults to false. +* @returns {bool|string} If value passed in matches one of the constants then the return value is the matched constant. +* If a non case sensitive match was done, then the value returned may be different than the value +* passed in. If there is no match then the method returns false. +*/ +UserRealm.prototype._validateConstantValue = function(constants, value, caseSensitive) { + if (!value) { + return false; + } + if (!caseSensitive) { + value = value.toLowerCase(); + } + return _.contains(_.values(constants), value) ? value : false; +}; + +/** +* Checks whether an account type string is valid. +* @private +* @param {string} type An account type string. +* @returns {bool} +*/ +UserRealm.prototype._validateAccountType = function(type) { + return this._validateConstantValue(AccountType, type); +}; + +/** +* Checks whether a federation protocol string is valid. +* @private +* @param {string} protocol A federation protocol string. +* @returns {bool} +*/ +UserRealm.prototype._validateFederationProtocol = function(protocol) { + return this._validateConstantValue(FederationProtocolType, protocol); +}; + +/** +* Logs the values parsed as part of user realm discovery. +* @private +*/ +UserRealm.prototype._logParsedResponse = function() { + this._log.verbose('UserRealm response:'); + this._log.verbose(' AccountType: ' + this.accountType); + this._log.verbose(' FederationProtocol: ' + this.federationProtocol); + this._log.verbose(' FederationMetatdataUrl: ' + this.federationMetadataUrl, true); + this._log.verbose(' FederationActiveAuthUrl: ' + this.federationActiveAuthUrl, true); +}; + +/** +* Parses the response from a user realm discovery request. +* @private +* @param {string} body The body returned as part of the http user realm discovery request. +* @param {UserRealm.DiscoverCallback} callback Called when parsing is complete. +*/ +UserRealm.prototype._parseDiscoveryResponse = function(body, callback) { + this._log.verbose('Discovery response:\n' + body, true); + + var response; + try { + response = JSON.parse(body); + } catch (err) { + callback(this._log.createError('Parsing realm discovery respone JSON failed: ' + body, true)); + return; + } + + var accountType = this._validateAccountType(response['account_type']); + if (!accountType) { + callback(this._log.createError('Cannot parse account_type: ' + accountType)); + return; + } + + this._accountType = accountType; + + if (this._accountType === AccountType.Federated) { + var protocol = this._validateFederationProtocol(response['federation_protocol']); + + if (!protocol) { + callback(this._log.createError('Cannot parse federation protocol: ' + protocol)); + return; + } + + this._federationProtocol = protocol; + this._federationMetadataUrl = response['federation_metadata_url']; + this._federationActiveAuthUrl = response['federation_active_auth_url']; + } + + this._logParsedResponse(); + callback(); +}; + +/** +* @callback DiscoverCallback +* @memberOf UserRealm +* @param {Error} error If an error occurs during discovery then this parameter will be used to return the error. +*/ + +/** +* Performs user realm discovery and fills in the properties on this object. +* @private +* @param {UserRealm.DiscoverCallback} callback Called when discovery is complete. +*/ +UserRealm.prototype.discover = function(callback) { + var self = this; + var options = util.createRequestOptions( + this, + { + headers : { + Accept : 'application/json' + } + } + ); + + var userRealmUrl = this._getUserRealmUrl(); + this._log.verbose('Performing user realm discovery at: ' + url.format(userRealmUrl), true); + request.get(userRealmUrl, options, util.createRequestHandler('User Realm Discovery', this._log, callback, + function(response, body) { + self._parseDiscoveryResponse(body, callback); + }) + ); +}; + +module.exports = UserRealm; - if (resolverStyle === ResolverStyle.LENIENT) { - var qoy = qoyLong; - date = LocalDate.of(y, 1, 1); - date = date.plusMonths(MathUtil.safeMultiply(MathUtil.safeSubtract(qoy, 1), 3)); - date = date.plusDays(MathUtil.safeSubtract(doq, 1)); - } else { - var _qoy = QUARTER_OF_YEAR.range().checkValidIntValue(qoyLong, QUARTER_OF_YEAR); +/***/ }), - if (resolverStyle === ResolverStyle.STRICT) { - var max = 92; +/***/ 5336: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (_qoy === 1) { - max = IsoChronology.isLeapYear(y) ? 91 : 90; - } else if (_qoy === 2) { - max = 91; - } +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +var adalIdConstants = __nccwpck_require__(10282).AdalIdParameters; +var os = __nccwpck_require__(12087); +var url = __nccwpck_require__(78835); + +var ADAL_VERSION; + +/** + * @namespace Util + * @private + */ + +function loadAdalVersion() { + ADAL_VERSION = __nccwpck_require__(93700)/* .version */ .i8; +} + +function adalInit() { + loadAdalVersion(); +} + +/** + * @static + * @memberOf Util + * @param {string|int} statusCode An HTTP status code. + */ +function isHttpSuccess(statusCode) { + return statusCode >= 200 && statusCode < 300; +} + +function addDefaultRequestHeaders (self, options) { + if (!options.headers) { + options.headers = {}; + } + var headers = options.headers; + if (!headers['Accept-Charset']) { + headers['Accept-Charset'] = 'utf-8'; + } + headers['client-request-id'] = self._callContext._logContext.correlationId; + headers['return-client-request-id'] = 'true'; + + // ADAL Id headers + headers[adalIdConstants.SKU] = adalIdConstants.NODE_SKU; + headers[adalIdConstants.VERSION] = ADAL_VERSION; + headers[adalIdConstants.OS] = os.platform(); + headers[adalIdConstants.CPU] = os.arch(); +} + +/** +* Central place for housing default request options. This is a place holder +* for when SSL validation is implemented an all requests are subject to that +* policy. +* @static +* @memberOf Util +* @param {object} options A set of options that will be merged with teh default options +* These will override any default options. +* @returns {object} Returns the merged options. +*/ +function createRequestOptions(self, options) { + var defaultOptions = {}; //{ strictSSL : true }; + var mergedOptions = defaultOptions; + if (options) { + _.extend(mergedOptions, options); + } + if (self._callContext.options && self._callContext.options.http) { + _.extend(mergedOptions, self._callContext.options.http); + } + + addDefaultRequestHeaders(self, mergedOptions); + return mergedOptions; +} + +function logReturnCorrelationId(log, operationMessage, response) { + if (response && response.headers && response.headers['client-request-id']) { + log.info(operationMessage + 'Server returned this correlationId: ' + response.headers['client-request-id'], true); + } +} + +/** +* Creates a function that can be used as the callback for http request operations. This is meant +* to centralize error handling in one place. +* @static +* @memberOf Util +* @param {string} operationMessage A message to be prepended to logged error strings. This should be something like 'Mex Request' +* and summarize the purpose of the http request. +* @param {object} log A Logger object being used by the calling component. +* @param {Util.CreateRequestHandlerErrorCallback} errorCallback Called in the event of an error. +* @param {Util.CreateRequestHandlerSuccessCallabck} successCallback Called on successfull completion of the request. +*/ +function createRequestHandler(operationMessage, log, errorCallback, successCallback) { + return function(err, response, body) { + logReturnCorrelationId(log, operationMessage, response); + if (err) { + log.error(operationMessage + ' request failed with', err, true); + errorCallback(err); + return; + } + if (!isHttpSuccess(response.statusCode)) { + var returnErrorString = operationMessage + ' request returned http error: ' + response.statusCode; + var errorResponse; + if (body) { + returnErrorString += ' and server response: ' + body; + try { + errorResponse = JSON.parse(body); + } catch (e) { + // No problem if it doesn't parse. + } + } + errorCallback(log.createError(returnErrorString, true), errorResponse); + return; + } + + successCallback(response, body); + }; +} + +/** +* @callback CreateRequestHandlerErrorCallback +* @memberOf Util +* @param {Error} error An error object. +*/ + +/** +* @callback CreateRequestHandlerSuccessCallabck +* @memberOf Util +* @param {object} response The response object returned from request. +* @param {string} body The body of the http response. +*/ + +/** +* Deep copies a url object. +* @static +* @memberOf Util +* @param {URL} urlSource The source url object to copy. +* @returns {URL} A deep copy of sourceUrl. +*/ +function copyUrl(urlSource) { + return url.parse(url.format(urlSource)); +} + +function convertUrlSafeToRegularBase64EncodedString(str) { + return str.replace(/-/g, '+').replace(/_/g, '/'); +} + +function convertRegularToUrlSafeBase64EncodedString(str) { + return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +} + +function base64DecodeStringUrlSafe(str) { + var base64 = convertUrlSafeToRegularBase64EncodedString(str); + return (new Buffer(base64, 'base64')).toString('utf8'); +} + +function base64EncodeStringUrlSafe(str) { + var base64 = (new Buffer(str, 'utf8').toString('base64')); + var converted = convertRegularToUrlSafeBase64EncodedString(base64); + return converted; +} + +module.exports.adalInit = adalInit; +module.exports.isHttpSuccess = isHttpSuccess; +module.exports.createRequestHandler = createRequestHandler; +module.exports.createRequestOptions = createRequestOptions; +module.exports.copyUrl = copyUrl; +module.exports.base64DecodeStringUrlSafe = base64DecodeStringUrlSafe; +module.exports.base64EncodeStringUrlSafe = base64EncodeStringUrlSafe; +module.exports.convertRegularToUrlSafeBase64EncodedString = convertRegularToUrlSafeBase64EncodedString; - ValueRange.of(1, max).checkValidValue(doq, this); - } else { - this.range().checkValidValue(doq, this); - } +/***/ }), - date = LocalDate.of(y, (_qoy - 1) * 3 + 1, 1).plusDays(doq - 1); - } +/***/ 39035: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - fieldValues.remove(this); - fieldValues.remove(ChronoField.YEAR); - fieldValues.remove(QUARTER_OF_YEAR); - return date; - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var request = __nccwpck_require__(48699); +var uuid = __nccwpck_require__(19744); + +var Logger = __nccwpck_require__(92288).Logger; +var util = __nccwpck_require__(5336); +var WSTrustResponse = __nccwpck_require__(55927); +var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; + +var USERNAME_PLACEHOLDER = '{UsernamePlaceHolder}'; +var PASSWORD_PLACEHOLDER = '{PasswordPlaceHolder}'; + +/** + * Creates a new instance of WSTrustRequest + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} wstrustEndpointUrl An STS WS-Trust soap endpoint. + * @param {string} appliesTo A URI that identifies a service for which the a token is to be obtained. + */ +function WSTrustRequest(callContext, wstrustEndpointUrl, appliesTo, wstrustEndpointVersion) { + this._log = new Logger('WSTrustRequest', callContext._logContext); + this._callContext = callContext; + this._wstrustEndpointUrl = wstrustEndpointUrl; + this._appliesTo = appliesTo; + this._wstrustEndpointVersion = wstrustEndpointVersion; +} + +/** +* Given a Date object adds the minutes parameter and returns a new Date object. +* @private +* @static +* @memberOf WSTrustRequest +* @param {Date} date A Date object. +* @param {Number} minutes The number of minutes to add to the date parameter. +* @returns {Date} Returns a Date object. +*/ +function _datePlusMinutes(date, minutes) { + var minutesInMilliSeconds = minutes * 60 * 1000; + var epochTime = date.getTime() + minutesInMilliSeconds; + return new Date(epochTime); +} + +/** + * Builds the soap security header for the RST message. + * @private + * @param {string} username A username + * @param {string} password The passowrd that corresponds to the username parameter. + * @returns {string} A string that contains the soap security header. + */ +WSTrustRequest.prototype._buildSecurityHeader = function() { + var timeNow = new Date(); + var expireTime = _datePlusMinutes(timeNow, 10); + var timeNowString = timeNow.toISOString(); + var expireTimeString = expireTime.toISOString(); + + var securityHeaderXml = + '\ + \ + ' + timeNowString + '\ + ' + expireTimeString + '\ + \ + \ + ' + USERNAME_PLACEHOLDER + '\ + ' + PASSWORD_PLACEHOLDER + '\ + \ + '; + + return securityHeaderXml; +}; + +/** + * Replaces the placeholders in the RST template with the actual username and password values. + * @private + * @param {string} RSTTemplate An RST with placeholders for username and password. + * @param {string} username A username + * @param {string} password The passowrd that corresponds to the username parameter. + * @returns {string} A string containing a complete RST soap message. + */ + +WSTrustRequest.prototype._populateRSTUsernamePassword = function(RSTTemplate, username, password) { + var RST = RSTTemplate.replace(USERNAME_PLACEHOLDER, username).replace(PASSWORD_PLACEHOLDER, this._populatedEscapedPassword(password)); + return RST; +}; + +/** + * Escape xml characters in password. + * @private + * @param {string} password The password to be excaped with xml charaters. + */ +WSTrustRequest.prototype._populatedEscapedPassword = function (password) { + var escapedPassword = password; + return escapedPassword.replace(/&/g, '&') + .replace(/"/g, '"') + .replace(/'/g, ''') + .replace(//g, '>'); +} + +/** + * Builds a WS-Trust RequestSecurityToken (RST) message using username password authentication. + * @private + * @param {string} username A username + * @param {string} password The passowrd that corresponds to the username parameter. + * @returns {string} A string containing a complete RST soap message. + */ +WSTrustRequest.prototype._buildRST = function(username, password) { + var messageID = uuid.v4(); + + // Create a template RST with placeholders for the username and password so the + // the RST can be logged without the sensitive information. + var schemaLocation = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'; + var soapAction = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; + var rstTrustNamespace = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512'; + var keyType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer'; + var requestType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue'; + + if (this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005) { + soapAction = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'; + rstTrustNamespace = 'http://schemas.xmlsoap.org/ws/2005/02/trust'; + keyType = 'http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey'; + requestType = 'http://schemas.xmlsoap.org/ws/2005/02/trust/Issue'; + } + + var RSTTemplate = + '\ + \ + ' + soapAction + '\ + urn:uuid:' + messageID + '\ + \ + http://www.w3.org/2005/08/addressing/anonymous\ + \ + ' + this._wstrustEndpointUrl + '\ + ' + this._buildSecurityHeader() + '\ + \ + \ + \ + \ + \ + ' + this._appliesTo + '\ + \ + \ + ' + keyType + '\ + ' + requestType + '\ + \ + \ + '; + + this._log.verbose('Created RST: \n' + RSTTemplate, true); + + var RST = this._populateRSTUsernamePassword(RSTTemplate, username, password); + return RST; +}; + +/** + * Handles the processing of a RSTR + * @private + * @param {string} body + * @param {WSTrustRequest.AcquireTokenCallback} callback + */ +WSTrustRequest.prototype._handleRSTR = function(body, callback) { + var err; + + var wstrustResponse = new WSTrustResponse(this._callContext, body, this._wstrustEndpointVersion); + try { + wstrustResponse.parse(); + } catch (error) { + err = error; + } + + callback(err, wstrustResponse); +}; + +/** + * Performs a WS-Trust RequestSecurityToken request to obtain a federated token in exchange for a username password. + * @param {string} username A username + * @param {string} password The passowrd that corresponds to the username parameter. + * @param {WSTrustRequest.AcquireTokenCallback} callback Called once the federated token has been retrieved or on error. +*/ +WSTrustRequest.prototype.acquireToken = function(username, password, callback) { + if (this._wstrustEndpointVersion === WSTrustVersion.UNDEFINED) { + var err = this._log.createError('Unsupported wstrust endpoint version. Current support version is wstrust2005 or wstrust13.'); + callback(err); + return; + } + + var self = this; + var RST = this._buildRST(username, password); + + var soapAction = this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005 ? 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; + + var options = util.createRequestOptions( + this, + { + headers : { + 'Content-Type' : 'application/soap+xml; charset=utf-8', + 'SOAPAction' : soapAction + }, + body : RST + } + ); + + this._log.verbose('Sending RST to: ' + this._wstrustEndpointUrl, true); + + request.post(this._wstrustEndpointUrl, options, util.createRequestHandler('WS-Trust RST', this._log, callback, + function(response, body) { + self._handleRSTR(body, callback); + } + )); +}; + +/** +* @callback AcquireTokenCallback +* @memberOf WSTrustRequest +* @param {Error} err Contains an error object if acquireToken fails. +* @param {WSTrustResponse} A successful response to the RST. +*/ + +module.exports = WSTrustRequest; - return DAY_OF_QUARTER_FIELD; - }(Field); - var QUARTER_OF_YEAR_FIELD = function (_Field2) { - _inheritsLoose(QUARTER_OF_YEAR_FIELD, _Field2); +/***/ }), - function QUARTER_OF_YEAR_FIELD() { - return _Field2.apply(this, arguments) || this; - } +/***/ 55927: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var _proto3 = QUARTER_OF_YEAR_FIELD.prototype; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var xmldom = __nccwpck_require__(57286); + +var xmlutil = __nccwpck_require__(27387); + +var Logger = __nccwpck_require__(92288).Logger; + +var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; + +var select = xmlutil.xpathSelect; +var DOMParser = xmldom.DOMParser; + +// A regular expression for finding the SAML Assertion in an RSTR. Used to remove the SAML +// assertion when logging the RSTR. +var assertionRegEx = /RequestedSecurityToken.*?((<.*?:Assertion.*?>).*<\/.*?Assertion>).*?/; + +/** + * Creates a log message that contains the RSTR scrubbed of the actual SAML assertion. + * @private + * @return {string} A log message. + */ +function scrubRSTRLogMessage(RSTR) { + var scrubbedRSTR = null; + + var singleLineRSTR = RSTR.replace(/(\r\n|\n|\r)/gm,''); + + var matchResult = assertionRegEx.exec(singleLineRSTR); + if (null === matchResult) { + // No Assertion was matched so just return the RSTR as is. + scrubbedRSTR = singleLineRSTR; + } else { + var samlAssertion = matchResult[1]; + var samlAssertionStartTag = matchResult[2]; + + scrubbedRSTR = singleLineRSTR.replace(samlAssertion, samlAssertionStartTag + 'ASSERTION CONTENTS REDACTED'); + } + + return 'RSTR Response: ' + scrubbedRSTR; +} + +/** + * Creates a new WSTrustResponse instance. + * @constructor + * @private + * @param {object} callContext Contains any context information that applies to the request. + * @param {string} response A soap response from a WS-Trust request. + * @param {sting} wstrustVersion The version for the WS-Trust request. + */ +function WSTrustResponse(callContext, response, wstrustVersion) { + this._log = new Logger('WSTrustResponse', callContext._logContext); + this._callContext = callContext; + this._response = response; + this._dom = null; + this._errorCode = null; + this._faultMessage = null; + this._tokenType = null; + this._token = null; + this._wstrustVersion = wstrustVersion; + + this._log.verbose(function(){return scrubRSTRLogMessage(response);}); +} + +/** + * If the soap response contained a soap fault then this property will contain the fault + * error code. Otherwise it will return null + * @instance + * @type {string} + * @memberOf WSTrustResponse + * @name errorCode + */ +Object.defineProperty(WSTrustResponse.prototype, 'errorCode', { + get: function() { + return this._errorCode; + } +}); + +/** + * @property {string} FaultMessage If the soap resopnse contained a soap fault with a fault message then it will + * be returned by this property. + * @instance + * @type {string} + * @memberOf WSTrustResponse + * @name faultMessage + */ +Object.defineProperty(WSTrustResponse.prototype, 'faultMessage', { + get: function() { + return this._faultMessage; + } +}); + +/** + * @property {string} TokenType If the soap resonse contained a token then this property will contain + * the token type uri + * @instance + * @type {string} + * @memberOf WSTrustResponse + * @name tokenType + */ +Object.defineProperty(WSTrustResponse.prototype, 'tokenType', { + get: function() { + return this._tokenType; + } +}); + +/** + * @property {string} Token If the soap response contained a token then this property will hold that token. + * @instance + * @type {string} + * @memberOf WSTrustResponse + * @name token + */ +Object.defineProperty(WSTrustResponse.prototype, 'token', { + get: function() { + return this._token; + } +}); + + // Sample error message + // + // + // http://www.w3.org/2005/08/addressing/soap/fault + // - + // + // 2013-07-30T00:32:21.989Z + // 2013-07-30T00:37:21.989Z + // + // + // + // + // + // + // s:Sender + // + // a:RequestFailed + // + // + // + // MSIS3127: The specified request failed. + // + // + // + // + +/** + * Attempts to parse an error from the soap response. If there is one then it + * will fill in the error related properties. Otherwsie it will do nothing. + * @private + * @returns {bool} true if an error was found and parsed in the response. + */ +WSTrustResponse.prototype._parseError = function() { + var errorFound = false; + + var faultNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Reason'); + if (faultNode.length) { + this._faultMessage = xmlutil.serializeNodeChildren(faultNode[0]); + + if (this._faultMessage) { + errorFound = true; + } + } + + // Subcode has minoccurs=0 and maxoccurs=1(default) according to the http://www.w3.org/2003/05/soap-envelope + // Subcode may have another subcode as well. This is only targetting at top level subcode. + // Subcode value may have different messages not always uses http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd. + // text inside the value is not possible to select without prefix, so substring is necessary + var subcodeNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Code/s:Subcode/s:Value'); + if (1 < subcodeNode.length) { + throw this._log.createError('Found too many fault code values:' + subcodeNode.length); + } + + if (subcodeNode.length) { + var errorCode = subcodeNode[0].firstChild.data; + this._errorCode = (errorCode.split(':'))[1]; + errorFound = true; + } + + return errorFound; +}; + +/** + * Attempts to parse a token from the soap response. If there is one then it will fill in the + * token related properties. Otherwise it does nothing. + * @private + * @throws {Error} If the response is not parseable, or too many tokens are found. + */ +WSTrustResponse.prototype._parseToken = function() { + var xPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? '//s:Envelope/s:Body/t:RequestSecurityTokenResponse/t:TokenType' : '//s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/wst:RequestSecurityTokenResponse/wst:TokenType'; + + var tokenTypeNodes = select(this._dom, xPath); + if (!tokenTypeNodes.length) { + this._log.warn('No TokenType elements found in RSTR'); + } + + for (var i = 0, length = tokenTypeNodes.length; i < length; i++) { + if (this._token) { + this._log.warn('Found more than one returned token. Using the first.'); + break; + } + + var tokenTypeNode = tokenTypeNodes[i]; + var tokenType = xmlutil.findElementText(tokenTypeNode); + if (!tokenType) { + this._log.warn('Could not find token type in RSTR token'); + } + + var securityTokenPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? 't:RequestedSecurityToken' : 'wst:RequestedSecurityToken'; + var requestedTokenNode = select(tokenTypeNode.parentNode, securityTokenPath); + if (1 < requestedTokenNode) { + throw this._log.createError('Found too many RequestedSecurityToken nodes for token type: ' + tokenType); + } + if (!requestedTokenNode.length) { + this._log.warn('Unable to find RequestsSecurityToken element associated with TokenType element: ' + tokenType); + continue; + } + + var token = xmlutil.serializeNodeChildren(requestedTokenNode[0]); + if (!token) { + this._log.warn('Unable to find token associated with TokenType element: ' + tokenType); + continue; + } + + this._token = token; + this._tokenType = tokenType; + + this._log.info('Found token of type: ' + this._tokenType); + } + + if (!this._token) { + throw this._log.createError('Unable to find any tokens in RSTR.'); + } +}; + +/** + * This method parses the soap response that was passed in at construction. + * @throws {Error} If the server returned an error, or there was any failure to parse the response. + */ +WSTrustResponse.prototype.parse = function() { + if (!this._response) { + throw this._log.createError('Received empty RSTR response body.'); + } + + try { + try { + var options = { + errorHandler : this._log.error + }; + this._dom = new DOMParser(options).parseFromString(this._response); + } catch (err) { + throw this._log.createError('Failed to parse RSTR in to DOM', err, true); + } + + var errorFound = this._parseError(); + + if (errorFound) { + var stringErrorCode = this.ErrorCode || 'NONE'; + var stringFaultMessage = this.FaultMessage || 'NONE'; + throw this._log.createError('Server returned error in RSTR - ErrorCode: ' + stringErrorCode + ' : FaultMessage: ' + stringFaultMessage, true); + } + + this._parseToken(); + } catch (err) { + delete this._dom; + throw err; + } +}; + +module.exports = WSTrustResponse; - _proto3.toString = function toString() { - return 'QuarterOfYear'; - }; +/***/ }), - _proto3.baseUnit = function baseUnit() { - return QUARTER_YEARS; - }; +/***/ 27387: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto3.rangeUnit = function rangeUnit() { - return ChronoUnit.YEARS; - }; +"use strict"; +/* + * @copyright + * Copyright © Microsoft Open Technologies, Inc. + * + * All Rights Reserved + * + * 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 + * + * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS + * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A + * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. + * + * See the Apache License, Version 2.0 for the specific language + * governing permissions and limitations under the License. + */ + + +var _ = __nccwpck_require__(83571); +var select = __nccwpck_require__(74277); +var XMLSerializer = __nccwpck_require__(57286).XMLSerializer; + +var constants = __nccwpck_require__(10282); + +/** + * @namespace XmlUtil + * @private + */ + +var XPATH_PATH_TEMPLATE = '*[local-name() = \'LOCAL_NAME\' and namespace-uri() = \'NAMESPACE\']'; +/** +* The xpath implementation being used does not have a way of matching expanded namespace. +* This method takes an xpath query and expands all of the namespaces involved. It then +* re-writes the query in to a longer form that directory matches the correct namespaces. +* @private +* @static +* @memberOf XmlUtil +* @param {string} xpath The expath query string to expand. +* @returns {string} An expanded xpath query. +*/ +function expandQNames(xpath) { + var namespaces = constants.XmlNamespaces; + var pathParts = xpath.split('/'); + for (var i=0; i < pathParts.length; i++) { + if (pathParts[i].indexOf(':') !== -1) { + var QNameParts = pathParts[i].split(':'); + if (QNameParts.length !== 2) { + throw new Error('Unable to parse XPath string : ' + xpath + ' : with QName : ' + pathParts[i]); + } + var expandedPath = XPATH_PATH_TEMPLATE.replace('LOCAL_NAME', QNameParts[1]); + expandedPath = expandedPath.replace('NAMESPACE', namespaces[QNameParts[0]]); + pathParts[i] = expandedPath; + } + } + return pathParts.join('/'); +} + +var exports = { + + /** + * Performs an xpath select that does appropriate namespace matching since the imported + * xpath module does not properly handle namespaces. + * @static + * @memberOf XmlUtil + * @param {object} dom A dom object created by the xmldom module + * @param {string} xpath An xpath expression + * @return {array} An array of matching dom nodes. + */ + xpathSelect : function (dom, xpath) { + return select(dom, expandQNames(xpath)); + }, + + /** + * Given a dom node serializes all immediate children that are xml elements. + * @static + * @memberOf XmlUtil + * @param {object} node An xml dom node. + * @return {string} Serialized xml. + */ + serializeNodeChildren : function(node) { + var doc = ''; + var sibling = node.firstChild; + var serializer = new XMLSerializer(); + + while (sibling) { + if (this.isElementNode(sibling)) { + doc += serializer.serializeToString(sibling); + } + sibling = sibling.nextSibling; + } + + return doc !== '' ? doc : null; + }, + + /** + * Detects whether the passed in dom node represents an xml element. + * @static + * @memberOf XmlUtil + * @param {object} node An xml dom node. + * @return {Boolean} true if the node represents an element. + */ + isElementNode : function(node) { + return _.has(node, 'tagName'); + }, + + /** + * Given an xmldom node this function returns any text data contained within. + * @static + * @memberOf XmlUtil + * @param {object} node An xmldom node from which the data should be extracted. + * @return {string} Any data found within the element or null if none is found. + */ + findElementText : function(node) { + var sibling = node.firstChild; + while (sibling && !sibling.data) { + sibling = sibling.nextSibling; + } + + return sibling.data ? sibling.data : null; + } +}; + +module.exports = exports; - _proto3.range = function range() { - return ValueRange.of(1, 4); - }; +/***/ }), - _proto3.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.MONTH_OF_YEAR) && this._isIso(temporal); - }; +/***/ 19744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto3.rangeRefinedBy = function rangeRefinedBy(temporal) { - return this.range(); - }; +var v1 = __nccwpck_require__(64425); +var v4 = __nccwpck_require__(85258); - _proto3.getFrom = function getFrom(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: QuarterOfYear'); - } +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; - var moy = temporal.getLong(ChronoField.MONTH_OF_YEAR); - return MathUtil.intDiv(moy + 2, 3); - }; +module.exports = uuid; - _proto3.adjustInto = function adjustInto(temporal, newValue) { - var curValue = this.getFrom(temporal); - this.range().checkValidValue(newValue, this); - return temporal.with(ChronoField.MONTH_OF_YEAR, temporal.getLong(ChronoField.MONTH_OF_YEAR) + (newValue - curValue) * 3); - }; - return QUARTER_OF_YEAR_FIELD; - }(Field); +/***/ }), - var WEEK_OF_WEEK_BASED_YEAR_FIELD = function (_Field3) { - _inheritsLoose(WEEK_OF_WEEK_BASED_YEAR_FIELD, _Field3); +/***/ 54121: +/***/ ((module) => { - function WEEK_OF_WEEK_BASED_YEAR_FIELD() { - return _Field3.apply(this, arguments) || this; - } +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; +for (var i = 0; i < 256; ++i) { + byteToHex[i] = (i + 0x100).toString(16).substr(1); +} - var _proto4 = WEEK_OF_WEEK_BASED_YEAR_FIELD.prototype; +function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; + // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 + return ([ + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]] + ]).join(''); +} - _proto4.toString = function toString() { - return 'WeekOfWeekBasedYear'; - }; +module.exports = bytesToUuid; - _proto4.baseUnit = function baseUnit() { - return ChronoUnit.WEEKS; - }; - _proto4.rangeUnit = function rangeUnit() { - return WEEK_BASED_YEARS; - }; +/***/ }), - _proto4.range = function range() { - return ValueRange.of(1, 52, 53); - }; +/***/ 57455: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto4.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.EPOCH_DAY) && this._isIso(temporal); - }; +// Unique ID creation requires a high quality random # generator. In node.js +// this is pretty straight-forward - we use the crypto API. - _proto4.rangeRefinedBy = function rangeRefinedBy(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: WeekOfWeekBasedYear'); - } +var crypto = __nccwpck_require__(76417); - return Field._getWeekRangeByLocalDate(LocalDate.from(temporal)); - }; +module.exports = function nodeRNG() { + return crypto.randomBytes(16); +}; - _proto4.getFrom = function getFrom(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: WeekOfWeekBasedYear'); - } - return Field._getWeek(LocalDate.from(temporal)); - }; +/***/ }), - _proto4.adjustInto = function adjustInto(temporal, newValue) { - this.range().checkValidValue(newValue, this); - return temporal.plus(MathUtil.safeSubtract(newValue, this.getFrom(temporal)), ChronoUnit.WEEKS); - }; +/***/ 64425: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto4.resolve = function resolve(fieldValues, partialTemporal, resolverStyle) { - var wbyLong = fieldValues.get(WEEK_BASED_YEAR); - var dowLong = fieldValues.get(ChronoField.DAY_OF_WEEK); +var rng = __nccwpck_require__(57455); +var bytesToUuid = __nccwpck_require__(54121); - if (wbyLong == null || dowLong == null) { - return null; - } +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html - var wby = WEEK_BASED_YEAR.range().checkValidIntValue(wbyLong, WEEK_BASED_YEAR); - var wowby = fieldValues.get(WEEK_OF_WEEK_BASED_YEAR); - var date; +var _nodeId; +var _clockseq; - if (resolverStyle === ResolverStyle.LENIENT) { - var dow = dowLong; - var weeks = 0; +// Previous uuid creation time +var _lastMSecs = 0; +var _lastNSecs = 0; - if (dow > 7) { - weeks = MathUtil.intDiv(dow - 1, 7); - dow = MathUtil.intMod(dow - 1, 7) + 1; - } else if (dow < 1) { - weeks = MathUtil.intDiv(dow, 7) - 1; - dow = MathUtil.intMod(dow, 7) + 7; - } +// See https://github.com/uuidjs/uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; - date = LocalDate.of(wby, 1, 4).plusWeeks(wowby - 1).plusWeeks(weeks).with(ChronoField.DAY_OF_WEEK, dow); - } else { - var _dow2 = ChronoField.DAY_OF_WEEK.checkValidIntValue(dowLong); + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - if (resolverStyle === ResolverStyle.STRICT) { - var temp = LocalDate.of(wby, 1, 4); + // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + if (node == null || clockseq == null) { + var seedBytes = rng(); + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [ + seedBytes[0] | 0x01, + seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] + ]; + } + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } - var range = Field._getWeekRangeByLocalDate(temp); + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - range.checkValidValue(wowby, this); - } else { - this.range().checkValidValue(wowby, this); - } + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - date = LocalDate.of(wby, 1, 4).plusWeeks(wowby - 1).with(ChronoField.DAY_OF_WEEK, _dow2); - } + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; - fieldValues.remove(this); - fieldValues.remove(WEEK_BASED_YEAR); - fieldValues.remove(ChronoField.DAY_OF_WEEK); - return date; - }; + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } - _proto4.displayName = function displayName() { - return 'Week'; - }; + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } - return WEEK_OF_WEEK_BASED_YEAR_FIELD; - }(Field); + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } - var WEEK_BASED_YEAR_FIELD = function (_Field4) { - _inheritsLoose(WEEK_BASED_YEAR_FIELD, _Field4); + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; - function WEEK_BASED_YEAR_FIELD() { - return _Field4.apply(this, arguments) || this; - } + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; - var _proto5 = WEEK_BASED_YEAR_FIELD.prototype; + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; - _proto5.toString = function toString() { - return 'WeekBasedYear'; - }; + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; - _proto5.baseUnit = function baseUnit() { - return WEEK_BASED_YEARS; - }; + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; - _proto5.rangeUnit = function rangeUnit() { - return ChronoUnit.FOREVER; - }; + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; - _proto5.range = function range() { - return ChronoField.YEAR.range(); - }; + // `clock_seq_low` + b[i++] = clockseq & 0xff; - _proto5.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.EPOCH_DAY) && this._isIso(temporal); - }; + // `node` + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } - _proto5.rangeRefinedBy = function rangeRefinedBy(temporal) { - return ChronoField.YEAR.range(); - }; - - _proto5.getFrom = function getFrom(temporal) { - if (temporal.isSupported(this) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: WeekBasedYear'); - } + return buf ? buf : bytesToUuid(b); +} - return Field._getWeekBasedYear(LocalDate.from(temporal)); - }; +module.exports = v1; - _proto5.adjustInto = function adjustInto(temporal, newValue) { - if (this.isSupportedBy(temporal) === false) { - throw new UnsupportedTemporalTypeException('Unsupported field: WeekBasedYear'); - } - var newWby = this.range().checkValidIntValue(newValue, WEEK_BASED_YEAR); - var date = LocalDate.from(temporal); - var dow = date.get(ChronoField.DAY_OF_WEEK); +/***/ }), - var week = Field._getWeek(date); +/***/ 85258: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (week === 53 && Field._getWeekRangeByYear(newWby) === 52) { - week = 52; - } +var rng = __nccwpck_require__(57455); +var bytesToUuid = __nccwpck_require__(54121); - var resolved = LocalDate.of(newWby, 1, 4); - var days = dow - resolved.get(ChronoField.DAY_OF_WEEK) + (week - 1) * 7; - resolved = resolved.plusDays(days); - return temporal.with(resolved); - }; +function v4(options, buf, offset) { + var i = buf && offset || 0; - return WEEK_BASED_YEAR_FIELD; - }(Field); + if (typeof(options) == 'string') { + buf = options === 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; - var Unit = function (_TemporalUnit) { - _inheritsLoose(Unit, _TemporalUnit); + var rnds = options.random || (options.rng || rng)(); - function Unit(name, estimatedDuration) { - var _this; + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; - _this = _TemporalUnit.call(this) || this; - _this._name = name; - _this._duration = estimatedDuration; - return _this; - } + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; + } + } - var _proto6 = Unit.prototype; + return buf || bytesToUuid(rnds); +} - _proto6.duration = function duration() { - return this._duration; - }; +module.exports = v4; - _proto6.isDurationEstimated = function isDurationEstimated() { - return true; - }; - _proto6.isDateBased = function isDateBased() { - return true; - }; +/***/ }), - _proto6.isTimeBased = function isTimeBased() { - return false; - }; +/***/ 64941: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto6.isSupportedBy = function isSupportedBy(temporal) { - return temporal.isSupported(ChronoField.EPOCH_DAY); - }; +"use strict"; - _proto6.addTo = function addTo(temporal, periodToAdd) { - switch (this) { - case WEEK_BASED_YEARS: - { - var added = MathUtil.safeAdd(temporal.get(WEEK_BASED_YEAR), periodToAdd); - return temporal.with(WEEK_BASED_YEAR, added); - } - case QUARTER_YEARS: - return temporal.plus(MathUtil.intDiv(periodToAdd, 256), ChronoUnit.YEARS).plus(MathUtil.intMod(periodToAdd, 256) * 3, ChronoUnit.MONTHS); +var compileSchema = __nccwpck_require__(875) + , resolve = __nccwpck_require__(63896) + , Cache = __nccwpck_require__(93679) + , SchemaObject = __nccwpck_require__(37605) + , stableStringify = __nccwpck_require__(30969) + , formats = __nccwpck_require__(66627) + , rules = __nccwpck_require__(68561) + , $dataMetaSchema = __nccwpck_require__(21412) + , util = __nccwpck_require__(76578); - default: - throw new IllegalStateException('Unreachable'); - } - }; +module.exports = Ajv; - _proto6.between = function between(temporal1, temporal2) { - switch (this) { - case WEEK_BASED_YEARS: - return MathUtil.safeSubtract(temporal2.getLong(WEEK_BASED_YEAR), temporal1.getLong(WEEK_BASED_YEAR)); +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; - case QUARTER_YEARS: - return MathUtil.intDiv(temporal1.until(temporal2, ChronoUnit.MONTHS), 3); +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; - default: - throw new IllegalStateException('Unreachable'); - } - }; +Ajv.prototype.compileAsync = __nccwpck_require__(80890); +var customKeyword = __nccwpck_require__(53297); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; - _proto6.toString = function toString() { - return name; - }; +var errorClasses = __nccwpck_require__(25726); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; - return Unit; - }(TemporalUnit); - - var DAY_OF_QUARTER = null; - var QUARTER_OF_YEAR = null; - var WEEK_OF_WEEK_BASED_YEAR = null; - var WEEK_BASED_YEAR = null; - var WEEK_BASED_YEARS = null; - var QUARTER_YEARS = null; - function _init$8() { - DAY_OF_QUARTER = new DAY_OF_QUARTER_FIELD(); - QUARTER_OF_YEAR = new QUARTER_OF_YEAR_FIELD(); - WEEK_OF_WEEK_BASED_YEAR = new WEEK_OF_WEEK_BASED_YEAR_FIELD(); - WEEK_BASED_YEAR = new WEEK_BASED_YEAR_FIELD(); - WEEK_BASED_YEARS = new Unit('WeekBasedYears', Duration.ofSeconds(31556952)); - QUARTER_YEARS = new Unit('QuarterYears', Duration.ofSeconds(31556952 / 4)); - IsoFields.DAY_OF_QUARTER = DAY_OF_QUARTER; - IsoFields.QUARTER_OF_YEAR = QUARTER_OF_YEAR; - IsoFields.WEEK_OF_WEEK_BASED_YEAR = WEEK_OF_WEEK_BASED_YEAR; - IsoFields.WEEK_BASED_YEAR = WEEK_BASED_YEAR; - IsoFields.WEEK_BASED_YEARS = WEEK_BASED_YEARS; - IsoFields.QUARTER_YEARS = QUARTER_YEARS; - - LocalDate.prototype.isoWeekOfWeekyear = function () { - return this.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); - }; +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; - LocalDate.prototype.isoWeekyear = function () { - return this.get(IsoFields.WEEK_BASED_YEAR); - }; - } +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var DecimalStyle = function () { - function DecimalStyle(zeroChar, positiveSignChar, negativeSignChar, decimalPointChar) { - this._zeroDigit = zeroChar; - this._zeroDigitCharCode = zeroChar.charCodeAt(0); - this._positiveSign = positiveSignChar; - this._negativeSign = negativeSignChar; - this._decimalSeparator = decimalPointChar; - } +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); - var _proto = DecimalStyle.prototype; + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); - _proto.positiveSign = function positiveSign() { - return this._positiveSign; - }; + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); - _proto.withPositiveSign = function withPositiveSign(positiveSign) { - if (positiveSign === this._positiveSign) { - return this; - } + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} - return new DecimalStyle(this._zeroDigit, positiveSign, this._negativeSign, this._decimalSeparator); - }; - _proto.negativeSign = function negativeSign() { - return this._negativeSign; - }; - _proto.withNegativeSign = function withNegativeSign(negativeSign) { - if (negativeSign === this._negativeSign) { - return this; - } +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } - return new DecimalStyle(this._zeroDigit, this._positiveSign, negativeSign, this._decimalSeparator); - }; + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} - _proto.zeroDigit = function zeroDigit() { - return this._zeroDigit; - }; - _proto.withZeroDigit = function withZeroDigit(zeroDigit) { - if (zeroDigit === this._zeroDigit) { - return this; - } +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} - return new DecimalStyle(zeroDigit, this._positiveSign, this._negativeSign, this._decimalSeparator); - }; - _proto.decimalSeparator = function decimalSeparator() { - return this._decimalSeparator; - }; +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i= 0 && val <= 9 ? val : -1; - }; +/** + * Validate schema + * @this Ajv + * @param {Object} schema schema to validate + * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid + * @return {Boolean} true if schema is valid + */ +function validateSchema(schema, throwOrLogError) { + var $schema = schema.$schema; + if ($schema !== undefined && typeof $schema != 'string') + throw new Error('$schema must be a string'); + $schema = $schema || this._opts.defaultMeta || defaultMeta(this); + if (!$schema) { + this.logger.warn('meta-schema not available'); + this.errors = null; + return true; + } + var valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + var message = 'schema is invalid: ' + this.errorsText(); + if (this._opts.validateSchema == 'log') this.logger.error(message); + else throw new Error(message); + } + return valid; +} - _proto.convertNumberToI18N = function convertNumberToI18N(numericText) { - if (this._zeroDigit === '0') { - return numericText; - } - var diff = this._zeroDigitCharCode - '0'.charCodeAt(0); - var convertedText = ''; +function defaultMeta(self) { + var meta = self._opts.meta; + self._opts.defaultMeta = typeof meta == 'object' + ? self._getId(meta) || meta + : self.getSchema(META_SCHEMA_ID) + ? META_SCHEMA_ID + : undefined; + return self._opts.defaultMeta; +} - for (var i = 0; i < numericText.length; i++) { - convertedText += String.fromCharCode(numericText.charCodeAt(i) + diff); - } - return convertedText; - }; +/** + * Get compiled schema from the instance by `key` or `ref`. + * @this Ajv + * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). + */ +function getSchema(keyRef) { + var schemaObj = _getSchemaObj(this, keyRef); + switch (typeof schemaObj) { + case 'object': return schemaObj.validate || this._compile(schemaObj); + case 'string': return this.getSchema(schemaObj); + case 'undefined': return _getSchemaFragment(this, keyRef); + } +} - _proto.equals = function equals(other) { - if (this === other) { - return true; - } - if (other instanceof DecimalStyle) { - return this._zeroDigit === other._zeroDigit && this._positiveSign === other._positiveSign && this._negativeSign === other._negativeSign && this._decimalSeparator === other._decimalSeparator; - } +function _getSchemaFragment(self, ref) { + var res = resolve.schema.call(self, { schema: {} }, ref); + if (res) { + var schema = res.schema + , root = res.root + , baseId = res.baseId; + var v = compileSchema.call(self, schema, root, undefined, baseId); + self._fragments[ref] = new SchemaObject({ + ref: ref, + fragment: true, + schema: schema, + root: root, + baseId: baseId, + validate: v + }); + return v; + } +} - return false; - }; - _proto.hashCode = function hashCode() { - return this._zeroDigit + this._positiveSign + this._negativeSign + this._decimalSeparator; - }; +function _getSchemaObj(self, keyRef) { + keyRef = resolve.normalizeId(keyRef); + return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; +} - _proto.toString = function toString() { - return 'DecimalStyle[' + this._zeroDigit + this._positiveSign + this._negativeSign + this._decimalSeparator + ']'; - }; - DecimalStyle.of = function of() { - throw new Error('not yet supported'); - }; +/** + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @this Ajv + * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object + * @return {Ajv} this for method chaining + */ +function removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + _removeAllSchemas(this, this._schemas, schemaKeyRef); + _removeAllSchemas(this, this._refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case 'undefined': + _removeAllSchemas(this, this._schemas); + _removeAllSchemas(this, this._refs); + this._cache.clear(); + return this; + case 'string': + var schemaObj = _getSchemaObj(this, schemaKeyRef); + if (schemaObj) this._cache.del(schemaObj.cacheKey); + delete this._schemas[schemaKeyRef]; + delete this._refs[schemaKeyRef]; + return this; + case 'object': + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; + this._cache.del(cacheKey); + var id = this._getId(schemaKeyRef); + if (id) { + id = resolve.normalizeId(id); + delete this._schemas[id]; + delete this._refs[id]; + } + } + return this; +} - DecimalStyle.availableLocales = function availableLocales() { - throw new Error('not yet supported'); - }; - return DecimalStyle; - }(); - DecimalStyle.STANDARD = new DecimalStyle('0', '+', '-', '.'); +function _removeAllSchemas(self, schemas, regex) { + for (var keyRef in schemas) { + var schemaObj = schemas[keyRef]; + if (!schemaObj.meta && (!regex || regex.test(keyRef))) { + self._cache.del(schemaObj.cacheKey); + delete schemas[keyRef]; + } + } +} - var SignStyle = function (_Enum) { - _inheritsLoose(SignStyle, _Enum); - function SignStyle() { - return _Enum.apply(this, arguments) || this; - } +/* @this Ajv */ +function _addSchema(schema, skipValidation, meta, shouldAddSchema) { + if (typeof schema != 'object' && typeof schema != 'boolean') + throw new Error('schema should be object or boolean'); + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schema) : schema; + var cached = this._cache.get(cacheKey); + if (cached) return cached; - var _proto = SignStyle.prototype; + shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; - _proto.parse = function parse(positive, strict, fixedWidth) { - switch (this) { - case SignStyle.NORMAL: - return !positive || !strict; + var id = resolve.normalizeId(this._getId(schema)); + if (id && shouldAddSchema) checkUnique(this, id); - case SignStyle.ALWAYS: - case SignStyle.EXCEEDS_PAD: - return true; + var willValidate = this._opts.validateSchema !== false && !skipValidation; + var recursiveMeta; + if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) + this.validateSchema(schema, true); - default: - return !strict && !fixedWidth; - } - }; + var localRefs = resolve.ids.call(this, schema); - return SignStyle; - }(Enum); - SignStyle.NORMAL = new SignStyle('NORMAL'); - SignStyle.NEVER = new SignStyle('NEVER'); - SignStyle.ALWAYS = new SignStyle('ALWAYS'); - SignStyle.EXCEEDS_PAD = new SignStyle('EXCEEDS_PAD'); - SignStyle.NOT_NEGATIVE = new SignStyle('NOT_NEGATIVE'); + var schemaObj = new SchemaObject({ + id: id, + schema: schema, + localRefs: localRefs, + cacheKey: cacheKey, + meta: meta + }); - var TextStyle = function (_Enum) { - _inheritsLoose(TextStyle, _Enum); + if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; + this._cache.put(cacheKey, schemaObj); - function TextStyle() { - return _Enum.apply(this, arguments) || this; - } + if (willValidate && recursiveMeta) this.validateSchema(schema, true); - var _proto = TextStyle.prototype; + return schemaObj; +} - _proto.isStandalone = function isStandalone() { - switch (this) { - case TextStyle.FULL_STANDALONE: - case TextStyle.SHORT_STANDALONE: - case TextStyle.NARROW_STANDALONE: - return true; - default: - return false; - } - }; +/* @this Ajv */ +function _compile(schemaObj, root) { + if (schemaObj.compiling) { + schemaObj.validate = callValidate; + callValidate.schema = schemaObj.schema; + callValidate.errors = null; + callValidate.root = root ? root : callValidate; + if (schemaObj.schema.$async === true) + callValidate.$async = true; + return callValidate; + } + schemaObj.compiling = true; - _proto.asStandalone = function asStandalone() { - switch (this) { - case TextStyle.FULL: - return TextStyle.FULL_STANDALONE; + var currentOpts; + if (schemaObj.meta) { + currentOpts = this._opts; + this._opts = this._metaOpts; + } - case TextStyle.SHORT: - return TextStyle.SHORT_STANDALONE; + var v; + try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); } + catch(e) { + delete schemaObj.validate; + throw e; + } + finally { + schemaObj.compiling = false; + if (schemaObj.meta) this._opts = currentOpts; + } - case TextStyle.NARROW: - return TextStyle.NARROW_STANDALONE; + schemaObj.validate = v; + schemaObj.refs = v.refs; + schemaObj.refVal = v.refVal; + schemaObj.root = v.root; + return v; - default: - return this; - } - }; - _proto.asNormal = function asNormal() { - switch (this) { - case TextStyle.FULL_STANDALONE: - return TextStyle.FULL; + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var _validate = schemaObj.validate; + var result = _validate.apply(this, arguments); + callValidate.errors = _validate.errors; + return result; + } +} - case TextStyle.SHORT_STANDALONE: - return TextStyle.SHORT; - case TextStyle.NARROW_STANDALONE: - return TextStyle.NARROW; +function chooseGetId(opts) { + switch (opts.schemaId) { + case 'auto': return _get$IdOrId; + case 'id': return _getId; + default: return _get$Id; + } +} - default: - return this; - } - }; +/* @this Ajv */ +function _getId(schema) { + if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); + return schema.id; +} - return TextStyle; - }(Enum); - TextStyle.FULL = new TextStyle('FULL'); - TextStyle.FULL_STANDALONE = new TextStyle('FULL_STANDALONE'); - TextStyle.SHORT = new TextStyle('SHORT'); - TextStyle.SHORT_STANDALONE = new TextStyle('SHORT_STANDALONE'); - TextStyle.NARROW = new TextStyle('NARROW'); - TextStyle.NARROW_STANDALONE = new TextStyle('NARROW_STANDALONE'); +/* @this Ajv */ +function _get$Id(schema) { + if (schema.id) this.logger.warn('schema id ignored', schema.id); + return schema.$id; +} - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var CharLiteralPrinterParser = function () { - function CharLiteralPrinterParser(literal) { - if (literal.length > 1) { - throw new IllegalArgumentException('invalid literal, too long: "' + literal + '"'); - } - this._literal = literal; - } +function _get$IdOrId(schema) { + if (schema.$id && schema.id && schema.$id != schema.id) + throw new Error('schema $id is different from id'); + return schema.$id || schema.id; +} - var _proto = CharLiteralPrinterParser.prototype; - _proto.print = function print(context, buf) { - buf.append(this._literal); - return true; - }; +/** + * Convert array of error message objects to string + * @this Ajv + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; - _proto.parse = function parse(context, text, position) { - var length = text.length; + var text = ''; + for (var i=0; i { - return position; - } - }; +"use strict"; - _proto.toString = function toString() { - var buf = ''; - if (this._printerParsers != null) { - buf += this._optional ? '[' : '('; - for (var i = 0; i < this._printerParsers.length; i++) { - var pp = this._printerParsers[i]; - buf += pp.toString(); - } +var Cache = module.exports = function Cache() { + this._cache = {}; +}; - buf += this._optional ? ']' : ')'; - } - return buf; - }; +Cache.prototype.put = function Cache_put(key, value) { + this._cache[key] = value; +}; - return CompositePrinterParser; - }(); - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var FractionPrinterParser = function () { - function FractionPrinterParser(field, minWidth, maxWidth, decimalPoint) { - requireNonNull(field, 'field'); +Cache.prototype.get = function Cache_get(key) { + return this._cache[key]; +}; - if (field.range().isFixed() === false) { - throw new IllegalArgumentException('Field must have a fixed set of values: ' + field); - } - if (minWidth < 0 || minWidth > 9) { - throw new IllegalArgumentException('Minimum width must be from 0 to 9 inclusive but was ' + minWidth); - } +Cache.prototype.del = function Cache_del(key) { + delete this._cache[key]; +}; - if (maxWidth < 1 || maxWidth > 9) { - throw new IllegalArgumentException('Maximum width must be from 1 to 9 inclusive but was ' + maxWidth); - } - if (maxWidth < minWidth) { - throw new IllegalArgumentException('Maximum width must exceed or equal the minimum width but ' + maxWidth + ' < ' + minWidth); - } +Cache.prototype.clear = function Cache_clear() { + this._cache = {}; +}; - this.field = field; - this.minWidth = minWidth; - this.maxWidth = maxWidth; - this.decimalPoint = decimalPoint; - } - var _proto = FractionPrinterParser.prototype; +/***/ }), - _proto.print = function print(context, buf) { - var value = context.getValue(this.field); +/***/ 80890: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (value === null) { - return false; - } +"use strict"; - var symbols = context.symbols(); - if (value === 0) { - if (this.minWidth > 0) { - if (this.decimalPoint) { - buf.append(symbols.decimalSeparator()); - } +var MissingRefError = __nccwpck_require__(25726).MissingRef; - for (var i = 0; i < this.minWidth; i++) { - buf.append(symbols.zeroDigit()); - } - } - } else { - var fraction = this.convertToFraction(value, symbols.zeroDigit()); - var outputScale = Math.min(Math.max(fraction.length, this.minWidth), this.maxWidth); - fraction = fraction.substr(0, outputScale); +module.exports = compileAsync; - if (fraction * 1 > 0) { - while (fraction.length > this.minWidth && fraction[fraction.length - 1] === '0') { - fraction = fraction.substr(0, fraction.length - 1); - } - } - var str = fraction; - str = symbols.convertNumberToI18N(str); +/** + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. + * @return {Promise} promise that resolves with a validating function. + */ +function compileAsync(schema, meta, callback) { + /* eslint no-shadow: 0 */ + /* global Promise */ + /* jshint validthis: true */ + var self = this; + if (typeof this._opts.loadSchema != 'function') + throw new Error('options.loadSchema should be a function'); - if (this.decimalPoint) { - buf.append(symbols.decimalSeparator()); - } + if (typeof meta == 'function') { + callback = meta; + meta = undefined; + } - buf.append(str); - } + var p = loadMetaSchemaOf(schema).then(function () { + var schemaObj = self._addSchema(schema, undefined, meta); + return schemaObj.validate || _compileAsync(schemaObj); + }); - return true; - }; + if (callback) { + p.then( + function(v) { callback(null, v); }, + callback + ); + } - _proto.parse = function parse(context, text, position) { - var effectiveMin = context.isStrict() ? this.minWidth : 0; - var effectiveMax = context.isStrict() ? this.maxWidth : 9; - var length = text.length; + return p; - if (position === length) { - return effectiveMin > 0 ? ~position : position; - } - if (this.decimalPoint) { - if (text[position] !== context.symbols().decimalSeparator()) { - return effectiveMin > 0 ? ~position : position; - } + function loadMetaSchemaOf(sch) { + var $schema = sch.$schema; + return $schema && !self.getSchema($schema) + ? compileAsync.call(self, { $ref: $schema }, true) + : Promise.resolve(); + } - position++; - } - var minEndPos = position + effectiveMin; + function _compileAsync(schemaObj) { + try { return self._compile(schemaObj); } + catch(e) { + if (e instanceof MissingRefError) return loadMissingSchema(e); + throw e; + } - if (minEndPos > length) { - return ~position; - } - var maxEndPos = Math.min(position + effectiveMax, length); - var total = 0; - var pos = position; + function loadMissingSchema(e) { + var ref = e.missingSchema; + if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); - while (pos < maxEndPos) { - var ch = text.charAt(pos++); - var digit = context.symbols().convertToDigit(ch); + var schemaPromise = self._loadingSchemas[ref]; + if (!schemaPromise) { + schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); + schemaPromise.then(removePromise, removePromise); + } - if (digit < 0) { - if (pos < minEndPos) { - return ~position; - } + return schemaPromise.then(function (sch) { + if (!added(ref)) { + return loadMetaSchemaOf(sch).then(function () { + if (!added(ref)) self.addSchema(sch, ref, undefined, meta); + }); + } + }).then(function() { + return _compileAsync(schemaObj); + }); - pos--; - break; - } + function removePromise() { + delete self._loadingSchemas[ref]; + } - total = total * 10 + digit; - } + function added(ref) { + return self._refs[ref] || self._schemas[ref]; + } + } + } +} - var moveLeft = pos - position; - var scale = Math.pow(10, moveLeft); - var value = this.convertFromFraction(total, scale); - return context.setParsedField(this.field, value, position, pos); - }; - _proto.convertToFraction = function convertToFraction(value, zeroDigit) { - var range = this.field.range(); - range.checkValidValue(value, this.field); +/***/ }), - var _min = range.minimum(); +/***/ 25726: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var _range = range.maximum() - _min + 1; +"use strict"; - var _value = value - _min; - var _scaled = MathUtil.intDiv(_value * 1000000000, _range); +var resolve = __nccwpck_require__(63896); - var fraction = '' + _scaled; +module.exports = { + Validation: errorSubclass(ValidationError), + MissingRef: errorSubclass(MissingRefError) +}; - while (fraction.length < 9) { - fraction = zeroDigit + fraction; - } - return fraction; - }; +function ValidationError(errors) { + this.message = 'validation failed'; + this.errors = errors; + this.ajv = this.validation = true; +} - _proto.convertFromFraction = function convertFromFraction(total, scale) { - var range = this.field.range(); - var _min = range.minimum(); +MissingRefError.message = function (baseId, ref) { + return 'can\'t resolve reference ' + ref + ' from id ' + baseId; +}; - var _range = range.maximum() - _min + 1; - var _value = MathUtil.intDiv(total * _range, scale); +function MissingRefError(baseId, ref, message) { + this.message = message || MissingRefError.message(baseId, ref); + this.missingRef = resolve.url(baseId, ref); + this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); +} - return _value; - }; - _proto.toString = function toString() { - var decimal = this.decimalPoint ? ',DecimalPoint' : ''; - return 'Fraction(' + this.field + ',' + this.minWidth + ',' + this.maxWidth + decimal + ')'; - }; +function errorSubclass(Subclass) { + Subclass.prototype = Object.create(Error.prototype); + Subclass.prototype.constructor = Subclass; + return Subclass; +} - return FractionPrinterParser; - }(); - var MAX_WIDTH = 15; - var EXCEED_POINTS = [0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; - var NumberPrinterParser = function () { - function NumberPrinterParser(field, minWidth, maxWidth, signStyle, subsequentWidth) { - if (subsequentWidth === void 0) { - subsequentWidth = 0; - } +/***/ }), - this._field = field; - this._minWidth = minWidth; - this._maxWidth = maxWidth; - this._signStyle = signStyle; - this._subsequentWidth = subsequentWidth; - } +/***/ 66627: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var _proto = NumberPrinterParser.prototype; +"use strict"; - _proto.field = function field() { - return this._field; - }; - _proto.minWidth = function minWidth() { - return this._minWidth; - }; +var util = __nccwpck_require__(76578); + +var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; +var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +// uri-template: https://tools.ietf.org/html/rfc6570 +var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + + +module.exports = formats; - _proto.maxWidth = function maxWidth() { - return this._maxWidth; - }; +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} - _proto.signStyle = function signStyle() { - return this._signStyle; - }; - _proto.withFixedWidth = function withFixedWidth() { - if (this._subsequentWidth === -1) { - return this; - } +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; - return new NumberPrinterParser(this._field, this._minWidth, this._maxWidth, this._signStyle, -1); - }; - _proto.withSubsequentWidth = function withSubsequentWidth(subsequentWidth) { - return new NumberPrinterParser(this._field, this._minWidth, this._maxWidth, this._signStyle, this._subsequentWidth + subsequentWidth); - }; +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: HOSTNAME, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; - _proto._isFixedWidth = function _isFixedWidth() { - return this._subsequentWidth === -1 || this._subsequentWidth > 0 && this._minWidth === this._maxWidth && this._signStyle === SignStyle.NOT_NEGATIVE; - }; - _proto.print = function print(context, buf) { - var contextValue = context.getValue(this._field); +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} - if (contextValue == null) { - return false; - } - var value = this._getValue(context, contextValue); +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; - var symbols = context.symbols(); - var str = '' + Math.abs(value); + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; - if (str.length > this._maxWidth) { - throw new DateTimeException('Field ' + this._field + ' cannot be printed as the value ' + value + ' exceeds the maximum print width of ' + this._maxWidth); - } + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} - str = symbols.convertNumberToI18N(str); - if (value >= 0) { - switch (this._signStyle) { - case SignStyle.EXCEEDS_PAD: - if (this._minWidth < MAX_WIDTH && value >= EXCEED_POINTS[this._minWidth]) { - buf.append(symbols.positiveSign()); - } +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} - break; - case SignStyle.ALWAYS: - buf.append(symbols.positiveSign()); - break; - } - } else { - switch (this._signStyle) { - case SignStyle.NORMAL: - case SignStyle.EXCEEDS_PAD: - case SignStyle.ALWAYS: - buf.append(symbols.negativeSign()); - break; +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} - case SignStyle.NOT_NEGATIVE: - throw new DateTimeException('Field ' + this._field + ' cannot be printed as the value ' + value + ' cannot be negative according to the SignStyle'); - } - } - for (var i = 0; i < this._minWidth - str.length; i++) { - buf.append(symbols.zeroDigit()); - } +/***/ }), - buf.append(str); - return true; - }; +/***/ 875: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.parse = function parse(context, text, position) { - var length = text.length; +"use strict"; - if (position === length) { - return ~position; - } - assert(position >= 0 && position < length); - var sign = text.charAt(position); - var negative = false; - var positive = false; +var resolve = __nccwpck_require__(63896) + , util = __nccwpck_require__(76578) + , errorClasses = __nccwpck_require__(25726) + , stableStringify = __nccwpck_require__(30969); - if (sign === context.symbols().positiveSign()) { - if (this._signStyle.parse(true, context.isStrict(), this._minWidth === this._maxWidth) === false) { - return ~position; - } +var validateGenerator = __nccwpck_require__(49585); - positive = true; - position++; - } else if (sign === context.symbols().negativeSign()) { - if (this._signStyle.parse(false, context.isStrict(), this._minWidth === this._maxWidth) === false) { - return ~position; - } +/** + * Functions below are used inside compiled validations function + */ - negative = true; - position++; - } else { - if (this._signStyle === SignStyle.ALWAYS && context.isStrict()) { - return ~position; - } - } +var ucs2length = util.ucs2length; +var equal = __nccwpck_require__(28206); - var effMinWidth = context.isStrict() || this._isFixedWidth() ? this._minWidth : 1; - var minEndPos = position + effMinWidth; +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; - if (minEndPos > length) { - return ~position; - } +module.exports = compile; - var effMaxWidth = (context.isStrict() || this._isFixedWidth() ? this._maxWidth : 9) + Math.max(this._subsequentWidth, 0); - var total = 0; - var pos = position; - for (var pass = 0; pass < 2; pass++) { - var maxEndPos = Math.min(pos + effMaxWidth, length); +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; - while (pos < maxEndPos) { - var ch = text.charAt(pos++); - var digit = context.symbols().convertToDigit(ch); + root = root || { schema: schema, refVal: refVal, refs: refs }; - if (digit < 0) { - pos--; + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); - if (pos < minEndPos) { - return ~position; - } + var formats = this._formats; + var RULES = this.RULES; - break; - } + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } - if (pos - position > MAX_WIDTH) { - throw new ArithmeticException('number text exceeds length'); - } else { - total = total * 10 + digit; - } - } + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } - if (this._subsequentWidth > 0 && pass === 0) { - var parseLen = pos - position; - effMaxWidth = Math.max(effMinWidth, parseLen - this._subsequentWidth); - pos = position; - total = 0; - } else { - break; - } - } + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); - if (negative) { - if (total === 0 && context.isStrict()) { - return ~(position - 1); - } + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; - if (total !== 0) { - total = -total; - } - } else if (this._signStyle === SignStyle.EXCEEDS_PAD && context.isStrict()) { - var _parseLen = pos - position; + if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + sourceCode + ); - if (positive) { - if (_parseLen <= this._minWidth) { - return ~(position - 1); - } - } else { - if (_parseLen > this._minWidth) { - return ~position; - } - } - } + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError + ); - return this._setValue(context, total, position, pos); - }; + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } - _proto._getValue = function _getValue(context, value) { - return value; + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults }; + } - _proto._setValue = function _setValue(context, value, errorPos, successPos) { - return context.setParsedField(this._field, value, errorPos, successPos); - }; + return validate; + } - _proto.toString = function toString() { - if (this._minWidth === 1 && this._maxWidth === MAX_WIDTH && this._signStyle === SignStyle.NORMAL) { - return 'Value(' + this._field + ')'; - } + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } - if (this._minWidth === this._maxWidth && this._signStyle === SignStyle.NOT_NEGATIVE) { - return 'Value(' + this._field + ',' + this._minWidth + ')'; - } + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } - return 'Value(' + this._field + ',' + this._minWidth + ',' + this._maxWidth + ',' + this._signStyle + ')'; - }; + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } - return NumberPrinterParser; - }(); - var ReducedPrinterParser = function (_NumberPrinterParser) { - _inheritsLoose(ReducedPrinterParser, _NumberPrinterParser); + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } - function ReducedPrinterParser(field, width, maxWidth, baseValue, baseDate) { - var _this; + function removeLocalRef(ref) { + delete refs[ref]; + } - _this = _NumberPrinterParser.call(this, field, width, maxWidth, SignStyle.NOT_NEGATIVE) || this; + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } - if (width < 1 || width > 10) { - throw new IllegalArgumentException('The width must be from 1 to 10 inclusive but was ' + width); - } + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } - if (maxWidth < 1 || maxWidth > 10) { - throw new IllegalArgumentException('The maxWidth must be from 1 to 10 inclusive but was ' + maxWidth); - } + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } - if (maxWidth < width) { - throw new IllegalArgumentException('The maxWidth must be greater than the width'); + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; } + return 'default' + index; + } + } - if (baseDate === null) { - if (field.range().isValidValue(baseValue) === false) { - throw new IllegalArgumentException('The base value must be within the range of the field'); - } + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); - if (baseValue + EXCEED_POINTS[width] > MathUtil.MAX_SAFE_INTEGER) { - throw new DateTimeException('Unable to add printer-parser as the range exceeds the capacity of an int'); - } + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); } - - _this._baseValue = baseValue; - _this._baseDate = baseDate; - return _this; } + } - var _proto2 = ReducedPrinterParser.prototype; - - _proto2._getValue = function _getValue(context, value) { - var absValue = Math.abs(value); - var baseValue = this._baseValue; + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; - if (this._baseDate !== null) { - context.temporal(); - var chrono = IsoChronology.INSTANCE; - baseValue = chrono.date(this._baseDate).get(this._field); - } + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } - if (value >= baseValue && value < baseValue + EXCEED_POINTS[this._minWidth]) { - return absValue % EXCEED_POINTS[this._minWidth]; - } + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); - return absValue % EXCEED_POINTS[this._maxWidth]; - }; + var index = customRules.length; + customRules[index] = validate; - _proto2._setValue = function _setValue(context, value, errorPos, successPos) { - var baseValue = this._baseValue; + return { + code: 'customRule' + index, + validate: validate + }; + } +} - if (this._baseDate != null) { - var chrono = context.getEffectiveChronology(); - baseValue = chrono.date(this._baseDate).get(this._field); - } - var parseLen = successPos - errorPos; +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} - if (parseLen === this._minWidth && value >= 0) { - var range = EXCEED_POINTS[this._minWidth]; - var lastPart = baseValue % range; - var basePart = baseValue - lastPart; - if (baseValue > 0) { - value = basePart + value; - } else { - value = basePart - value; - } +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} - if (value < baseValue) { - value += range; - } - } - return context.setParsedField(this._field, value, errorPos, successPos); - }; +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i { - var totalSecs = MathUtil.safeToInt(offsetSecs); +"use strict"; - if (totalSecs === 0) { - buf.append(this.noOffsetText); - } else { - var absHours = Math.abs(MathUtil.intMod(MathUtil.intDiv(totalSecs, 3600), 100)); - var absMinutes = Math.abs(MathUtil.intMod(MathUtil.intDiv(totalSecs, 60), 60)); - var absSeconds = Math.abs(MathUtil.intMod(totalSecs, 60)); - var bufPos = buf.length(); - var output = absHours; - buf.append(totalSecs < 0 ? '-' : '+').appendChar(MathUtil.intDiv(absHours, 10) + '0').appendChar(MathUtil.intMod(absHours, 10) + '0'); - if (this.type >= 3 || this.type >= 1 && absMinutes > 0) { - buf.append(this.type % 2 === 0 ? ':' : '').appendChar(MathUtil.intDiv(absMinutes, 10) + '0').appendChar(absMinutes % 10 + '0'); - output += absMinutes; +var URI = __nccwpck_require__(71682) + , equal = __nccwpck_require__(28206) + , util = __nccwpck_require__(76578) + , SchemaObject = __nccwpck_require__(37605) + , traverse = __nccwpck_require__(52533); - if (this.type >= 7 || this.type >= 5 && absSeconds > 0) { - buf.append(this.type % 2 === 0 ? ':' : '').appendChar(MathUtil.intDiv(absSeconds, 10) + '0').appendChar(absSeconds % 10 + '0'); - output += absSeconds; - } - } +module.exports = resolve; - if (output === 0) { - buf.setLength(bufPos); - buf.append(this.noOffsetText); - } - } +resolve.normalizeId = normalizeId; +resolve.fullPath = getFullPath; +resolve.url = resolveUrl; +resolve.ids = resolveIds; +resolve.inlineRef = inlineRef; +resolve.schema = resolveSchema; - return true; - }; +/** + * [resolve and compile the references ($ref)] + * @this Ajv + * @param {Function} compile reference to schema compilation funciton (localCompile) + * @param {Object} root object with information about the root schema for the current schema + * @param {String} ref reference to resolve + * @return {Object|Function} schema object (if the schema can be inlined) or validation function + */ +function resolve(compile, root, ref) { + /* jshint validthis: true */ + var refVal = this._refs[ref]; + if (typeof refVal == 'string') { + if (this._refs[refVal]) refVal = this._refs[refVal]; + else return resolve.call(this, compile, root, refVal); + } - _proto.parse = function parse(context, text, position) { - var length = text.length; - var noOffsetLen = this.noOffsetText.length; + refVal = refVal || this._schemas[ref]; + if (refVal instanceof SchemaObject) { + return inlineRef(refVal.schema, this._opts.inlineRefs) + ? refVal.schema + : refVal.validate || this._compile(refVal); + } - if (noOffsetLen === 0) { - if (position === length) { - return context.setParsedField(ChronoField.OFFSET_SECONDS, 0, position, position); - } - } else { - if (position === length) { - return ~position; - } + var res = resolveSchema.call(this, root, ref); + var schema, v, baseId; + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } - if (context.subSequenceEquals(text, position, this.noOffsetText, 0, noOffsetLen)) { - return context.setParsedField(ChronoField.OFFSET_SECONDS, 0, position, position + noOffsetLen); - } - } + if (schema instanceof SchemaObject) { + v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); + } else if (schema !== undefined) { + v = inlineRef(schema, this._opts.inlineRefs) + ? schema + : compile.call(this, schema, root, undefined, baseId); + } - var sign = text[position]; + return v; +} - if (sign === '+' || sign === '-') { - var negative = sign === '-' ? -1 : 1; - var array = [0, 0, 0, 0]; - array[0] = position + 1; - if ((this._parseNumber(array, 1, text, true) || this._parseNumber(array, 2, text, this.type >= 3) || this._parseNumber(array, 3, text, false)) === false) { - var offsetSecs = MathUtil.safeZero(negative * (array[1] * 3600 + array[2] * 60 + array[3])); - return context.setParsedField(ChronoField.OFFSET_SECONDS, offsetSecs, position, array[0]); - } - } +/** + * Resolve schema, its root and baseId + * @this Ajv + * @param {Object} root root object with properties schema, refVal, refs + * @param {String} ref reference to resolve + * @return {Object} object with properties schema, root, baseId + */ +function resolveSchema(root, ref) { + /* jshint validthis: true */ + var p = URI.parse(ref) + , refPath = _getFullPath(p) + , baseId = getFullPath(this._getId(root.schema)); + if (Object.keys(root.schema).length === 0 || refPath !== baseId) { + var id = normalizeId(refPath); + var refVal = this._refs[id]; + if (typeof refVal == 'string') { + return resolveRecursive.call(this, root, refVal, p); + } else if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + root = refVal; + } else { + refVal = this._schemas[id]; + if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + if (id == normalizeId(ref)) + return { schema: refVal, root: root, baseId: baseId }; + root = refVal; + } else { + return; + } + } + if (!root.schema) return; + baseId = getFullPath(this._getId(root.schema)); + } + return getJsonPointer.call(this, p, baseId, root.schema, root); +} - if (noOffsetLen === 0) { - return context.setParsedField(ChronoField.OFFSET_SECONDS, 0, position, position + noOffsetLen); - } - return ~position; - }; +/* @this Ajv */ +function resolveRecursive(root, ref, parsedRef) { + /* jshint validthis: true */ + var res = resolveSchema.call(this, root, ref); + if (res) { + var schema = res.schema; + var baseId = res.baseId; + root = res.root; + var id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + return getJsonPointer.call(this, parsedRef, baseId, schema, root); + } +} - _proto._parseNumber = function _parseNumber(array, arrayIndex, parseText, required) { - if ((this.type + 3) / 2 < arrayIndex) { - return false; - } - var pos = array[0]; +var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); +/* @this Ajv */ +function getJsonPointer(parsedRef, baseId, schema, root) { + /* jshint validthis: true */ + parsedRef.fragment = parsedRef.fragment || ''; + if (parsedRef.fragment.slice(0,1) != '/') return; + var parts = parsedRef.fragment.split('/'); - if (this.type % 2 === 0 && arrayIndex > 1) { - if (pos + 1 > parseText.length || parseText[pos] !== ':') { - return required; + for (var i = 1; i < parts.length; i++) { + var part = parts[i]; + if (part) { + part = util.unescapeFragment(part); + schema = schema[part]; + if (schema === undefined) break; + var id; + if (!PREVENT_SCOPE_CHANGE[part]) { + id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + if (schema.$ref) { + var $ref = resolveUrl(baseId, schema.$ref); + var res = resolveSchema.call(this, root, $ref); + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; } - - pos++; - } - - if (pos + 2 > parseText.length) { - return required; - } - - var ch1 = parseText[pos++]; - var ch2 = parseText[pos++]; - - if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') { - return required; } + } + } + } + if (schema !== undefined && schema !== root.schema) + return { schema: schema, root: root, baseId: baseId }; +} - var value = (ch1.charCodeAt(0) - 48) * 10 + (ch2.charCodeAt(0) - 48); - if (value < 0 || value > 59) { - return required; - } +var SIMPLE_INLINED = util.toHash([ + 'type', 'format', 'pattern', + 'maxLength', 'minLength', + 'maxProperties', 'minProperties', + 'maxItems', 'minItems', + 'maximum', 'minimum', + 'uniqueItems', 'multipleOf', + 'required', 'enum' +]); +function inlineRef(schema, limit) { + if (limit === false) return false; + if (limit === undefined || limit === true) return checkNoRef(schema); + else if (limit) return countKeys(schema) <= limit; +} - array[arrayIndex] = value; - array[0] = pos; - return false; - }; - _proto.toString = function toString() { - var converted = this.noOffsetText.replace('\'', '\'\''); - return 'Offset(' + PATTERNS[this.type] + ',\'' + converted + '\')'; - }; +function checkNoRef(schema) { + var item; + if (Array.isArray(schema)) { + for (var i=0; i this._padWidth) { - throw new DateTimeException("Cannot print as output of " + len + " characters exceeds pad width of " + this._padWidth); - } +function _getFullPath(p) { + return URI.serialize(p).split('#')[0] + '#'; +} - for (var i = 0; i < this._padWidth - len; i++) { - buf.insert(preLen, this._padChar); - } - return true; - }; +var TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; +} - _proto.parse = function parse(context, text, position) { - var strict = context.isStrict(); - var caseSensitive = context.isCaseSensitive(); - assert(!(position > text.length)); - assert(position >= 0); - if (position === text.length) { - return ~position; - } +function resolveUrl(baseId, id) { + id = normalizeId(id); + return URI.resolve(baseId, id); +} - var endPos = position + this._padWidth; - if (endPos > text.length) { - if (strict) { - return ~position; - } +/* @this Ajv */ +function resolveIds(schema) { + var schemaId = normalizeId(this._getId(schema)); + var baseIds = {'': schemaId}; + var fullPaths = {'': getFullPath(schemaId, false)}; + var localRefs = {}; + var self = this; - endPos = text.length; + traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (jsonPtr === '') return; + var id = self._getId(sch); + var baseId = baseIds[parentJsonPtr]; + var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword; + if (keyIndex !== undefined) + fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex)); + + if (typeof id == 'string') { + id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); + + var refVal = self._refs[id]; + if (typeof refVal == 'string') refVal = self._refs[refVal]; + if (refVal && refVal.schema) { + if (!equal(sch, refVal.schema)) + throw new Error('id "' + id + '" resolves to more than one schema'); + } else if (id != normalizeId(fullPath)) { + if (id[0] == '#') { + if (localRefs[id] && !equal(sch, localRefs[id])) + throw new Error('id "' + id + '" resolves to more than one schema'); + localRefs[id] = sch; + } else { + self._refs[id] = fullPath; } + } + } + baseIds[jsonPtr] = baseId; + fullPaths[jsonPtr] = fullPath; + }); - var pos = position; - - while (pos < endPos && (caseSensitive ? text[pos] === this._padChar : context.charEquals(text[pos], this._padChar))) { - pos++; - } + return localRefs; +} - text = text.substring(0, endPos); - var resultPos = this._printerParser.parse(context, text, pos); +/***/ }), - if (resultPos !== endPos && strict) { - return ~(position + pos); - } +/***/ 68561: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return resultPos; - }; +"use strict"; - _proto.toString = function toString() { - return "Pad(" + this._printerParser + "," + this._padWidth + (this._padChar === ' ' ? ')' : ',\'' + this._padChar + '\')'); - }; - return PadPrinterParserDecorator; - }(); +var ruleModules = __nccwpck_require__(85810) + , toHash = __nccwpck_require__(76578).toHash; - var SettingsParser = function (_Enum) { - _inheritsLoose(SettingsParser, _Enum); +module.exports = function rules() { + var RULES = [ + { type: 'number', + rules: [ { 'maximum': ['exclusiveMaximum'] }, + { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, + { type: 'string', + rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, + { type: 'array', + rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, + { type: 'object', + rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', + { 'properties': ['additionalProperties', 'patternProperties'] } ] }, + { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } + ]; - function SettingsParser() { - return _Enum.apply(this, arguments) || this; - } + var ALL = [ 'type', '$comment' ]; + var KEYWORDS = [ + '$schema', '$id', 'id', '$data', '$async', 'title', + 'description', 'default', 'definitions', + 'examples', 'readOnly', 'writeOnly', + 'contentMediaType', 'contentEncoding', + 'additionalItems', 'then', 'else' + ]; + var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; + RULES.all = toHash(ALL); + RULES.types = toHash(TYPES); + + RULES.forEach(function (group) { + group.rules = group.rules.map(function (keyword) { + var implKeywords; + if (typeof keyword == 'object') { + var key = Object.keys(keyword)[0]; + implKeywords = keyword[key]; + keyword = key; + implKeywords.forEach(function (k) { + ALL.push(k); + RULES.all[k] = true; + }); + } + ALL.push(keyword); + var rule = RULES.all[keyword] = { + keyword: keyword, + code: ruleModules[keyword], + implements: implKeywords + }; + return rule; + }); - var _proto = SettingsParser.prototype; + RULES.all.$comment = { + keyword: '$comment', + code: ruleModules.$comment + }; - _proto.print = function print() { - return true; - }; + if (group.type) RULES.types[group.type] = group; + }); - _proto.parse = function parse(context, text, position) { - switch (this) { - case SettingsParser.SENSITIVE: - context.setCaseSensitive(true); - break; + RULES.keywords = toHash(ALL.concat(KEYWORDS)); + RULES.custom = {}; - case SettingsParser.INSENSITIVE: - context.setCaseSensitive(false); - break; + return RULES; +}; - case SettingsParser.STRICT: - context.setStrict(true); - break; - case SettingsParser.LENIENT: - context.setStrict(false); - break; - } +/***/ }), - return position; - }; +/***/ 37605: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.toString = function toString() { - switch (this) { - case SettingsParser.SENSITIVE: - return 'ParseCaseSensitive(true)'; +"use strict"; - case SettingsParser.INSENSITIVE: - return 'ParseCaseSensitive(false)'; - case SettingsParser.STRICT: - return 'ParseStrict(true)'; +var util = __nccwpck_require__(76578); - case SettingsParser.LENIENT: - return 'ParseStrict(false)'; - } - }; +module.exports = SchemaObject; - return SettingsParser; - }(Enum); - SettingsParser.SENSITIVE = new SettingsParser('SENSITIVE'); - SettingsParser.INSENSITIVE = new SettingsParser('INSENSITIVE'); - SettingsParser.STRICT = new SettingsParser('STRICT'); - SettingsParser.LENIENT = new SettingsParser('LENIENT'); +function SchemaObject(obj) { + util.copy(obj, this); +} - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var StringLiteralPrinterParser = function () { - function StringLiteralPrinterParser(literal) { - this._literal = literal; - } - var _proto = StringLiteralPrinterParser.prototype; +/***/ }), - _proto.print = function print(context, buf) { - buf.append(this._literal); - return true; - }; +/***/ 64580: +/***/ ((module) => { - _proto.parse = function parse(context, text, position) { - var length = text.length; - assert(!(position > length || position < 0)); +"use strict"; - if (context.subSequenceEquals(text, position, this._literal, 0, this._literal.length) === false) { - return ~position; - } - return position + this._literal.length; - }; +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +module.exports = function ucs2length(str) { + var length = 0 + , len = str.length + , pos = 0 + , value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; - _proto.toString = function toString() { - var converted = this._literal.replace("'", "''"); - return '\'' + converted + '\''; - }; +/***/ }), - return StringLiteralPrinterParser; - }(); +/***/ 76578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /* - * @copyright (c) 2016, Philipp Thürwächter, Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ZoneRulesProvider = function () { - function ZoneRulesProvider() {} +"use strict"; - ZoneRulesProvider.getRules = function getRules(zoneId) { - throw new DateTimeException('unsupported ZoneId:' + zoneId); - }; - ZoneRulesProvider.getAvailableZoneIds = function getAvailableZoneIds() { - return []; - }; - return ZoneRulesProvider; - }(); +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: __nccwpck_require__(28206), + ucs2length: __nccwpck_require__(64580), + varOccurences: varOccurences, + varReplace: varReplace, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} - var ZoneRegion = function (_ZoneId) { - _inheritsLoose(ZoneRegion, _ZoneId); - ZoneRegion.ofId = function ofId(zoneId) { - var rules = ZoneRulesProvider.getRules(zoneId); - return new ZoneRegion(zoneId, rules); - }; +function checkDataType(dataType, data, strictNumbers, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} - function ZoneRegion(id, rules) { - var _this; - _this = _ZoneId.call(this) || this; - _this._id = id; - _this._rules = rules; - return _this; +function checkDataTypes(dataTypes, data, strictNumbers) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); - var _proto = ZoneRegion.prototype; - - _proto.id = function id() { - return this._id; - }; - - _proto.rules = function rules() { - return this._rules; - }; - - return ZoneRegion; - }(ZoneId); + return code; + } +} - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ZoneIdPrinterParser = function () { - function ZoneIdPrinterParser(query, description) { - this.query = query; - this.description = description; - } - var _proto = ZoneIdPrinterParser.prototype; +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i length) { - return ~position; - } - if (position === length) { - return ~position; - } +function escapeQuotes(str) { + return str.replace(SINGLE_QUOTE, '\\$&') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\f/g, '\\f') + .replace(/\t/g, '\\t'); +} - var nextChar = text.charAt(position); - if (nextChar === '+' || nextChar === '-') { - var newContext = context.copy(); - var endPos = OffsetIdPrinterParser.INSTANCE_ID.parse(newContext, text, position); +function varOccurences(str, dataVar) { + dataVar += '[^0-9]'; + var matches = str.match(new RegExp(dataVar, 'g')); + return matches ? matches.length : 0; +} - if (endPos < 0) { - return endPos; - } - var offset = newContext.getParsed(ChronoField.OFFSET_SECONDS); - var zone = ZoneOffset.ofTotalSeconds(offset); - context.setParsedZone(zone); - return endPos; - } else if (length >= position + 2) { - var nextNextChar = text.charAt(position + 1); +function varReplace(str, dataVar, expr) { + dataVar += '([^0-9])'; + expr = expr.replace(/\$/g, '$$$$'); + return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); +} - if (context.charEquals(nextChar, 'U') && context.charEquals(nextNextChar, 'T')) { - if (length >= position + 3 && context.charEquals(text.charAt(position + 2), 'C')) { - return this._parsePrefixedOffset(context, text, position, position + 3); - } - return this._parsePrefixedOffset(context, text, position, position + 2); - } else if (context.charEquals(nextChar, 'G') && length >= position + 3 && context.charEquals(nextNextChar, 'M') && context.charEquals(text.charAt(position + 2), 'T')) { - return this._parsePrefixedOffset(context, text, position, position + 3); - } - } +function schemaHasRules(schema, rules) { + if (typeof schema == 'boolean') return !schema; + for (var key in schema) if (rules[key]) return true; +} - if (text.substr(position, 6) === 'SYSTEM') { - context.setParsedZone(ZoneId.systemDefault()); - return position + 6; - } - if (context.charEquals(nextChar, 'Z')) { - context.setParsedZone(ZoneOffset.UTC); - return position + 1; - } +function schemaHasRulesExcept(schema, rules, exceptKeyword) { + if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not'; + for (var key in schema) if (key != exceptKeyword && rules[key]) return true; +} - var availableZoneIds = ZoneRulesProvider.getAvailableZoneIds(); - if (zoneIdTree.size !== availableZoneIds.length) { - zoneIdTree = ZoneIdTree.createTreeMap(availableZoneIds); - } +function schemaUnknownRules(schema, rules) { + if (typeof schema == 'boolean') return; + for (var key in schema) if (!rules[key]) return key; +} - var maxParseLength = length - position; - var treeMap = zoneIdTree.treeMap; - var parsedZoneId = null; - var parseLength = 0; - while (treeMap != null) { - var parsedSubZoneId = text.substr(position, Math.min(treeMap.length, maxParseLength)); - treeMap = treeMap.get(parsedSubZoneId); +function toQuotedString(str) { + return '\'' + escapeQuotes(str) + '\''; +} - if (treeMap != null && treeMap.isLeaf) { - parsedZoneId = parsedSubZoneId; - parseLength = treeMap.length; - } - } - if (parsedZoneId != null) { - context.setParsedZone(ZoneRegion.ofId(parsedZoneId)); - return position + parseLength; - } +function getPathExpr(currentPath, expr, jsonPointers, isNumber) { + var path = jsonPointers // false by default + ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') + : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''); + return joinPaths(currentPath, path); +} - return ~position; - }; - _proto._parsePrefixedOffset = function _parsePrefixedOffset(context, text, prefixPos, position) { - var prefix = text.substring(prefixPos, position).toUpperCase(); - var newContext = context.copy(); +function getPath(currentPath, prop, jsonPointers) { + var path = jsonPointers // false by default + ? toQuotedString('/' + escapeJsonPointer(prop)) + : toQuotedString(getProperty(prop)); + return joinPaths(currentPath, path); +} - if (position < text.length && context.charEquals(text.charAt(position), 'Z')) { - context.setParsedZone(ZoneId.ofOffset(prefix, ZoneOffset.UTC)); - return position; - } - var endPos = OffsetIdPrinterParser.INSTANCE_ID.parse(newContext, text, position); +var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; +var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; +function getData($data, lvl, paths) { + var up, jsonPointer, data, matches; + if ($data === '') return 'rootData'; + if ($data[0] == '/') { + if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); + jsonPointer = $data; + data = 'rootData'; + } else { + matches = $data.match(RELATIVE_JSON_POINTER); + if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); + up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer == '#') { + if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } - if (endPos < 0) { - context.setParsedZone(ZoneId.ofOffset(prefix, ZoneOffset.UTC)); - return position; - } + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } - var offsetSecs = newContext.getParsed(ChronoField.OFFSET_SECONDS); - var offset = ZoneOffset.ofTotalSeconds(offsetSecs); - context.setParsedZone(ZoneId.ofOffset(prefix, offset)); - return endPos; - }; + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i this.length) { - var subZoneId = zoneId.substr(0, this.length); - var subTreeMap = this._treeMap[subZoneId]; +/***/ 21412: +/***/ ((module) => { - if (subTreeMap == null) { - subTreeMap = new ZoneIdTreeMap(idLength, false); - this._treeMap[subZoneId] = subTreeMap; - } +"use strict"; - subTreeMap.add(zoneId); - } - }; - _proto2.get = function get(zoneId) { - return this._treeMap[zoneId]; - }; +var KEYWORDS = [ + 'multipleOf', + 'maximum', + 'exclusiveMaximum', + 'minimum', + 'exclusiveMinimum', + 'maxLength', + 'minLength', + 'pattern', + 'additionalItems', + 'maxItems', + 'minItems', + 'uniqueItems', + 'maxProperties', + 'minProperties', + 'required', + 'additionalProperties', + 'enum', + 'format', + 'const' +]; - return ZoneIdTreeMap; - }(); +module.exports = function (metaSchema, keywordsJsonPointers) { + for (var i=0; i { - _proto.parseCaseSensitive = function parseCaseSensitive() { - this._appendInternalPrinterParser(SettingsParser.SENSITIVE); +"use strict"; - return this; - }; - _proto.parseCaseInsensitive = function parseCaseInsensitive() { - this._appendInternalPrinterParser(SettingsParser.INSENSITIVE); +var metaSchema = __nccwpck_require__(40038); - return this; - }; +module.exports = { + $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', + definitions: { + simpleTypes: metaSchema.definitions.simpleTypes + }, + type: 'object', + dependencies: { + schema: ['validate'], + $data: ['validate'], + statements: ['inline'], + valid: {not: {required: ['macro']}} + }, + properties: { + type: metaSchema.properties.type, + schema: {type: 'boolean'}, + statements: {type: 'boolean'}, + dependencies: { + type: 'array', + items: {type: 'string'} + }, + metaSchema: {type: 'object'}, + modifying: {type: 'boolean'}, + valid: {type: 'boolean'}, + $data: {type: 'boolean'}, + async: {type: 'boolean'}, + errors: { + anyOf: [ + {type: 'boolean'}, + {const: 'full'} + ] + } + } +}; - _proto.parseStrict = function parseStrict() { - this._appendInternalPrinterParser(SettingsParser.STRICT); - return this; - }; +/***/ }), - _proto.parseLenient = function parseLenient() { - this._appendInternalPrinterParser(SettingsParser.LENIENT); +/***/ 7404: +/***/ ((module) => { - return this; - }; +"use strict"; - _proto.appendValue = function appendValue() { - if (arguments.length === 1) { - return this._appendValue1.apply(this, arguments); - } else if (arguments.length === 2) { - return this._appendValue2.apply(this, arguments); +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; } else { - return this._appendValue4.apply(this, arguments); + $exclusive = false; + $opStr += '='; } - }; - - _proto._appendValue1 = function _appendValue1(field) { - requireNonNull(field); - - this._appendValuePrinterParser(new NumberPrinterParser(field, 1, MAX_WIDTH$1, SignStyle.NORMAL)); - - return this; - }; + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - _proto._appendValue2 = function _appendValue2(field, width) { - requireNonNull(field); - if (width < 1 || width > MAX_WIDTH$1) { - throw new IllegalArgumentException("The width must be from 1 to " + MAX_WIDTH$1 + " inclusive but was " + width); - } +/***/ }), - var pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE); +/***/ 64683: +/***/ ((module) => { - this._appendValuePrinterParser(pp); +"use strict"; - return this; - }; +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - _proto._appendValue4 = function _appendValue4(field, minWidth, maxWidth, signStyle) { - requireNonNull(field); - requireNonNull(signStyle); - if (minWidth === maxWidth && signStyle === SignStyle.NOT_NEGATIVE) { - return this._appendValue2(field, maxWidth); - } +/***/ }), - if (minWidth < 1 || minWidth > MAX_WIDTH$1) { - throw new IllegalArgumentException("The minimum width must be from 1 to " + MAX_WIDTH$1 + " inclusive but was " + minWidth); - } +/***/ 52114: +/***/ ((module) => { - if (maxWidth < 1 || maxWidth > MAX_WIDTH$1) { - throw new IllegalArgumentException("The minimum width must be from 1 to " + MAX_WIDTH$1 + " inclusive but was " + maxWidth); - } +"use strict"; - if (maxWidth < minWidth) { - throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " + maxWidth + " < " + minWidth); - } +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - var pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle); - this._appendValuePrinterParser(pp); +/***/ }), - return this; - }; +/***/ 71142: +/***/ ((module) => { - _proto.appendValueReduced = function appendValueReduced() { - if (arguments.length === 4 && arguments[3] instanceof ChronoLocalDate) { - return this._appendValueReducedFieldWidthMaxWidthBaseDate.apply(this, arguments); - } else { - return this._appendValueReducedFieldWidthMaxWidthBaseValue.apply(this, arguments); - } - }; +"use strict"; - _proto._appendValueReducedFieldWidthMaxWidthBaseValue = function _appendValueReducedFieldWidthMaxWidthBaseValue(field, width, maxWidth, baseValue) { - requireNonNull(field, 'field'); - var pp = new ReducedPrinterParser(field, width, maxWidth, baseValue, null); +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - this._appendValuePrinterParser(pp); - return this; - }; +/***/ }), - _proto._appendValueReducedFieldWidthMaxWidthBaseDate = function _appendValueReducedFieldWidthMaxWidthBaseDate(field, width, maxWidth, baseDate) { - requireNonNull(field, 'field'); - requireNonNull(baseDate, 'baseDate'); - requireInstance(baseDate, ChronoLocalDate, 'baseDate'); - var pp = new ReducedPrinterParser(field, width, maxWidth, 0, baseDate); +/***/ 89443: +/***/ ((module) => { - this._appendValuePrinterParser(pp); +"use strict"; - return this; - }; +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + return out; +} - _proto._appendValuePrinterParser = function _appendValuePrinterParser(pp) { - assert(pp != null); - if (this._active._valueParserIndex >= 0 && this._active._printerParsers[this._active._valueParserIndex] instanceof NumberPrinterParser) { - var activeValueParser = this._active._valueParserIndex; - var basePP = this._active._printerParsers[activeValueParser]; +/***/ }), - if (pp.minWidth() === pp.maxWidth() && pp.signStyle() === SignStyle.NOT_NEGATIVE) { - basePP = basePP.withSubsequentWidth(pp.maxWidth()); +/***/ 63093: +/***/ ((module) => { - this._appendInternal(pp.withFixedWidth()); +"use strict"; - this._active._valueParserIndex = activeValueParser; - } else { - basePP = basePP.withFixedWidth(); - this._active._valueParserIndex = this._appendInternal(pp); - } +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} - this._active._printerParsers[activeValueParser] = basePP; - } else { - this._active._valueParserIndex = this._appendInternal(pp); - } - return this; - }; +/***/ }), - _proto.appendFraction = function appendFraction(field, minWidth, maxWidth, decimalPoint) { - this._appendInternal(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint)); +/***/ 30134: +/***/ ((module) => { - return this; - }; +"use strict"; - _proto.appendInstant = function appendInstant(fractionalDigits) { - if (fractionalDigits === void 0) { - fractionalDigits = -2; - } +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; +} - if (fractionalDigits < -2 || fractionalDigits > 9) { - throw new IllegalArgumentException('Invalid fractional digits: ' + fractionalDigits); - } - this._appendInternal(new InstantPrinterParser(fractionalDigits)); +/***/ }), - return this; - }; +/***/ 1661: +/***/ ((module) => { - _proto.appendOffsetId = function appendOffsetId() { - this._appendInternal(OffsetIdPrinterParser.INSTANCE_ID); +"use strict"; - return this; - }; +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - _proto.appendOffset = function appendOffset(pattern, noOffsetText) { - this._appendInternalPrinterParser(new OffsetIdPrinterParser(noOffsetText, pattern)); - return this; - }; +/***/ }), - _proto.appendZoneId = function appendZoneId() { - this._appendInternal(new ZoneIdPrinterParser(TemporalQueries.zoneId(), 'ZoneId()')); +/***/ 55964: +/***/ ((module) => { - return this; - }; +"use strict"; - _proto.appendPattern = function appendPattern(pattern) { - requireNonNull(pattern, 'pattern'); +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} - this._parsePattern(pattern); - return this; - }; +/***/ }), - _proto.appendZoneText = function appendZoneText() { - throw new IllegalArgumentException('Pattern using (localized) text not implemented, use js-joda-locale plugin!'); - }; +/***/ 5912: +/***/ ((module) => { - _proto.appendText = function appendText() { - throw new IllegalArgumentException('Pattern using (localized) text not implemented, use js-joda-locale plugin!'); - }; +"use strict"; - _proto.appendLocalizedOffset = function appendLocalizedOffset() { - throw new IllegalArgumentException('Pattern using (localized) text not implemented, use js-joda-locale plugin!'); - }; +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' { - if (cur >= 'A' && cur <= 'Z' || cur >= 'a' && cur <= 'z') { - var start = pos++; +"use strict"; - for (; pos < pattern.length && pattern.charAt(pos) === cur; pos++) { +module.exports = function generate_dependencies(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $schemaDeps = {}, + $propertyDeps = {}, + $ownProperties = it.opts.ownProperties; + for ($property in $schema) { + if ($property == '__proto__') continue; + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } + out += 'var ' + ($errs) + ' = errors;'; + var $currentErrorPath = it.errorPath; + out += 'var missing' + ($lvl) + ';'; + for (var $property in $propertyDeps) { + $deps = $propertyDeps[$property]; + if ($deps.length) { + out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + if ($breakOnError) { + out += ' && ( '; + var arr1 = $deps; + if (arr1) { + var $propertyKey, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $propertyKey = arr1[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ')) { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } - - var count = pos - start; - - if (cur === 'p') { - var pad = 0; - - if (pos < pattern.length) { - cur = pattern.charAt(pos); - - if (cur >= 'A' && cur <= 'Z' || cur >= 'a' && cur <= 'z') { - pad = count; - start = pos++; - - for (; pos < pattern.length && pattern.charAt(pos) === cur; pos++) { - } - - count = pos - start; + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + out += ' ) { '; + var arr2 = $deps; + if (arr2) { + var $propertyKey, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $propertyKey = arr2[i2 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; } - - if (pad === 0) { - throw new IllegalArgumentException('Pad letter \'p\' must be followed by valid pad pattern: ' + pattern); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - - this.padNext(pad); + out += ' } '; + } else { + out += ' {} '; } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; + for (var $property in $schemaDeps) { + var $sch = $schemaDeps[$property]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} - var field = FIELD_MAP[cur]; - if (field != null) { - this._parseField(cur, count, field); - } else if (cur === 'z') { - if (count > 4) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } else if (count === 4) { - this.appendZoneText(TextStyle.FULL); - } else { - this.appendZoneText(TextStyle.SHORT); - } - } else if (cur === 'V') { - if (count !== 2) { - throw new IllegalArgumentException('Pattern letter count must be 2: ' + cur); - } +/***/ }), - this.appendZoneId(); - } else if (cur === 'Z') { - if (count < 4) { - this.appendOffset('+HHMM', '+0000'); - } else if (count === 4) { - this.appendLocalizedOffset(TextStyle.FULL); - } else if (count === 5) { - this.appendOffset('+HH:MM:ss', 'Z'); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } - } else if (cur === 'O') { - if (count === 1) { - this.appendLocalizedOffset(TextStyle.SHORT); - } else if (count === 4) { - this.appendLocalizedOffset(TextStyle.FULL); - } else { - throw new IllegalArgumentException('Pattern letter count must be 1 or 4: ' + cur); - } - } else if (cur === 'X') { - if (count > 5) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +/***/ 10163: +/***/ ((module) => { - this.appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count === 1 ? 0 : 1)], 'Z'); - } else if (cur === 'x') { - if (count > 5) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +"use strict"; - var zero = count === 1 ? '+00' : count % 2 === 0 ? '+0000' : '+00:00'; - this.appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count === 1 ? 0 : 1)], zero); - } else if (cur === 'W') { - if (count > 1) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - this.appendWeekField('W', count); - } else if (cur === 'w') { - if (count > 2) { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } - this.appendWeekField('w', count); - } else if (cur === 'Y') { - this.appendWeekField('Y', count); - } else { - throw new IllegalArgumentException('Unknown pattern letter: ' + cur); - } +/***/ }), - pos--; - } else if (cur === '\'') { - var _start = pos++; +/***/ 63847: +/***/ ((module) => { - for (; pos < pattern.length; pos++) { - if (pattern.charAt(pos) === '\'') { - if (pos + 1 < pattern.length && pattern.charAt(pos + 1) === '\'') { - pos++; - } else { - break; - } - } - } +"use strict"; - if (pos >= pattern.length) { - throw new IllegalArgumentException('Pattern ends with an incomplete string literal: ' + pattern); - } +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - var str = pattern.substring(_start + 1, pos); - if (str.length === 0) { - this.appendLiteral('\''); - } else { - this.appendLiteral(str.replace('\'\'', '\'')); - } - } else if (cur === '[') { - this.optionalStart(); - } else if (cur === ']') { - if (this._active._parent === null) { - throw new IllegalArgumentException('Pattern invalid as it contains ] without previous ['); - } +/***/ }), - this.optionalEnd(); - } else if (cur === '{' || cur === '}' || cur === '#') { - throw new IllegalArgumentException('Pattern includes reserved character: \'' + cur + '\''); - } else { - this.appendLiteral(cur); - } - } - }; +/***/ 80862: +/***/ ((module) => { - _proto._parseField = function _parseField(cur, count, field) { - switch (cur) { - case 'u': - case 'y': - if (count === 2) { - this.appendValueReduced(field, 2, 2, ReducedPrinterParser.BASE_DATE); - } else if (count < 4) { - this.appendValue(field, count, MAX_WIDTH$1, SignStyle.NORMAL); - } else { - this.appendValue(field, count, MAX_WIDTH$1, SignStyle.EXCEEDS_PAD); - } +"use strict"; - break; +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), + $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; + } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; + } + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} - case 'M': - case 'Q': - switch (count) { - case 1: - this.appendValue(field); - break; - case 2: - this.appendValue(field, 2); - break; +/***/ }), - case 3: - this.appendText(field, TextStyle.SHORT); - break; +/***/ 85810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case 4: - this.appendText(field, TextStyle.FULL); - break; +"use strict"; - case 5: - this.appendText(field, TextStyle.NARROW); - break; - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': __nccwpck_require__(42393), + allOf: __nccwpck_require__(89443), + anyOf: __nccwpck_require__(63093), + '$comment': __nccwpck_require__(30134), + const: __nccwpck_require__(1661), + contains: __nccwpck_require__(55964), + dependencies: __nccwpck_require__(2591), + 'enum': __nccwpck_require__(10163), + format: __nccwpck_require__(63847), + 'if': __nccwpck_require__(80862), + items: __nccwpck_require__(54408), + maximum: __nccwpck_require__(7404), + minimum: __nccwpck_require__(7404), + maxItems: __nccwpck_require__(64683), + minItems: __nccwpck_require__(64683), + maxLength: __nccwpck_require__(52114), + minLength: __nccwpck_require__(52114), + maxProperties: __nccwpck_require__(71142), + minProperties: __nccwpck_require__(71142), + multipleOf: __nccwpck_require__(39772), + not: __nccwpck_require__(60750), + oneOf: __nccwpck_require__(6106), + pattern: __nccwpck_require__(13912), + properties: __nccwpck_require__(52924), + propertyNames: __nccwpck_require__(19195), + required: __nccwpck_require__(8420), + uniqueItems: __nccwpck_require__(24995), + validate: __nccwpck_require__(49585) +}; + + +/***/ }), + +/***/ 54408: +/***/ ((module) => { - break; +"use strict"; - case 'L': - case 'q': - switch (count) { - case 1: - this.appendValue(field); - break; +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} - case 2: - this.appendValue(field, 2); - break; - case 3: - this.appendText(field, TextStyle.SHORT_STANDALONE); - break; +/***/ }), - case 4: - this.appendText(field, TextStyle.FULL_STANDALONE); - break; +/***/ 39772: +/***/ ((module) => { - case 5: - this.appendText(field, TextStyle.NARROW_STANDALONE); - break; +"use strict"; - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - break; - case 'e': - switch (count) { - case 1: - case 2: - this.appendWeekField('e', count); - break; +/***/ }), - case 3: - this.appendText(field, TextStyle.SHORT); - break; +/***/ 60750: +/***/ ((module) => { - case 4: - this.appendText(field, TextStyle.FULL); - break; +"use strict"; - case 5: - this.appendText(field, TextStyle.NARROW); - break; +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } - break; +/***/ }), - case 'c': - switch (count) { - case 1: - this.appendWeekField('c', count); - break; +/***/ 6106: +/***/ ((module) => { - case 2: - throw new IllegalArgumentException('Invalid number of pattern letters: ' + cur); +"use strict"; - case 3: - this.appendText(field, TextStyle.SHORT_STANDALONE); - break; +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} - case 4: - this.appendText(field, TextStyle.FULL_STANDALONE); - break; - case 5: - this.appendText(field, TextStyle.NARROW_STANDALONE); - break; +/***/ }), - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +/***/ 13912: +/***/ ((module) => { - break; +"use strict"; - case 'a': - if (count === 1) { - this.appendText(field, TextStyle.SHORT); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); - } +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} - break; - case 'E': - case 'G': - switch (count) { - case 1: - case 2: - case 3: - this.appendText(field, TextStyle.SHORT); - break; +/***/ }), - case 4: - this.appendText(field, TextStyle.FULL); - break; +/***/ 52924: +/***/ ((module) => { - case 5: - this.appendText(field, TextStyle.NARROW); - break; +"use strict"; - default: - throw new IllegalArgumentException('Too many pattern letters: ' + cur); +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}).filter(notProto), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties).filter(notProto), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { + return p !== '__proto__'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; } - - break; - - case 'S': - this.appendFraction(ChronoField.NANO_OF_SECOND, count, count, false); - break; - - case 'F': - if (count === 1) { - this.appendValue(field); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; } - - break; - - case 'd': - case 'h': - case 'H': - case 'k': - case 'K': - case 'm': - case 's': - if (count === 1) { - this.appendValue(field); - } else if (count === 2) { - this.appendValue(field, count); - } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - - break; - - case 'D': - if (count === 1) { - this.appendValue(field); - } else if (count <= 3) { - this.appendValue(field, count); + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - throw new IllegalArgumentException('Too many pattern letters: ' + cur); + out += ' validate.errors = [' + (__err) + ']; return false; '; } - - break; - - default: - if (count === 1) { - this.appendValue(field); + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; } else { - this.appendValue(field, count); + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } } - - break; - } - }; - - _proto.padNext = function padNext() { - if (arguments.length === 1) { - return this._padNext1.apply(this, arguments); - } else { - return this._padNext2.apply(this, arguments); + out += ' ' + ($code) + ' } '; + } } - }; - - _proto._padNext1 = function _padNext1(padWidth) { - return this._padNext2(padWidth, ' '); - }; - - _proto._padNext2 = function _padNext2(padWidth, padChar) { - if (padWidth < 1) { - throw new IllegalArgumentException('The pad width must be at least one but was ' + padWidth); + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; } - - this._active._padNextWidth = padWidth; - this._active._padNextChar = padChar; - this._active._valueParserIndex = -1; - return this; - }; - - _proto.optionalStart = function optionalStart() { - this._active._valueParserIndex = -1; - this._active = DateTimeFormatterBuilder._of(this._active, true); - return this; - }; - - _proto.optionalEnd = function optionalEnd() { - if (this._active._parent == null) { - throw new IllegalStateException('Cannot call optionalEnd() as there was no previous call to optionalStart()'); + } + } + } + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} - if (this._active._printerParsers.length > 0) { - var cpp = new CompositePrinterParser(this._active._printerParsers, this._active._optional); - this._active = this._active._parent; - this._appendInternal(cpp); - } else { - this._active = this._active._parent; - } +/***/ }), - return this; - }; +/***/ 19195: +/***/ ((module) => { - _proto._appendInternal = function _appendInternal(pp) { - assert(pp != null); +"use strict"; - if (this._active._padNextWidth > 0) { - if (pp != null) { - pp = new PadPrinterParserDecorator(pp, this._active._padNextWidth, this._active._padNextChar); - } +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' { - _proto.appendLiteral = function appendLiteral(literal) { - assert(literal != null); +"use strict"; - if (literal.length > 0) { - if (literal.length === 1) { - this._appendInternalPrinterParser(new CharLiteralPrinterParser(literal.charAt(0))); +module.exports = function generate_ref(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $async, $refCode; + if ($schema == '#' || $schema == '#/') { + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } + } else { + var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); + if ($refVal === undefined) { + var $message = it.MissingRefError.message(it.baseId, $schema); + if (it.opts.missingRefs == 'fail') { + it.logger.error($message); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; + } + if (it.opts.verbose) { + out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - this._appendInternalPrinterParser(new StringLiteralPrinterParser(literal)); - } - } - - return this; - }; - - _proto._appendInternalPrinterParser = function _appendInternalPrinterParser(pp) { - assert(pp != null); - - if (this._active._padNextWidth > 0) { - if (pp != null) { - pp = new PadPrinterParserDecorator(pp, this._active._padNextWidth, this._active._padNextChar); + out += ' validate.errors = [' + (__err) + ']; return false; '; } - - this._active._padNextWidth = 0; - this._active._padNextChar = 0; + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - - this._active._printerParsers.push(pp); - - this._active._valueParserIndex = -1; - return this._active._printerParsers.length - 1; - }; - - _proto.append = function append(formatter) { - requireNonNull(formatter, 'formatter'); - - this._appendInternal(formatter._toPrinterParser(false)); - - return this; - }; - - _proto.toFormatter = function toFormatter(resolverStyle) { - if (resolverStyle === void 0) { - resolverStyle = ResolverStyle.SMART; + if ($breakOnError) { + out += ' if (false) { '; } - - while (this._active._parent != null) { - this.optionalEnd(); + } else if (it.opts.missingRefs == 'ignore') { + it.logger.warn($message); + if ($breakOnError) { + out += ' if (true) { '; } - - var pp = new CompositePrinterParser(this._printerParsers, false); - return new DateTimeFormatter(pp, null, DecimalStyle.STANDARD, resolverStyle, null, null, null); - }; - - return DateTimeFormatterBuilder; - }(); - var SECONDS_PER_10000_YEARS = 146097 * 25 * 86400; - var SECONDS_0000_TO_1970 = (146097 * 5 - (30 * 365 + 7)) * 86400; - - var InstantPrinterParser = function () { - function InstantPrinterParser(fractionalDigits) { - this.fractionalDigits = fractionalDigits; + } else { + throw new it.MissingRefError(it.baseId, $schema, $message); + } + } else if ($refVal.inline) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $refVal.schema; + $it.schemaPath = ''; + $it.errSchemaPath = $schema; + var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); + out += ' ' + ($code) + ' '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; } + } else { + $async = $refVal.$async === true || (it.async && $refVal.$async !== false); + $refCode = $refVal.code; + } + } + if ($refCode) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + if (it.opts.passContext) { + out += ' ' + ($refCode) + '.call(this, '; + } else { + out += ' ' + ($refCode) + '( '; + } + out += ' ' + ($data) + ', (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; + var __callValidate = out; + out = $$outStack.pop(); + if ($async) { + if (!it.async) throw new Error('async schema referenced by sync schema'); + if ($breakOnError) { + out += ' var ' + ($valid) + '; '; + } + out += ' try { await ' + (__callValidate) + '; '; + if ($breakOnError) { + out += ' ' + ($valid) + ' = true; '; + } + out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; '; + if ($breakOnError) { + out += ' ' + ($valid) + ' = false; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + } + } else { + out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' else { '; + } + } + } + return out; +} - var _proto2 = InstantPrinterParser.prototype; - - _proto2.print = function print(context, buf) { - var inSecs = context.getValue(ChronoField.INSTANT_SECONDS); - var inNanos = 0; - - if (context.temporal().isSupported(ChronoField.NANO_OF_SECOND)) { - inNanos = context.temporal().getLong(ChronoField.NANO_OF_SECOND); - } - if (inSecs == null) { - return false; - } +/***/ }), - var inSec = inSecs; - var inNano = ChronoField.NANO_OF_SECOND.checkValidIntValue(inNanos); +/***/ 8420: +/***/ ((module) => { - if (inSec >= -SECONDS_0000_TO_1970) { - var zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970; - var hi = MathUtil.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1; - var lo = MathUtil.floorMod(zeroSecs, SECONDS_PER_10000_YEARS); - var ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC); +"use strict"; - if (hi > 0) { - buf.append('+').append(hi); +module.exports = function generate_required(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $vSchema = 'schema' + $lvl; + if (!$isData) { + if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { + var $required = []; + var arr1 = $schema; + if (arr1) { + var $property, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $property = arr1[i1 += 1]; + var $propertySch = it.schema.properties[$property]; + if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { + $required[$required.length] = $property; } - - buf.append(ldt); - - if (ldt.second() === 0) { - buf.append(':00'); + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; } else { - var _zeroSecs = inSec + SECONDS_0000_TO_1970; - - var _hi = MathUtil.intDiv(_zeroSecs, SECONDS_PER_10000_YEARS); - - var _lo = MathUtil.intMod(_zeroSecs, SECONDS_PER_10000_YEARS); - - var _ldt = LocalDateTime.ofEpochSecond(_lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC); - - var pos = buf.length(); - buf.append(_ldt); - - if (_ldt.second() === 0) { - buf.append(':00'); + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } - - if (_hi < 0) { - if (_ldt.year() === -10000) { - buf.replace(pos, pos + 2, '' + (_hi - 1)); - } else if (_lo === 0) { - buf.insert(pos, _hi); + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; } else { - buf.insert(pos + 1, Math.abs(_hi)); + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - - if (this.fractionalDigits === -2) { - if (inNano !== 0) { - buf.append('.'); - - if (MathUtil.intMod(inNano, 1000000) === 0) { - buf.append(('' + (MathUtil.intDiv(inNano, 1000000) + 1000)).substring(1)); - } else if (MathUtil.intMod(inNano, 1000) === 0) { - buf.append(('' + (MathUtil.intDiv(inNano, 1000) + 1000000)).substring(1)); + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; } else { - buf.append(('' + (inNano + 1000000000)).substring(1)); + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } + out += '\' '; } - } else if (this.fractionalDigits > 0 || this.fractionalDigits === -1 && inNano > 0) { - buf.append('.'); - var div = 100000000; - - for (var i = 0; this.fractionalDigits === -1 && inNano > 0 || i < this.fractionalDigits; i++) { - var digit = MathUtil.intDiv(inNano, div); - buf.append(digit); - inNano = inNano - digit * div; - div = MathUtil.intDiv(div, 10); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } + out += ' } '; + } else { + out += ' {} '; } - - buf.append('Z'); - return true; - }; - - _proto2.parse = function parse(context, text, position) { - var newContext = context.copy(); - var minDigits = this.fractionalDigits < 0 ? 0 : this.fractionalDigits; - var maxDigits = this.fractionalDigits < 0 ? 9 : this.fractionalDigits; - - var parser = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T').appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':').appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(ChronoField.SECOND_OF_MINUTE, 2).appendFraction(ChronoField.NANO_OF_SECOND, minDigits, maxDigits, true).appendLiteral('Z').toFormatter()._toPrinterParser(false); - - var pos = parser.parse(newContext, text, position); - - if (pos < 0) { - return pos; - } - - var yearParsed = newContext.getParsed(ChronoField.YEAR); - var month = newContext.getParsed(ChronoField.MONTH_OF_YEAR); - var day = newContext.getParsed(ChronoField.DAY_OF_MONTH); - var hour = newContext.getParsed(ChronoField.HOUR_OF_DAY); - var min = newContext.getParsed(ChronoField.MINUTE_OF_HOUR); - var secVal = newContext.getParsed(ChronoField.SECOND_OF_MINUTE); - var nanoVal = newContext.getParsed(ChronoField.NANO_OF_SECOND); - var sec = secVal != null ? secVal : 0; - var nano = nanoVal != null ? nanoVal : 0; - var year = MathUtil.intMod(yearParsed, 10000); - var days = 0; - - if (hour === 24 && min === 0 && sec === 0 && nano === 0) { - hour = 0; - days = 1; - } else if (hour === 23 && min === 59 && sec === 60) { - context.setParsedLeapSecond(); - sec = 59; + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; } - - var instantSecs; - - try { - var ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0).plusDays(days); - instantSecs = ldt.toEpochSecond(ZoneOffset.UTC); - instantSecs += MathUtil.safeMultiply(MathUtil.intDiv(yearParsed, 10000), SECONDS_PER_10000_YEARS); - } catch (ex) { - return ~position; + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } } - - var successPos = pos; - successPos = context.setParsedField(ChronoField.INSTANT_SECONDS, instantSecs, position, successPos); - return context.setParsedField(ChronoField.NANO_OF_SECOND, nano, position, successPos); - }; - - _proto2.toString = function toString() { - return 'Instant()'; - }; - - return InstantPrinterParser; - }(); - - function _init$9() { - ReducedPrinterParser.BASE_DATE = LocalDate.of(2000, 1, 1); - DateTimeFormatterBuilder.CompositePrinterParser = CompositePrinterParser; - DateTimeFormatterBuilder.PadPrinterParserDecorator = PadPrinterParserDecorator; - DateTimeFormatterBuilder.SettingsParser = SettingsParser; - DateTimeFormatterBuilder.CharLiteralPrinterParser = StringLiteralPrinterParser; - DateTimeFormatterBuilder.StringLiteralPrinterParser = StringLiteralPrinterParser; - DateTimeFormatterBuilder.CharLiteralPrinterParser = CharLiteralPrinterParser; - DateTimeFormatterBuilder.NumberPrinterParser = NumberPrinterParser; - DateTimeFormatterBuilder.ReducedPrinterParser = ReducedPrinterParser; - DateTimeFormatterBuilder.FractionPrinterParser = FractionPrinterParser; - DateTimeFormatterBuilder.OffsetIdPrinterParser = OffsetIdPrinterParser; - DateTimeFormatterBuilder.ZoneIdPrinterParser = ZoneIdPrinterParser; - } - - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var StringBuilder = function () { - function StringBuilder() { - this._str = ''; } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} - var _proto = StringBuilder.prototype; - - _proto.append = function append(str) { - this._str += str; - return this; - }; - - _proto.appendChar = function appendChar(str) { - this._str += str[0]; - return this; - }; - - _proto.insert = function insert(offset, str) { - this._str = this._str.slice(0, offset) + str + this._str.slice(offset); - return this; - }; - - _proto.replace = function replace(start, end, str) { - this._str = this._str.slice(0, start) + str + this._str.slice(end); - return this; - }; - - _proto.length = function length() { - return this._str.length; - }; - - _proto.setLength = function setLength(length) { - this._str = this._str.slice(0, length); - return this; - }; - - _proto.toString = function toString() { - return this._str; - }; - - return StringBuilder; - }(); - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var DateTimeFormatter = function () { - DateTimeFormatter.parsedExcessDays = function parsedExcessDays() { - return DateTimeFormatter.PARSED_EXCESS_DAYS; - }; +/***/ }), - DateTimeFormatter.parsedLeapSecond = function parsedLeapSecond() { - return DateTimeFormatter.PARSED_LEAP_SECOND; - }; +/***/ 24995: +/***/ ((module) => { - DateTimeFormatter.ofPattern = function ofPattern(pattern) { - return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(); - }; +"use strict"; - function DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone) { - if (chrono === void 0) { - chrono = IsoChronology.INSTANCE; +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); } - - assert(printerParser != null); - assert(decimalStyle != null); - assert(resolverStyle != null); - this._printerParser = printerParser; - this._locale = locale; - this._decimalStyle = decimalStyle; - this._resolverStyle = resolverStyle; - this._resolverFields = resolverFields; - this._chrono = chrono; - this._zone = zone; + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} - var _proto = DateTimeFormatter.prototype; - _proto.locale = function locale() { - return this._locale; - }; +/***/ }), - _proto.decimalStyle = function decimalStyle() { - return this._decimalStyle; - }; +/***/ 49585: +/***/ ((module) => { - _proto.chronology = function chronology() { - return this._chrono; - }; +"use strict"; - _proto.withChronology = function withChronology(chrono) { - if (this._chrono != null && this._chrono.equals(chrono)) { - return this; +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; } - - return new DateTimeFormatter(this._printerParser, this._locale, this._decimalStyle, this._resolverStyle, this._resolverFields, chrono, this._zone); - }; - - _proto.withLocale = function withLocale() { - return this; - }; - - _proto.withResolverStyle = function withResolverStyle(resolverStyle) { - requireNonNull(resolverStyle, 'resolverStyle'); - - if (resolverStyle.equals(this._resolverStyle)) { - return this; + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - - return new DateTimeFormatter(this._printerParser, this._locale, this._decimalStyle, resolverStyle, this._resolverFields, this._chrono, this._zone); - }; - - _proto.format = function format(temporal) { - var buf = new StringBuilder(32); - - this._formatTo(temporal, buf); - - return buf.toString(); - }; - - _proto._formatTo = function _formatTo(temporal, appendable) { - requireNonNull(temporal, 'temporal'); - requireNonNull(appendable, 'appendable'); - var context = new DateTimePrintContext(temporal, this); - - this._printerParser.print(context, appendable); - }; - - _proto.parse = function parse(text, type) { - if (arguments.length === 1) { - return this.parse1(text); + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - return this.parse2(text, type); + out += ' validate.errors = [' + (__err) + ']; return false; '; } - }; - - _proto.parse1 = function parse1(text) { - requireNonNull(text, 'text'); - - try { - return this._parseToBuilder(text, null).resolve(this._resolverStyle, this._resolverFields); - } catch (ex) { - if (ex instanceof DateTimeParseException) { - throw ex; + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [""]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if (it.schema.$comment && it.opts.$comment) { + out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; + } + out += ' if (' + ($coerced) + ' !== undefined) ; '; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($type == 'string') { + out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' else { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); } else { - throw this._createError(text, ex); + out += '' + ($typeSchema); } - } - }; - - _proto.parse2 = function parse2(text, type) { - requireNonNull(text, 'text'); - requireNonNull(type, 'type'); - - try { - var builder = this._parseToBuilder(text, null).resolve(this._resolverStyle, this._resolverFields); - - return builder.build(type); - } catch (ex) { - if (ex instanceof DateTimeParseException) { - throw ex; + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - throw this._createError(text, ex); + out += ' validate.errors = [' + (__err) + ']; return false; '; } - } - }; - - _proto._createError = function _createError(text, ex) { - var abbr = ''; - - if (text.length > 64) { - abbr = text.substring(0, 64) + '...'; } else { - abbr = text; + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - - return new DateTimeParseException('Text \'' + abbr + '\' could not be parsed: ' + ex.message, text, 0, ex); - }; - - _proto._parseToBuilder = function _parseToBuilder(text, position) { - var pos = position != null ? position : new ParsePosition(0); - - var result = this._parseUnresolved0(text, pos); - - if (result == null || pos.getErrorIndex() >= 0 || position == null && pos.getIndex() < text.length) { - var abbr = ''; - - if (text.length > 64) { - abbr = text.substr(0, 64).toString() + '...'; + out += ' } if (' + ($coerced) + ' !== undefined) { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); } else { - abbr = text; + out += '' + ($typeSchema); } - - if (pos.getErrorIndex() >= 0) { - throw new DateTimeParseException('Text \'' + abbr + '\' could not be parsed at index ' + pos.getErrorIndex(), text, pos.getErrorIndex()); - } else { - throw new DateTimeParseException('Text \'' + abbr + '\' could not be parsed, unparsed text found at index ' + pos.getIndex(), text, pos.getIndex()); + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; } - } - - return result.toBuilder(); - }; - - _proto.parseUnresolved = function parseUnresolved(text, position) { - return this._parseUnresolved0(text, position); - }; - - _proto._parseUnresolved0 = function _parseUnresolved0(text, position) { - assert(text != null, 'text', NullPointerException); - assert(position != null, 'position', NullPointerException); - var context = new DateTimeParseContext(this); - var pos = position.getIndex(); - pos = this._printerParser.parse(context, text, pos); - - if (pos < 0) { - position.setErrorIndex(~pos); - return null; - } - - position.setIndex(pos); - return context.toParsed(); - }; - - _proto._toPrinterParser = function _toPrinterParser(optional) { - return this._printerParser.withOptional(optional); - }; - - _proto.toString = function toString() { - var pattern = this._printerParser.toString(); - - return pattern.indexOf('[') === 0 ? pattern : pattern.substring(1, pattern.length - 1); - }; - - return DateTimeFormatter; - }(); - function _init$a() { - DateTimeFormatter.ISO_LOCAL_DATE = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-').appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-').appendValue(ChronoField.DAY_OF_MONTH, 2).toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_LOCAL_TIME = new DateTimeFormatterBuilder().appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':').appendValue(ChronoField.MINUTE_OF_HOUR, 2).optionalStart().appendLiteral(':').appendValue(ChronoField.SECOND_OF_MINUTE, 2).optionalStart().appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true).toFormatter(ResolverStyle.STRICT); - DateTimeFormatter.ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T').append(DateTimeFormatter.ISO_LOCAL_TIME).toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_INSTANT = new DateTimeFormatterBuilder().parseCaseInsensitive().appendInstant().toFormatter(ResolverStyle.STRICT); - DateTimeFormatter.ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE_TIME).appendOffsetId().toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_ZONED_DATE_TIME = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_OFFSET_DATE_TIME).optionalStart().appendLiteral('[').parseCaseSensitive().appendZoneId().appendLiteral(']').toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.BASIC_ISO_DATE = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendValue(ChronoField.MONTH_OF_YEAR, 2).appendValue(ChronoField.DAY_OF_MONTH, 2).toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_OFFSET_DATE = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).appendOffsetId().toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_OFFSET_TIME = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_TIME).appendOffsetId().toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); - DateTimeFormatter.ISO_ORDINAL_DATE = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-').appendValue(ChronoField.DAY_OF_YEAR).toFormatter(ResolverStyle.STRICT); - DateTimeFormatter.ISO_WEEK_DATE = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-W').appendValue(ChronoField.ALIGNED_WEEK_OF_YEAR).appendLiteral('-').appendValue(ChronoField.DAY_OF_WEEK).toFormatter(ResolverStyle.STRICT); - DateTimeFormatter.PARSED_EXCESS_DAYS = createTemporalQuery('PARSED_EXCESS_DAYS', function (temporal) { - if (temporal instanceof DateTimeBuilder) { - return temporal.excessDays; + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; } else { - return Period.ZERO; - } - }); - DateTimeFormatter.PARSED_LEAP_SECOND = createTemporalQuery('PARSED_LEAP_SECOND', function (temporal) { - if (temporal instanceof DateTimeBuilder) { - return temporal.leapSecond; + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } } else { - return false; + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - }); + } + out += ' } '; } - - var MonthDay = function (_TemporalAccessor) { - _inheritsLoose(MonthDay, _TemporalAccessor); - - MonthDay.now = function now(zoneIdOrClock) { - if (arguments.length === 0) { - return MonthDay.now0(); - } else if (arguments.length === 1 && zoneIdOrClock instanceof ZoneId) { - return MonthDay.nowZoneId(zoneIdOrClock); - } else { - return MonthDay.nowClock(zoneIdOrClock); + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; + } + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + ($code) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } } - }; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }; return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } - MonthDay.now0 = function now0() { - return this.nowClock(Clock.systemDefaultZone()); - }; + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } - MonthDay.nowZoneId = function nowZoneId(zone) { - requireNonNull(zone, 'zone'); - return this.nowClock(Clock.system(zone)); - }; + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } - MonthDay.nowClock = function nowClock(clock) { - requireNonNull(clock, 'clock'); - var now = LocalDate.now(clock); - return MonthDay.of(now.month(), now.dayOfMonth()); - }; + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} - MonthDay.of = function of(monthOrNumber, number) { - if (arguments.length === 2 && monthOrNumber instanceof Month) { - return MonthDay.ofMonthNumber(monthOrNumber, number); - } else { - return MonthDay.ofNumberNumber(monthOrNumber, number); - } - }; - MonthDay.ofMonthNumber = function ofMonthNumber(month, dayOfMonth) { - requireNonNull(month, 'month'); - ChronoField.DAY_OF_MONTH.checkValidValue(dayOfMonth); +/***/ }), - if (dayOfMonth > month.maxLength()) { - throw new DateTimeException('Illegal value for DayOfMonth field, value ' + dayOfMonth + ' is not valid for month ' + month.toString()); - } +/***/ 53297: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return new MonthDay(month.value(), dayOfMonth); - }; +"use strict"; - MonthDay.ofNumberNumber = function ofNumberNumber(month, dayOfMonth) { - requireNonNull(month, 'month'); - requireNonNull(dayOfMonth, 'dayOfMonth'); - return MonthDay.of(Month.of(month), dayOfMonth); - }; - MonthDay.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - requireInstance(temporal, TemporalAccessor, 'temporal'); +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = __nccwpck_require__(5912); +var definitionSchema = __nccwpck_require__(10458); - if (temporal instanceof MonthDay) { - return temporal; - } +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; - try { - return MonthDay.of(temporal.get(ChronoField.MONTH_OF_YEAR), temporal.get(ChronoField.DAY_OF_MONTH)); - } catch (ex) { - throw new DateTimeException('Unable to obtain MonthDay from TemporalAccessor: ' + temporal + ', type ' + (temporal && temporal.constructor != null ? temporal.constructor.name : '')); - } - }; - MonthDay.parse = function parse(text, formatter) { - if (arguments.length === 1) { - return MonthDay.parseString(text); - } else { - return MonthDay.parseStringFormatter(text, formatter); - } - }; +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); - MonthDay.parseString = function parseString(text) { - return MonthDay.parseStringFormatter(text, PARSER); - }; + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); - MonthDay.parseStringFormatter = function parseStringFormatter(text, formatter) { - requireNonNull(text, 'text'); - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.parse(text, MonthDay.FROM); - }; + if (definition) { + this.validateKeyword(definition, true); - function MonthDay(month, dayOfMonth) { - var _this; + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i { - var day = Math.min(this._day, month.maxLength()); - return new MonthDay(month.value(), day); - }; +"use strict"; +/* module decorator */ module = __nccwpck_require__.nmd(module); - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - if (dayOfMonth === this._day) { - return this; - } - return MonthDay.of(this._month, dayOfMonth); - }; +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - requireInstance(_query, TemporalQuery, 'query'); +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; - return _TemporalAccessor.prototype.query.call(this, _query); - }; +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - temporal = temporal.with(ChronoField.MONTH_OF_YEAR, this._month); - return temporal.with(ChronoField.DAY_OF_MONTH, Math.min(temporal.range(ChronoField.DAY_OF_MONTH).maximum(), this._day)); - }; +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); - _proto.atYear = function atYear(year) { - return LocalDate.of(year, this._month, this.isValidYear(year) ? this._day : 28); - }; + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, MonthDay, 'other'); - var cmp = this._month - other.monthValue(); + return value; + }, + enumerable: true, + configurable: true + }); +}; - if (cmp === 0) { - cmp = this._day - other.dayOfMonth(); - } +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = __nccwpck_require__(86931); + } - return cmp; - }; + const offset = isBackground ? 10 : 0; + const styles = {}; - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - requireInstance(other, MonthDay, 'other'); - return this.compareTo(other) > 0; - }; + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - requireInstance(other, MonthDay, 'other'); - return this.compareTo(other) < 0; - }; + return styles; +}; - _proto.equals = function equals(obj) { - if (this === obj) { - return true; - } +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], - if (obj instanceof MonthDay) { - var other = obj; - return this.monthValue() === other.monthValue() && this.dayOfMonth() === other.dayOfMonth(); - } + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], - return false; - }; + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; - _proto.toString = function toString() { - return '--' + (this._month < 10 ? '0' : '') + this._month + (this._day < 10 ? '-0' : '-') + this._day; - }; + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - _proto.toJSON = function toJSON() { - return this.toString(); - }; + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.format(this); - }; + group[styleName] = styles[styleName]; - return MonthDay; - }(TemporalAccessor); - var PARSER; - function _init$b() { - PARSER = new DateTimeFormatterBuilder().appendLiteral('--').appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-').appendValue(ChronoField.DAY_OF_MONTH, 2).toFormatter(); - MonthDay.FROM = createTemporalQuery('MonthDay.FROM', function (temporal) { - return MonthDay.from(temporal); - }); - } + codes.set(style[0], style[1]); + } - var YearMonth = function (_Temporal) { - _inheritsLoose(YearMonth, _Temporal); + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } - YearMonth.now = function now(zoneIdOrClock) { - if (arguments.length === 0) { - return YearMonth.now0(); - } else if (arguments.length === 1 && zoneIdOrClock instanceof ZoneId) { - return YearMonth.nowZoneId(zoneIdOrClock); - } else { - return YearMonth.nowClock(zoneIdOrClock); - } - }; + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); - YearMonth.now0 = function now0() { - return YearMonth.nowClock(Clock.systemDefaultZone()); - }; + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; - YearMonth.nowZoneId = function nowZoneId(zone) { - return YearMonth.nowClock(Clock.system(zone)); - }; + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - YearMonth.nowClock = function nowClock(clock) { - var now = LocalDate.now(clock); - return YearMonth.of(now.year(), now.month()); - }; + return styles; +} - YearMonth.of = function of(year, monthOrNumber) { - if (arguments.length === 2 && monthOrNumber instanceof Month) { - return YearMonth.ofNumberMonth(year, monthOrNumber); - } else { - return YearMonth.ofNumberNumber(year, monthOrNumber); - } - }; +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); - YearMonth.ofNumberMonth = function ofNumberMonth(year, month) { - requireNonNull(month, 'month'); - requireInstance(month, Month, 'month'); - return YearMonth.ofNumberNumber(year, month.value()); - }; - YearMonth.ofNumberNumber = function ofNumberNumber(year, month) { - requireNonNull(year, 'year'); - requireNonNull(month, 'month'); - ChronoField.YEAR.checkValidValue(year); - ChronoField.MONTH_OF_YEAR.checkValidValue(month); - return new YearMonth(year, month); - }; +/***/ }), - YearMonth.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); +/***/ 64808: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (temporal instanceof YearMonth) { - return temporal; - } +"use strict"; - try { - return YearMonth.of(temporal.get(ChronoField.YEAR), temporal.get(ChronoField.MONTH_OF_YEAR)); - } catch (ex) { - throw new DateTimeException('Unable to obtain YearMonth from TemporalAccessor: ' + temporal + ', type ' + (temporal && temporal.constructor != null ? temporal.constructor.name : '')); - } - }; - YearMonth.parse = function parse(text, formatter) { - if (arguments.length === 1) { - return YearMonth.parseString(text); - } else { - return YearMonth.parseStringFormatter(text, formatter); - } - }; +var lib = __nccwpck_require__(98035); +module.exports = lib(__dirname); - YearMonth.parseString = function parseString(text) { - return YearMonth.parseStringFormatter(text, PARSER$1); - }; +/***/ }), - YearMonth.parseStringFormatter = function parseStringFormatter(text, formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, YearMonth.FROM); - }; +/***/ 98035: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function YearMonth(year, month) { - var _this; +"use strict"; - _this = _Temporal.call(this) || this; - _this._year = MathUtil.safeToInt(year); - _this._month = MathUtil.safeToInt(month); - return _this; - } - var _proto = YearMonth.prototype; +module.exports = function(dirname) { + var path = __nccwpck_require__(85622); + var resolve = __nccwpck_require__(15619); + var appRootPath = resolve(dirname); - _proto.isSupported = function isSupported(fieldOrUnit) { - if (arguments.length === 1 && fieldOrUnit instanceof TemporalField) { - return this.isSupportedField(fieldOrUnit); - } else { - return this.isSupportedUnit(fieldOrUnit); - } - }; + var publicInterface = { + resolve: function(pathToModule) { + return path.join(appRootPath, pathToModule); + }, - _proto.isSupportedField = function isSupportedField(field) { - if (field instanceof ChronoField) { - return field === ChronoField.YEAR || field === ChronoField.MONTH_OF_YEAR || field === ChronoField.PROLEPTIC_MONTH || field === ChronoField.YEAR_OF_ERA || field === ChronoField.ERA; - } + require: function(pathToModule) { + return require(publicInterface.resolve(pathToModule)); + }, - return field != null && field.isSupportedBy(this); - }; + toString: function() { + return appRootPath; + }, - _proto.isSupportedUnit = function isSupportedUnit(unit) { - if (unit instanceof ChronoUnit) { - return unit === ChronoUnit.MONTHS || unit === ChronoUnit.YEARS || unit === ChronoUnit.DECADES || unit === ChronoUnit.CENTURIES || unit === ChronoUnit.MILLENNIA || unit === ChronoUnit.ERAS; - } + setPath: function(explicitlySetPath) { + appRootPath = path.resolve(explicitlySetPath); + publicInterface.path = appRootPath; + }, - return unit != null && unit.isSupportedBy(this); - }; + path: appRootPath + }; - _proto.range = function range(field) { - if (field === ChronoField.YEAR_OF_ERA) { - return this.year() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE); - } + return publicInterface; +}; - return _Temporal.prototype.range.call(this, field); - }; +/***/ }), - _proto.get = function get(field) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; +/***/ 15619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); +"use strict"; - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.MONTH_OF_YEAR: - return this._month; - case ChronoField.PROLEPTIC_MONTH: - return this._getProlepticMonth(); +// Dependencies +var path = __nccwpck_require__(85622); - case ChronoField.YEAR_OF_ERA: - return this._year < 1 ? 1 - this._year : this._year; +// Load global paths +var globalPaths = __nccwpck_require__(32282).globalPaths; - case ChronoField.YEAR: - return this._year; +// Guess at NPM's global install dir +var npmGlobalPrefix; +if ('win32' === process.platform) { + npmGlobalPrefix = path.dirname(process.execPath); +} else { + npmGlobalPrefix = path.dirname(path.dirname(process.execPath)); +} +var npmGlobalModuleDir = path.resolve(npmGlobalPrefix, 'lib', 'node_modules'); - case ChronoField.ERA: - return this._year < 1 ? 0 : 1; - } +// Save OS-specific path separator +var sep = path.sep; - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +// If we're in webpack, force it to use the original require() method +var requireFunction = ( true) + ? eval("require") + : 0; - return field.getFrom(this); - }; +const isInstalledWithPNPM = function(resolved) { + const pnpmDir = sep + '.pnpm'; - _proto._getProlepticMonth = function _getProlepticMonth() { - return MathUtil.safeAdd(MathUtil.safeMultiply(this._year, 12), this._month - 1); - }; + for (const globalPath of globalPaths) { + if (-1 !== globalPath.indexOf(pnpmDir) && -1 !== resolved.indexOf(pnpmDir)) { + return true; + } + } + return false; +} - _proto.year = function year() { - return this._year; - }; +const getFirstPartFromNodeModules = function(resolved) { + const nodeModulesDir = sep + 'node_modules'; - _proto.monthValue = function monthValue() { - return this._month; - }; + if (-1 !== resolved.indexOf(nodeModulesDir)) { + const parts = resolved.split(nodeModulesDir); + if (parts.length) { + return parts[0]; + } + } - _proto.month = function month() { - return Month.of(this._month); - }; + return null; +} - _proto.isLeapYear = function isLeapYear() { - return IsoChronology.isLeapYear(this._year); - }; +// Resolver +module.exports = function resolve(dirname) { + // Check for environmental variable + if (process.env.APP_ROOT_PATH) { + return path.resolve(process.env.APP_ROOT_PATH); + } - _proto.isValidDay = function isValidDay(dayOfMonth) { - return dayOfMonth >= 1 && dayOfMonth <= this.lengthOfMonth(); - }; - - _proto.lengthOfMonth = function lengthOfMonth() { - return this.month().length(this.isLeapYear()); - }; + // Defer to Yarn Plug'n'Play if enabled + if (process.versions.pnp) { + try { + var pnp = requireFunction('pnpapi'); + return pnp.getPackageInformation(pnp.topLevel).packageLocation; + } catch (e) {} + } - _proto.lengthOfYear = function lengthOfYear() { - return this.isLeapYear() ? 366 : 365; - }; + // Defer to main process in electron renderer + if ('undefined' !== typeof window && window.process && 'renderer' === window.process.type) { + try { + var remote = requireFunction('electron').remote; + return remote.require('app-root-path').path; + } catch (e) {} + } - _proto.with = function _with(adjusterOrField, value) { - if (arguments.length === 1) { - return this.withAdjuster(adjusterOrField); - } else { - return this.withFieldValue(adjusterOrField, value); - } - }; + // Defer to AWS Lambda when executing there + if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) { + return process.env.LAMBDA_TASK_ROOT; + } - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; + var resolved = path.resolve(dirname); + var alternateMethod = false; + var appRootPath = null; - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); + // Check if the globalPaths contain some folders with '.pnpm' in the path + // If yes this means it is most likely installed with pnpm + if (isInstalledWithPNPM(resolved)) { + appRootPath = getFirstPartFromNodeModules(resolved); - if (field instanceof ChronoField) { - var f = field; - f.checkValidValue(newValue); + if (appRootPath) { + return appRootPath; + } + } - switch (f) { - case ChronoField.MONTH_OF_YEAR: - return this.withMonth(newValue); + // Make sure that we're not loaded from a global include path + // Eg. $HOME/.node_modules + // $HOME/.node_libraries + // $PREFIX/lib/node + globalPaths.forEach(function(globalPath) { + if (!alternateMethod && 0 === resolved.indexOf(globalPath)) { + alternateMethod = true; + } + }); - case ChronoField.PROLEPTIC_MONTH: - return this.plusMonths(newValue - this.getLong(ChronoField.PROLEPTIC_MONTH)); + // If the app-root-path library isn't loaded globally, + // and node_modules exists in the path, just split __dirname + if (!alternateMethod) { + appRootPath = getFirstPartFromNodeModules(resolved); + } - case ChronoField.YEAR_OF_ERA: - return this.withYear(this._year < 1 ? 1 - newValue : newValue); + // If the above didn't work, or this module is loaded globally, then + // resort to require.main.filename (See http://nodejs.org/api/modules.html) + if (alternateMethod || null == appRootPath) { + appRootPath = path.dirname(requireFunction.main.filename); + } - case ChronoField.YEAR: - return this.withYear(newValue); + // Handle global bin/ directory edge-case + if (alternateMethod && -1 !== appRootPath.indexOf(npmGlobalModuleDir) && (appRootPath.length - 4) === appRootPath.indexOf(sep + 'bin')) { + appRootPath = appRootPath.slice(0, -4); + } - case ChronoField.ERA: - return this.getLong(ChronoField.ERA) === newValue ? this : this.withYear(1 - this._year); - } + // Return + return appRootPath; +}; - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - return field.adjustInto(this, newValue); - }; +/***/ }), - _proto.withYear = function withYear(year) { - ChronoField.YEAR.checkValidValue(year); - return new YearMonth(year, this._month); - }; +/***/ 83278: +/***/ ((module) => { - _proto.withMonth = function withMonth(month) { - ChronoField.MONTH_OF_YEAR.checkValidValue(month); - return new YearMonth(this._year, month); - }; +"use strict"; - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.addTo(this); - }; - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit, 'unit'); +function isArguments (thingy) { + return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') +} - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.MONTHS: - return this.plusMonths(amountToAdd); +var types = { + '*': {label: 'any', check: function () { return true }}, + A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }}, + S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }}, + N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }}, + F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }}, + O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }}, + B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }}, + E: {label: 'error', check: function (thingy) { return thingy instanceof Error }}, + Z: {label: 'null', check: function (thingy) { return thingy == null }} +} - case ChronoUnit.YEARS: - return this.plusYears(amountToAdd); +function addSchema (schema, arity) { + var group = arity[schema.length] = arity[schema.length] || [] + if (group.indexOf(schema) === -1) group.push(schema) +} - case ChronoUnit.DECADES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 10)); +var validate = module.exports = function (rawSchemas, args) { + if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) + if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') + if (!args) throw missingRequiredArg(1, 'args') + if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) + if (!types.A.check(args)) throw invalidType(1, ['array'], args) + var schemas = rawSchemas.split('|') + var arity = {} - case ChronoUnit.CENTURIES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 100)); + schemas.forEach(function (schema) { + for (var ii = 0; ii < schema.length; ++ii) { + var type = schema[ii] + if (!types[type]) throw unknownType(ii, type) + } + if (/E.*E/.test(schema)) throw moreThanOneError(schema) + addSchema(schema, arity) + if (/E/.test(schema)) { + addSchema(schema.replace(/E.*$/, 'E'), arity) + addSchema(schema.replace(/E/, 'Z'), arity) + if (schema.length === 1) addSchema('', arity) + } + }) + var matching = arity[args.length] + if (!matching) { + throw wrongNumberOfArgs(Object.keys(arity), args.length) + } + for (var ii = 0; ii < args.length; ++ii) { + var newMatching = matching.filter(function (schema) { + var type = schema[ii] + var typeCheck = types[type].check + return typeCheck(args[ii]) + }) + if (!newMatching.length) { + var labels = matching.map(function (schema) { + return types[schema[ii]].label + }).filter(function (schema) { return schema != null }) + throw invalidType(ii, labels, args[ii]) + } + matching = newMatching + } +} - case ChronoUnit.MILLENNIA: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 1000)); +function missingRequiredArg (num) { + return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) +} - case ChronoUnit.ERAS: - return this.with(ChronoField.ERA, MathUtil.safeAdd(this.getLong(ChronoField.ERA), amountToAdd)); - } +function unknownType (num, type) { + return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) +} - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +function invalidType (num, expectedTypes, value) { + var valueType + Object.keys(types).forEach(function (typeCode) { + if (types[typeCode].check(value)) valueType = types[typeCode].label + }) + return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + + englishList(expectedTypes) + ' but got ' + valueType) +} - return unit.addTo(this, amountToAdd); - }; +function englishList (list) { + return list.join(', ').replace(/, ([^,]+)$/, ' or $1') +} - _proto.plusYears = function plusYears(yearsToAdd) { - if (yearsToAdd === 0) { - return this; - } +function wrongNumberOfArgs (expected, got) { + var english = englishList(expected) + var args = expected.every(function (ex) { return ex.length === 1 }) + ? 'argument' + : 'arguments' + return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) +} - var newYear = ChronoField.YEAR.checkValidIntValue(this._year + yearsToAdd); - return this.withYear(newYear); - }; +function moreThanOneError (schema) { + return newException('ETOOMANYERRORTYPES', + 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') +} - _proto.plusMonths = function plusMonths(monthsToAdd) { - if (monthsToAdd === 0) { - return this; - } +function newException (code, msg) { + var e = new Error(msg) + e.code = code + if (Error.captureStackTrace) Error.captureStackTrace(e, validate) + return e +} - var monthCount = this._year * 12 + (this._month - 1); - var calcMonths = monthCount + monthsToAdd; - var newYear = ChronoField.YEAR.checkValidIntValue(MathUtil.floorDiv(calcMonths, 12)); - var newMonth = MathUtil.floorMod(calcMonths, 12) + 1; - return new YearMonth(newYear, newMonth); - }; - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; +/***/ }), - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return amountToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plusAmountUnit(MathUtil.MAX_SAFE_INTEGER, unit).plusAmountUnit(1, unit) : this.plusAmountUnit(-amountToSubtract, unit); - }; +/***/ 11083: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _proto.minusYears = function minusYears(yearsToSubtract) { - return yearsToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plusYears(MathUtil.MIN_SAFE_INTEGER).plusYears(1) : this.plusYears(-yearsToSubtract); - }; +"use strict"; - _proto.minusMonths = function minusMonths(monthsToSubtract) { - return monthsToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plusMonths(Math.MAX_SAFE_INTEGER).plusMonths(1) : this.plusMonths(-monthsToSubtract); - }; +exports.TrackerGroup = __nccwpck_require__(60660) +exports.Tracker = __nccwpck_require__(8074) +exports.TrackerStream = __nccwpck_require__(31375) - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - requireInstance(_query, TemporalQuery, 'query'); - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.MONTHS; - } else if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } +/***/ }), - return _Temporal.prototype.query.call(this, _query); - }; +/***/ 10165: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - requireInstance(temporal, Temporal, 'temporal'); - return temporal.with(ChronoField.PROLEPTIC_MONTH, this._getProlepticMonth()); - }; +"use strict"; - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - requireInstance(endExclusive, Temporal, 'endExclusive'); - requireInstance(unit, TemporalUnit, 'unit'); - var end = YearMonth.from(endExclusive); +var EventEmitter = __nccwpck_require__(28614).EventEmitter +var util = __nccwpck_require__(31669) - if (unit instanceof ChronoUnit) { - var monthsUntil = end._getProlepticMonth() - this._getProlepticMonth(); +var trackerId = 0 +var TrackerBase = module.exports = function (name) { + EventEmitter.call(this) + this.id = ++trackerId + this.name = name +} +util.inherits(TrackerBase, EventEmitter) - switch (unit) { - case ChronoUnit.MONTHS: - return monthsUntil; - case ChronoUnit.YEARS: - return monthsUntil / 12; +/***/ }), - case ChronoUnit.DECADES: - return monthsUntil / 120; +/***/ 60660: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case ChronoUnit.CENTURIES: - return monthsUntil / 1200; +"use strict"; - case ChronoUnit.MILLENNIA: - return monthsUntil / 12000; +var util = __nccwpck_require__(31669) +var TrackerBase = __nccwpck_require__(10165) +var Tracker = __nccwpck_require__(8074) +var TrackerStream = __nccwpck_require__(31375) - case ChronoUnit.ERAS: - return end.getLong(ChronoField.ERA) - this.getLong(ChronoField.ERA); - } +var TrackerGroup = module.exports = function (name) { + TrackerBase.call(this, name) + this.parentGroup = null + this.trackers = [] + this.completion = {} + this.weight = {} + this.totalWeight = 0 + this.finished = false + this.bubbleChange = bubbleChange(this) +} +util.inherits(TrackerGroup, TrackerBase) - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +function bubbleChange (trackerGroup) { + return function (name, completed, tracker) { + trackerGroup.completion[tracker.id] = completed + if (trackerGroup.finished) return + trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup) + } +} - return unit.between(this, end); - }; +TrackerGroup.prototype.nameInTree = function () { + var names = [] + var from = this + while (from) { + names.unshift(from.name) + from = from.parentGroup + } + return names.join('/') +} - _proto.atDay = function atDay(dayOfMonth) { - return LocalDate.of(this._year, this._month, dayOfMonth); - }; +TrackerGroup.prototype.addUnit = function (unit, weight) { + if (unit.addUnit) { + var toTest = this + while (toTest) { + if (unit === toTest) { + throw new Error( + 'Attempted to add tracker group ' + + unit.name + ' to tree that already includes it ' + + this.nameInTree(this)) + } + toTest = toTest.parentGroup + } + unit.parentGroup = this + } + this.weight[unit.id] = weight || 1 + this.totalWeight += this.weight[unit.id] + this.trackers.push(unit) + this.completion[unit.id] = unit.completed() + unit.on('change', this.bubbleChange) + if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit) + return unit +} - _proto.atEndOfMonth = function atEndOfMonth() { - return LocalDate.of(this._year, this._month, this.lengthOfMonth()); - }; +TrackerGroup.prototype.completed = function () { + if (this.trackers.length === 0) return 0 + var valPerWeight = 1 / this.totalWeight + var completed = 0 + for (var ii = 0; ii < this.trackers.length; ii++) { + var trackerId = this.trackers[ii].id + completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId] + } + return completed +} - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, YearMonth, 'other'); - var cmp = this._year - other.year(); +TrackerGroup.prototype.newGroup = function (name, weight) { + return this.addUnit(new TrackerGroup(name), weight) +} - if (cmp === 0) { - cmp = this._month - other.monthValue(); - } +TrackerGroup.prototype.newItem = function (name, todo, weight) { + return this.addUnit(new Tracker(name, todo), weight) +} - return cmp; - }; +TrackerGroup.prototype.newStream = function (name, todo, weight) { + return this.addUnit(new TrackerStream(name, todo), weight) +} - _proto.isAfter = function isAfter(other) { - return this.compareTo(other) > 0; - }; +TrackerGroup.prototype.finish = function () { + this.finished = true + if (!this.trackers.length) this.addUnit(new Tracker(), 1, true) + for (var ii = 0; ii < this.trackers.length; ii++) { + var tracker = this.trackers[ii] + tracker.finish() + tracker.removeListener('change', this.bubbleChange) + } + this.emit('change', this.name, 1, this) +} - _proto.isBefore = function isBefore(other) { - return this.compareTo(other) < 0; - }; +var buffer = ' ' +TrackerGroup.prototype.debug = function (depth) { + depth = depth || 0 + var indent = depth ? buffer.substr(0, depth) : '' + var output = indent + (this.name || 'top') + ': ' + this.completed() + '\n' + this.trackers.forEach(function (tracker) { + if (tracker instanceof TrackerGroup) { + output += tracker.debug(depth + 1) + } else { + output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n' + } + }) + return output +} - _proto.equals = function equals(obj) { - if (this === obj) { - return true; - } - if (obj instanceof YearMonth) { - var other = obj; - return this.year() === other.year() && this.monthValue() === other.monthValue(); - } +/***/ }), - return false; - }; +/***/ 31375: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.toString = function toString() { - return PARSER$1.format(this); - }; +"use strict"; - _proto.toJSON = function toJSON() { - return this.toString(); - }; +var util = __nccwpck_require__(31669) +var stream = __nccwpck_require__(51642) +var delegate = __nccwpck_require__(61318) +var Tracker = __nccwpck_require__(8074) - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; +var TrackerStream = module.exports = function (name, size, options) { + stream.Transform.call(this, options) + this.tracker = new Tracker(name, size) + this.name = name + this.id = this.tracker.id + this.tracker.on('change', delegateChange(this)) +} +util.inherits(TrackerStream, stream.Transform) - return YearMonth; - }(Temporal); - var PARSER$1; - function _init$c() { - PARSER$1 = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-').appendValue(ChronoField.MONTH_OF_YEAR, 2).toFormatter(); - YearMonth.FROM = createTemporalQuery('YearMonth.FROM', function (temporal) { - return YearMonth.from(temporal); - }); - } +function delegateChange (trackerStream) { + return function (name, completion, tracker) { + trackerStream.emit('change', name, completion, trackerStream) + } +} - var Year = function (_Temporal) { - _inheritsLoose(Year, _Temporal); +TrackerStream.prototype._transform = function (data, encoding, cb) { + this.tracker.completeWork(data.length ? data.length : 1) + this.push(data) + cb() +} - function Year(value) { - var _this; +TrackerStream.prototype._flush = function (cb) { + this.tracker.finish() + cb() +} - _this = _Temporal.call(this) || this; - _this._year = MathUtil.safeToInt(value); - return _this; - } +delegate(TrackerStream.prototype, 'tracker') + .method('completed') + .method('addWork') + .method('finish') - var _proto = Year.prototype; - _proto.value = function value() { - return this._year; - }; +/***/ }), - Year.now = function now(zoneIdOrClock) { - if (zoneIdOrClock === void 0) { - zoneIdOrClock = undefined; - } +/***/ 8074: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (zoneIdOrClock === undefined) { - return Year.now0(); - } else if (zoneIdOrClock instanceof ZoneId) { - return Year.nowZoneId(zoneIdOrClock); - } else { - return Year.nowClock(zoneIdOrClock); - } - }; +"use strict"; - Year.now0 = function now0() { - return Year.nowClock(Clock.systemDefaultZone()); - }; +var util = __nccwpck_require__(31669) +var TrackerBase = __nccwpck_require__(10165) - Year.nowZoneId = function nowZoneId(zone) { - requireNonNull(zone, 'zone'); - requireInstance(zone, ZoneId, 'zone'); - return Year.nowClock(Clock.system(zone)); - }; +var Tracker = module.exports = function (name, todo) { + TrackerBase.call(this, name) + this.workDone = 0 + this.workTodo = todo || 0 +} +util.inherits(Tracker, TrackerBase) - Year.nowClock = function nowClock(clock) { - requireNonNull(clock, 'clock'); - requireInstance(clock, Clock, 'clock'); - var now = LocalDate.now(clock); - return Year.of(now.year()); - }; +Tracker.prototype.completed = function () { + return this.workTodo === 0 ? 0 : this.workDone / this.workTodo +} - Year.of = function of(isoYear) { - requireNonNull(isoYear, 'isoYear'); - ChronoField.YEAR.checkValidValue(isoYear); - return new Year(isoYear); - }; +Tracker.prototype.addWork = function (work) { + this.workTodo += work + this.emit('change', this.name, this.completed(), this) +} - Year.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - requireInstance(temporal, TemporalAccessor, 'temporal'); +Tracker.prototype.completeWork = function (work) { + this.workDone += work + if (this.workDone > this.workTodo) this.workDone = this.workTodo + this.emit('change', this.name, this.completed(), this) +} - if (temporal instanceof Year) { - return temporal; - } +Tracker.prototype.finish = function () { + this.workTodo = this.workDone = 1 + this.emit('change', this.name, 1, this) +} - try { - return Year.of(temporal.get(ChronoField.YEAR)); - } catch (ex) { - throw new DateTimeException('Unable to obtain Year from TemporalAccessor: ' + temporal + ', type ' + (temporal && temporal.constructor != null ? temporal.constructor.name : '')); - } - }; - Year.parse = function parse(text, formatter) { - if (arguments.length <= 1) { - return Year.parseText(text); - } else { - return Year.parseTextFormatter(text, formatter); - } - }; +/***/ }), - Year.parseText = function parseText(text) { - requireNonNull(text, 'text'); - return Year.parse(text, PARSER$2); - }; +/***/ 99348: +/***/ ((module) => { - Year.parseTextFormatter = function parseTextFormatter(text, formatter) { - if (formatter === void 0) { - formatter = PARSER$2; - } +// Copyright 2011 Mark Cavage All rights reserved. - requireNonNull(text, 'text'); - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.parse(text, Year.FROM); - }; - Year.isLeap = function isLeap(year) { - return MathUtil.intMod(year, 4) === 0 && (MathUtil.intMod(year, 100) !== 0 || MathUtil.intMod(year, 400) === 0); - }; +module.exports = { - _proto.isSupported = function isSupported(fieldOrUnit) { - if (arguments.length === 1 && fieldOrUnit instanceof TemporalField) { - return this.isSupportedField(fieldOrUnit); - } else { - return this.isSupportedUnit(fieldOrUnit); - } - }; + newInvalidAsn1Error: function (msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } - _proto.isSupportedField = function isSupportedField(field) { - if (field instanceof ChronoField) { - return field === ChronoField.YEAR || field === ChronoField.YEAR_OF_ERA || field === ChronoField.ERA; - } +}; - return field != null && field.isSupportedBy(this); - }; - _proto.isSupportedUnit = function isSupportedUnit(unit) { - if (unit instanceof ChronoUnit) { - return unit === ChronoUnit.YEARS || unit === ChronoUnit.DECADES || unit === ChronoUnit.CENTURIES || unit === ChronoUnit.MILLENNIA || unit === ChronoUnit.ERAS; - } +/***/ }), - return unit != null && unit.isSupportedBy(this); - }; +/***/ 194: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.range = function range(field) { - if (this.isSupported(field)) { - return field.range(); - } else if (field instanceof ChronoField) { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +// Copyright 2011 Mark Cavage All rights reserved. - return _Temporal.prototype.range.call(this, field); - }; +var errors = __nccwpck_require__(99348); +var types = __nccwpck_require__(42473); - _proto.get = function get(field) { - return this.range(field).checkValidIntValue(this.getLong(field), field); - }; +var Reader = __nccwpck_require__(20290); +var Writer = __nccwpck_require__(43200); - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.YEAR_OF_ERA: - return this._year < 1 ? 1 - this._year : this._year; +// --- Exports - case ChronoField.YEAR: - return this._year; +module.exports = { - case ChronoField.ERA: - return this._year < 1 ? 0 : 1; - } + Reader: Reader, - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } + Writer: Writer - return field.getFrom(this); - }; +}; - _proto.isLeap = function isLeap() { - return Year.isLeap(this._year); - }; +for (var t in types) { + if (types.hasOwnProperty(t)) + module.exports[t] = types[t]; +} +for (var e in errors) { + if (errors.hasOwnProperty(e)) + module.exports[e] = errors[e]; +} - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); +/***/ }), - if (field instanceof ChronoField) { - field.checkValidValue(newValue); +/***/ 20290: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - switch (field) { - case ChronoField.YEAR_OF_ERA: - return Year.of(this._year < 1 ? 1 - newValue : newValue); +// Copyright 2011 Mark Cavage All rights reserved. - case ChronoField.YEAR: - return Year.of(newValue); +var assert = __nccwpck_require__(42357); +var Buffer = __nccwpck_require__(15118).Buffer; - case ChronoField.ERA: - return this.getLong(ChronoField.ERA) === newValue ? this : Year.of(1 - this._year); - } +var ASN1 = __nccwpck_require__(42473); +var errors = __nccwpck_require__(99348); - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } - return field.adjustInto(this, newValue); - }; +// --- Globals - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.addTo(this); - }; +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(amountToAdd, 'amountToAdd'); - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit, 'unit'); - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.YEARS: - return this.plusYears(amountToAdd); - case ChronoUnit.DECADES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 10)); +// --- API - case ChronoUnit.CENTURIES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 100)); +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) + throw new TypeError('data must be a node Buffer'); - case ChronoUnit.MILLENNIA: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 1000)); + this._buf = data; + this._size = data.length; - case ChronoUnit.ERAS: - return this.with(ChronoField.ERA, MathUtil.safeAdd(this.getLong(ChronoField.ERA), amountToAdd)); - } + // These hold the "current" state + this._len = 0; + this._offset = 0; +} - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function () { return (this._len); } +}); - return unit.addTo(this, amountToAdd); - }; +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function () { return (this._offset); } +}); - _proto.plusYears = function plusYears(yearsToAdd) { - if (yearsToAdd === 0) { - return this; - } +Object.defineProperty(Reader.prototype, 'remain', { + get: function () { return (this._size - this._offset); } +}); - return Year.of(ChronoField.YEAR.checkValidIntValue(MathUtil.safeAdd(this._year, yearsToAdd))); - }; +Object.defineProperty(Reader.prototype, 'buffer', { + get: function () { return (this._buf.slice(this._offset)); } +}); - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - requireInstance(amount, TemporalAmount, 'amount'); - return amount.subtractFrom(this); - }; - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(amountToSubtract, 'amountToSubtract'); - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit, 'unit'); - return amountToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plus(MathUtil.MAX_SAFE_INTEGER, unit).plus(1, unit) : this.plus(-amountToSubtract, unit); - }; +/** + * Reads a single byte and advances offset; you can pass in `true` to make this + * a "peek" operation (i.e., get the byte, but don't advance the offset). + * + * @param {Boolean} peek true means don't move offset. + * @return {Number} the next byte, null if not enough data. + */ +Reader.prototype.readByte = function (peek) { + if (this._size - this._offset < 1) + return null; - _proto.minusYears = function minusYears(yearsToSubtract) { - return yearsToSubtract === MathUtil.MIN_SAFE_INTEGER ? this.plusYears(MathUtil.MAX_SAFE_INTEGER).plusYears(1) : this.plusYears(-yearsToSubtract); - }; + var b = this._buf[this._offset] & 0xff; - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - return temporal.with(ChronoField.YEAR, this._year); - }; + if (!peek) + this._offset += 1; - _proto.isValidMonthDay = function isValidMonthDay(monthDay) { - return monthDay != null && monthDay.isValidYear(this._year); - }; + return b; +}; - _proto.length = function length() { - return this.isLeap() ? 366 : 365; - }; - _proto.atDay = function atDay(dayOfYear) { - return LocalDate.ofYearDay(this._year, dayOfYear); - }; +Reader.prototype.peek = function () { + return this.readByte(true); +}; - _proto.atMonth = function atMonth(monthOrNumber) { - if (arguments.length === 1 && monthOrNumber instanceof Month) { - return this.atMonthMonth(monthOrNumber); - } else { - return this.atMonthNumber(monthOrNumber); - } - }; - _proto.atMonthMonth = function atMonthMonth(month) { - requireNonNull(month, 'month'); - requireInstance(month, Month, 'month'); - return YearMonth.of(this._year, month); - }; +/** + * Reads a (potentially) variable length off the BER buffer. This call is + * not really meant to be called directly, as callers have to manipulate + * the internal buffer afterwards. + * + * As a result of this call, you can call `Reader.length`, until the + * next thing called that does a readLength. + * + * @return {Number} the amount of offset to advance the buffer. + * @throws {InvalidAsn1Error} on bad ASN.1 + */ +Reader.prototype.readLength = function (offset) { + if (offset === undefined) + offset = this._offset; - _proto.atMonthNumber = function atMonthNumber(month) { - requireNonNull(month, 'month'); - return YearMonth.of(this._year, month); - }; + if (offset >= this._size) + return null; - _proto.atMonthDay = function atMonthDay(monthDay) { - requireNonNull(monthDay, 'monthDay'); - requireInstance(monthDay, MonthDay, 'monthDay'); - return monthDay.atYear(this._year); - }; + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) + return null; - _proto.query = function query(_query) { - requireNonNull(_query, 'query()'); - requireInstance(_query, TemporalQuery, 'query()'); + if ((lenB & 0x80) === 0x80) { + lenB &= 0x7f; - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.YEARS; - } else if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } + if (lenB === 0) + throw newInvalidAsn1Error('Indefinite length not supported'); - return _Temporal.prototype.query.call(this, _query); - }; + if (lenB > 4) + throw newInvalidAsn1Error('encoding too long'); - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, Year, 'other'); - return this._year - other._year; - }; + if (this._size - offset < lenB) + return null; - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - requireInstance(other, Year, 'other'); - return this._year > other._year; - }; + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - requireInstance(other, Year, 'other'); - return this._year < other._year; - }; + } else { + // Wasn't a variable length + this._len = lenB; + } - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return formatter.format(this); - }; + return offset; +}; - _proto.equals = function equals(other) { - if (this === other) { - return true; - } - if (other instanceof Year) { - return this.value() === other.value(); - } +/** + * Parses the next sequence in this BER buffer. + * + * To get the length of the sequence, call `Reader.length`. + * + * @return {Number} the sequence's tag. + */ +Reader.prototype.readSequence = function (tag) { + var seq = this.peek(); + if (seq === null) + return null; + if (tag !== undefined && tag !== seq) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + seq.toString(16)); - return false; - }; + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; - _proto.toString = function toString() { - return '' + this._year; - }; + this._offset = o; + return seq; +}; - _proto.toJSON = function toJSON() { - return this.toString(); - }; - _proto.until = function until(endExclusive, unit) { - var end = Year.from(endExclusive); +Reader.prototype.readInt = function () { + return this._readTag(ASN1.Integer); +}; - if (unit instanceof ChronoUnit) { - var yearsUntil = end.value() - this.value(); - switch (unit) { - case ChronoUnit.YEARS: - return yearsUntil; +Reader.prototype.readBoolean = function () { + return (this._readTag(ASN1.Boolean) === 0 ? false : true); +}; - case ChronoUnit.DECADES: - return MathUtil.intDiv(yearsUntil, 10); - case ChronoUnit.CENTURIES: - return MathUtil.intDiv(yearsUntil, 100); +Reader.prototype.readEnumeration = function () { + return this._readTag(ASN1.Enumeration); +}; - case ChronoUnit.MILLENNIA: - return MathUtil.intDiv(yearsUntil, 1000); - case ChronoUnit.ERAS: - return end.getLong(ChronoField.ERA) - this.getLong(ChronoField.ERA); - } +Reader.prototype.readString = function (tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } + var b = this.peek(); + if (b === null) + return null; - return unit.between(this, end); - }; + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - return Year; - }(Temporal); - var PARSER$2; - function _init$d() { - Year.MIN_VALUE = YearConstants.MIN_VALUE; - Year.MAX_VALUE = YearConstants.MAX_VALUE; - PARSER$2 = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).toFormatter(); - Year.FROM = createTemporalQuery('Year.FROM', function (temporal) { - return Year.from(temporal); - }); - } + var o = this.readLength(this._offset + 1); // stored in `length` - var TemporalAdjusters = function () { - function TemporalAdjusters() {} + if (o === null) + return null; - TemporalAdjusters.firstDayOfMonth = function firstDayOfMonth() { - return Impl.FIRST_DAY_OF_MONTH; - }; + if (this.length > this._size - o) + return null; - TemporalAdjusters.lastDayOfMonth = function lastDayOfMonth() { - return Impl.LAST_DAY_OF_MONTH; - }; + this._offset = o; - TemporalAdjusters.firstDayOfNextMonth = function firstDayOfNextMonth() { - return Impl.FIRST_DAY_OF_NEXT_MONTH; - }; + if (this.length === 0) + return retbuf ? Buffer.alloc(0) : ''; - TemporalAdjusters.firstDayOfYear = function firstDayOfYear() { - return Impl.FIRST_DAY_OF_YEAR; - }; + var str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; - TemporalAdjusters.lastDayOfYear = function lastDayOfYear() { - return Impl.LAST_DAY_OF_YEAR; - }; + return retbuf ? str : str.toString('utf8'); +}; - TemporalAdjusters.firstDayOfNextYear = function firstDayOfNextYear() { - return Impl.FIRST_DAY_OF_NEXT_YEAR; - }; +Reader.prototype.readOID = function (tag) { + if (!tag) + tag = ASN1.OID; - TemporalAdjusters.firstInMonth = function firstInMonth(dayOfWeek) { - requireNonNull(dayOfWeek, 'dayOfWeek'); - return new DayOfWeekInMonth(1, dayOfWeek); - }; + var b = this.readString(tag, true); + if (b === null) + return null; - TemporalAdjusters.lastInMonth = function lastInMonth(dayOfWeek) { - requireNonNull(dayOfWeek, 'dayOfWeek'); - return new DayOfWeekInMonth(-1, dayOfWeek); - }; + var values = []; + var value = 0; - TemporalAdjusters.dayOfWeekInMonth = function dayOfWeekInMonth(ordinal, dayOfWeek) { - requireNonNull(dayOfWeek, 'dayOfWeek'); - return new DayOfWeekInMonth(ordinal, dayOfWeek); - }; + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 0xff; - TemporalAdjusters.next = function next(dayOfWeek) { - return new RelativeDayOfWeek(2, dayOfWeek); - }; + value <<= 7; + value += byte & 0x7f; + if ((byte & 0x80) === 0) { + values.push(value); + value = 0; + } + } - TemporalAdjusters.nextOrSame = function nextOrSame(dayOfWeek) { - return new RelativeDayOfWeek(0, dayOfWeek); - }; + value = values.shift(); + values.unshift(value % 40); + values.unshift((value / 40) >> 0); - TemporalAdjusters.previous = function previous(dayOfWeek) { - return new RelativeDayOfWeek(3, dayOfWeek); - }; + return values.join('.'); +}; - TemporalAdjusters.previousOrSame = function previousOrSame(dayOfWeek) { - return new RelativeDayOfWeek(1, dayOfWeek); - }; - return TemporalAdjusters; - }(); +Reader.prototype._readTag = function (tag) { + assert.ok(tag !== undefined); - var Impl = function (_TemporalAdjuster) { - _inheritsLoose(Impl, _TemporalAdjuster); + var b = this.peek(); - function Impl(ordinal) { - var _this; + if (b === null) + return null; - _this = _TemporalAdjuster.call(this) || this; - _this._ordinal = ordinal; - return _this; - } + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - var _proto = Impl.prototype; + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; - _proto.adjustInto = function adjustInto(temporal) { - switch (this._ordinal) { - case 0: - return temporal.with(ChronoField.DAY_OF_MONTH, 1); + if (this.length > 4) + throw newInvalidAsn1Error('Integer too long: ' + this.length); - case 1: - return temporal.with(ChronoField.DAY_OF_MONTH, temporal.range(ChronoField.DAY_OF_MONTH).maximum()); + if (this.length > this._size - o) + return null; + this._offset = o; - case 2: - return temporal.with(ChronoField.DAY_OF_MONTH, 1).plus(1, ChronoUnit.MONTHS); + var fb = this._buf[this._offset]; + var value = 0; - case 3: - return temporal.with(ChronoField.DAY_OF_YEAR, 1); + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= (this._buf[this._offset++] & 0xff); + } - case 4: - return temporal.with(ChronoField.DAY_OF_YEAR, temporal.range(ChronoField.DAY_OF_YEAR).maximum()); + if ((fb & 0x80) === 0x80 && i !== 4) + value -= (1 << (i * 8)); - case 5: - return temporal.with(ChronoField.DAY_OF_YEAR, 1).plus(1, ChronoUnit.YEARS); - } + return value >> 0; +}; - throw new IllegalStateException('Unreachable'); - }; - return Impl; - }(TemporalAdjuster); - Impl.FIRST_DAY_OF_MONTH = new Impl(0); - Impl.LAST_DAY_OF_MONTH = new Impl(1); - Impl.FIRST_DAY_OF_NEXT_MONTH = new Impl(2); - Impl.FIRST_DAY_OF_YEAR = new Impl(3); - Impl.LAST_DAY_OF_YEAR = new Impl(4); - Impl.FIRST_DAY_OF_NEXT_YEAR = new Impl(5); +// --- Exported API - var DayOfWeekInMonth = function (_TemporalAdjuster2) { - _inheritsLoose(DayOfWeekInMonth, _TemporalAdjuster2); +module.exports = Reader; - function DayOfWeekInMonth(ordinal, dow) { - var _this2; - _this2 = _TemporalAdjuster2.call(this) || this; - _this2._ordinal = ordinal; - _this2._dowValue = dow.value(); - return _this2; - } +/***/ }), - var _proto2 = DayOfWeekInMonth.prototype; +/***/ 42473: +/***/ ((module) => { - _proto2.adjustInto = function adjustInto(temporal) { - if (this._ordinal >= 0) { - var temp = temporal.with(ChronoField.DAY_OF_MONTH, 1); - var curDow = temp.get(ChronoField.DAY_OF_WEEK); - var dowDiff = MathUtil.intMod(this._dowValue - curDow + 7, 7); - dowDiff += (this._ordinal - 1) * 7; - return temp.plus(dowDiff, ChronoUnit.DAYS); - } else { - var _temp = temporal.with(ChronoField.DAY_OF_MONTH, temporal.range(ChronoField.DAY_OF_MONTH).maximum()); +// Copyright 2011 Mark Cavage All rights reserved. - var _curDow = _temp.get(ChronoField.DAY_OF_WEEK); - var daysDiff = this._dowValue - _curDow; - daysDiff = daysDiff === 0 ? 0 : daysDiff > 0 ? daysDiff - 7 : daysDiff; - daysDiff -= (-this._ordinal - 1) * 7; - return _temp.plus(daysDiff, ChronoUnit.DAYS); - } - }; +module.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 +}; + + +/***/ }), + +/***/ 43200: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return DayOfWeekInMonth; - }(TemporalAdjuster); +// Copyright 2011 Mark Cavage All rights reserved. - var RelativeDayOfWeek = function (_TemporalAdjuster3) { - _inheritsLoose(RelativeDayOfWeek, _TemporalAdjuster3); +var assert = __nccwpck_require__(42357); +var Buffer = __nccwpck_require__(15118).Buffer; +var ASN1 = __nccwpck_require__(42473); +var errors = __nccwpck_require__(99348); - function RelativeDayOfWeek(relative, dayOfWeek) { - var _this3; - _this3 = _TemporalAdjuster3.call(this) || this; - requireNonNull(dayOfWeek, 'dayOfWeek'); - _this3._relative = relative; - _this3._dowValue = dayOfWeek.value(); - return _this3; - } +// --- Globals - var _proto3 = RelativeDayOfWeek.prototype; +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - _proto3.adjustInto = function adjustInto(temporal) { - var calDow = temporal.get(ChronoField.DAY_OF_WEEK); +var DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 +}; - if (this._relative < 2 && calDow === this._dowValue) { - return temporal; - } - if ((this._relative & 1) === 0) { - var daysDiff = calDow - this._dowValue; - return temporal.plus(daysDiff >= 0 ? 7 - daysDiff : -daysDiff, ChronoUnit.DAYS); - } else { - var _daysDiff = this._dowValue - calDow; +// --- Helpers - return temporal.minus(_daysDiff >= 0 ? 7 - _daysDiff : -_daysDiff, ChronoUnit.DAYS); - } - }; +function merge(from, to) { + assert.ok(from); + assert.equal(typeof (from), 'object'); + assert.ok(to); + assert.equal(typeof (to), 'object'); - return RelativeDayOfWeek; - }(TemporalAdjuster); + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function (key) { + if (to[key]) + return; - var IsoChronology = function (_Enum) { - _inheritsLoose(IsoChronology, _Enum); + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); + }); - function IsoChronology() { - return _Enum.apply(this, arguments) || this; - } + return to; +} - IsoChronology.isLeapYear = function isLeapYear(prolepticYear) { - return (prolepticYear & 3) === 0 && (prolepticYear % 100 !== 0 || prolepticYear % 400 === 0); - }; - var _proto = IsoChronology.prototype; - _proto._updateResolveMap = function _updateResolveMap(fieldValues, field, value) { - requireNonNull(fieldValues, 'fieldValues'); - requireNonNull(field, 'field'); - var current = fieldValues.get(field); +// --- API - if (current != null && current !== value) { - throw new DateTimeException('Invalid state, field: ' + field + ' ' + current + ' conflicts with ' + field + ' ' + value); - } +function Writer(options) { + options = merge(DEFAULT_OPTS, options || {}); - fieldValues.put(field, value); - }; + this._buf = Buffer.alloc(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; - _proto.resolveDate = function resolveDate(fieldValues, resolverStyle) { - if (fieldValues.containsKey(ChronoField.EPOCH_DAY)) { - return LocalDate.ofEpochDay(fieldValues.remove(ChronoField.EPOCH_DAY)); - } + // A list of offsets in the buffer where we need to insert + // sequence tag/len pairs. + this._seq = []; +} - var prolepticMonth = fieldValues.remove(ChronoField.PROLEPTIC_MONTH); +Object.defineProperty(Writer.prototype, 'buffer', { + get: function () { + if (this._seq.length) + throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); - if (prolepticMonth != null) { - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.PROLEPTIC_MONTH.checkValidValue(prolepticMonth); - } + return (this._buf.slice(0, this._offset)); + } +}); - this._updateResolveMap(fieldValues, ChronoField.MONTH_OF_YEAR, MathUtil.floorMod(prolepticMonth, 12) + 1); +Writer.prototype.writeByte = function (b) { + if (typeof (b) !== 'number') + throw new TypeError('argument must be a Number'); - this._updateResolveMap(fieldValues, ChronoField.YEAR, MathUtil.floorDiv(prolepticMonth, 12)); - } + this._ensure(1); + this._buf[this._offset++] = b; +}; - var yoeLong = fieldValues.remove(ChronoField.YEAR_OF_ERA); - if (yoeLong != null) { - if (resolverStyle !== ResolverStyle.LENIENT) { - ChronoField.YEAR_OF_ERA.checkValidValue(yoeLong); - } +Writer.prototype.writeInt = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Integer; - var era = fieldValues.remove(ChronoField.ERA); + var sz = 4; - if (era == null) { - var year = fieldValues.get(ChronoField.YEAR); + while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && + (sz > 1)) { + sz--; + i <<= 8; + } - if (resolverStyle === ResolverStyle.STRICT) { - if (year != null) { - this._updateResolveMap(fieldValues, ChronoField.YEAR, year > 0 ? yoeLong : MathUtil.safeSubtract(1, yoeLong)); - } else { - fieldValues.put(ChronoField.YEAR_OF_ERA, yoeLong); - } - } else { - this._updateResolveMap(fieldValues, ChronoField.YEAR, year == null || year > 0 ? yoeLong : MathUtil.safeSubtract(1, yoeLong)); - } - } else if (era === 1) { - this._updateResolveMap(fieldValues, ChronoField.YEAR, yoeLong); - } else if (era === 0) { - this._updateResolveMap(fieldValues, ChronoField.YEAR, MathUtil.safeSubtract(1, yoeLong)); - } else { - throw new DateTimeException('Invalid value for era: ' + era); - } - } else if (fieldValues.containsKey(ChronoField.ERA)) { - ChronoField.ERA.checkValidValue(fieldValues.get(ChronoField.ERA)); - } + if (sz > 4) + throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); - if (fieldValues.containsKey(ChronoField.YEAR)) { - if (fieldValues.containsKey(ChronoField.MONTH_OF_YEAR)) { - if (fieldValues.containsKey(ChronoField.DAY_OF_MONTH)) { - var y = ChronoField.YEAR.checkValidIntValue(fieldValues.remove(ChronoField.YEAR)); - var moy = fieldValues.remove(ChronoField.MONTH_OF_YEAR); - var dom = fieldValues.remove(ChronoField.DAY_OF_MONTH); + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; - if (resolverStyle === ResolverStyle.LENIENT) { - var months = moy - 1; - var days = dom - 1; - return LocalDate.of(y, 1, 1).plusMonths(months).plusDays(days); - } else if (resolverStyle === ResolverStyle.SMART) { - ChronoField.DAY_OF_MONTH.checkValidValue(dom); + while (sz-- > 0) { + this._buf[this._offset++] = ((i & 0xff000000) >>> 24); + i <<= 8; + } - if (moy === 4 || moy === 6 || moy === 9 || moy === 11) { - dom = Math.min(dom, 30); - } else if (moy === 2) { - dom = Math.min(dom, Month.FEBRUARY.length(Year.isLeap(y))); - } +}; - return LocalDate.of(y, moy, dom); - } else { - return LocalDate.of(y, moy, dom); - } - } - } - if (fieldValues.containsKey(ChronoField.DAY_OF_YEAR)) { - var _y = ChronoField.YEAR.checkValidIntValue(fieldValues.remove(ChronoField.YEAR)); +Writer.prototype.writeNull = function () { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; - if (resolverStyle === ResolverStyle.LENIENT) { - var _days = MathUtil.safeSubtract(fieldValues.remove(ChronoField.DAY_OF_YEAR), 1); - return LocalDate.ofYearDay(_y, 1).plusDays(_days); - } +Writer.prototype.writeEnumeration = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Enumeration; - var doy = ChronoField.DAY_OF_YEAR.checkValidIntValue(fieldValues.remove(ChronoField.DAY_OF_YEAR)); - return LocalDate.ofYearDay(_y, doy); - } + return this.writeInt(i, tag); +}; - if (fieldValues.containsKey(ChronoField.ALIGNED_WEEK_OF_YEAR)) { - if (fieldValues.containsKey(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)) { - var _y2 = ChronoField.YEAR.checkValidIntValue(fieldValues.remove(ChronoField.YEAR)); - if (resolverStyle === ResolverStyle.LENIENT) { - var weeks = MathUtil.safeSubtract(fieldValues.remove(ChronoField.ALIGNED_WEEK_OF_YEAR), 1); +Writer.prototype.writeBoolean = function (b, tag) { + if (typeof (b) !== 'boolean') + throw new TypeError('argument must be a Boolean'); + if (typeof (tag) !== 'number') + tag = ASN1.Boolean; - var _days2 = MathUtil.safeSubtract(fieldValues.remove(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), 1); + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; - return LocalDate.of(_y2, 1, 1).plusWeeks(weeks).plusDays(_days2); - } - var aw = ChronoField.ALIGNED_WEEK_OF_YEAR.checkValidIntValue(fieldValues.remove(ChronoField.ALIGNED_WEEK_OF_YEAR)); - var ad = ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR.checkValidIntValue(fieldValues.remove(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); - var date = LocalDate.of(_y2, 1, 1).plusDays((aw - 1) * 7 + (ad - 1)); +Writer.prototype.writeString = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); + if (typeof (tag) !== 'number') + tag = ASN1.OctetString; - if (resolverStyle === ResolverStyle.STRICT && date.get(ChronoField.YEAR) !== _y2) { - throw new DateTimeException('Strict mode rejected date parsed to a different year'); - } + var len = Buffer.byteLength(s); + this.writeByte(tag); + this.writeLength(len); + if (len) { + this._ensure(len); + this._buf.write(s, this._offset); + this._offset += len; + } +}; - return date; - } - if (fieldValues.containsKey(ChronoField.DAY_OF_WEEK)) { - var _y3 = ChronoField.YEAR.checkValidIntValue(fieldValues.remove(ChronoField.YEAR)); +Writer.prototype.writeBuffer = function (buf, tag) { + if (typeof (tag) !== 'number') + throw new TypeError('tag must be a number'); + if (!Buffer.isBuffer(buf)) + throw new TypeError('argument must be a buffer'); - if (resolverStyle === ResolverStyle.LENIENT) { - var _weeks = MathUtil.safeSubtract(fieldValues.remove(ChronoField.ALIGNED_WEEK_OF_YEAR), 1); + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; - var _days3 = MathUtil.safeSubtract(fieldValues.remove(ChronoField.DAY_OF_WEEK), 1); - return LocalDate.of(_y3, 1, 1).plusWeeks(_weeks).plusDays(_days3); - } +Writer.prototype.writeStringArray = function (strings) { + if ((!strings instanceof Array)) + throw new TypeError('argument must be an Array[String]'); - var _aw = ChronoField.ALIGNED_WEEK_OF_YEAR.checkValidIntValue(fieldValues.remove(ChronoField.ALIGNED_WEEK_OF_YEAR)); + var self = this; + strings.forEach(function (s) { + self.writeString(s); + }); +}; - var dow = ChronoField.DAY_OF_WEEK.checkValidIntValue(fieldValues.remove(ChronoField.DAY_OF_WEEK)); +// This is really to solve DER cases, but whatever for now +Writer.prototype.writeOID = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string'); + if (typeof (tag) !== 'number') + tag = ASN1.OID; + + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error('argument is not a valid OID string'); + + function encodeOctet(bytes, octet) { + if (octet < 128) { + bytes.push(octet); + } else if (octet < 16384) { + bytes.push((octet >>> 7) | 0x80); + bytes.push(octet & 0x7F); + } else if (octet < 2097152) { + bytes.push((octet >>> 14) | 0x80); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else if (octet < 268435456) { + bytes.push((octet >>> 21) | 0x80); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else { + bytes.push(((octet >>> 28) | 0x80) & 0xFF); + bytes.push(((octet >>> 21) | 0x80) & 0xFF); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } + } - var _date = LocalDate.of(_y3, 1, 1).plusWeeks(_aw - 1).with(TemporalAdjusters.nextOrSame(DayOfWeek.of(dow))); + var tmp = s.split('.'); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function (b) { + encodeOctet(bytes, parseInt(b, 10)); + }); - if (resolverStyle === ResolverStyle.STRICT && _date.get(ChronoField.YEAR) !== _y3) { - throw new DateTimeException('Strict mode rejected date parsed to a different month'); - } + var self = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function (b) { + self.writeByte(b); + }); +}; - return _date; - } - } - } - return null; - }; +Writer.prototype.writeLength = function (len) { + if (typeof (len) !== 'number') + throw new TypeError('argument must be a Number'); - _proto.date = function date(temporal) { - return LocalDate.from(temporal); - }; + this._ensure(4); - return IsoChronology; - }(Enum); - function _init$e() { - IsoChronology.INSTANCE = new IsoChronology('IsoChronology'); - } + if (len <= 0x7f) { + this._buf[this._offset++] = len; + } else if (len <= 0xff) { + this._buf[this._offset++] = 0x81; + this._buf[this._offset++] = len; + } else if (len <= 0xffff) { + this._buf[this._offset++] = 0x82; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 0xffffff) { + this._buf[this._offset++] = 0x83; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else { + throw newInvalidAsn1Error('Length too long (> 4 bytes)'); + } +}; + +Writer.prototype.startSequence = function (tag) { + if (typeof (tag) !== 'number') + tag = ASN1.Sequence | ASN1.Constructor; + + this.writeByte(tag); + this._seq.push(this._offset); + this._ensure(3); + this._offset += 3; +}; + + +Writer.prototype.endSequence = function () { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; + + if (len <= 0x7f) { + this._shift(start, len, -2); + this._buf[seq] = len; + } else if (len <= 0xff) { + this._shift(start, len, -1); + this._buf[seq] = 0x81; + this._buf[seq + 1] = len; + } else if (len <= 0xffff) { + this._buf[seq] = 0x82; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 0xffffff) { + this._shift(start, len, 1); + this._buf[seq] = 0x83; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw newInvalidAsn1Error('Sequence too long'); + } +}; - var OffsetTime = function (_DefaultInterfaceTemp) { - _inheritsLoose(OffsetTime, _DefaultInterfaceTemp); - OffsetTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); +Writer.prototype._shift = function (start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); - if (temporal instanceof OffsetTime) { - return temporal; - } else if (temporal instanceof OffsetDateTime) { - return temporal.toOffsetTime(); - } + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; +}; - try { - var time = LocalTime.from(temporal); - var offset = ZoneOffset.from(temporal); - return new OffsetTime(time, offset); - } catch (ex) { - throw new DateTimeException("Unable to obtain OffsetTime TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); - } - }; +Writer.prototype._ensure = function (len) { + assert.ok(len); - OffsetTime.now = function now(clockOrZone) { - if (arguments.length === 0) { - return OffsetTime._now(Clock.systemDefaultZone()); - } else if (clockOrZone instanceof Clock) { - return OffsetTime._now(clockOrZone); - } else { - return OffsetTime._now(Clock.system(clockOrZone)); - } - }; + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) + sz += len; - OffsetTime._now = function _now(clock) { - requireNonNull(clock, 'clock'); - var now = clock.instant(); - return OffsetTime.ofInstant(now, clock.zone().rules().offset(now)); - }; + var buf = Buffer.alloc(sz); - OffsetTime.of = function of() { - if (arguments.length <= 2) { - return OffsetTime.ofTimeAndOffset.apply(this, arguments); - } else { - return OffsetTime.ofNumbers.apply(this, arguments); - } - }; + this._buf.copy(buf, 0, 0, this._offset); + this._buf = buf; + this._size = sz; + } +}; - OffsetTime.ofNumbers = function ofNumbers(hour, minute, second, nanoOfSecond, offset) { - var time = LocalTime.of(hour, minute, second, nanoOfSecond); - return new OffsetTime(time, offset); - }; - OffsetTime.ofTimeAndOffset = function ofTimeAndOffset(time, offset) { - return new OffsetTime(time, offset); - }; - OffsetTime.ofInstant = function ofInstant(instant, zone) { - requireNonNull(instant, 'instant'); - requireInstance(instant, Instant, 'instant'); - requireNonNull(zone, 'zone'); - requireInstance(zone, ZoneId, 'zone'); - var rules = zone.rules(); - var offset = rules.offset(instant); - var secsOfDay = instant.epochSecond() % LocalTime.SECONDS_PER_DAY; - secsOfDay = (secsOfDay + offset.totalSeconds()) % LocalTime.SECONDS_PER_DAY; +// --- Exported API - if (secsOfDay < 0) { - secsOfDay += LocalTime.SECONDS_PER_DAY; - } +module.exports = Writer; - var time = LocalTime.ofSecondOfDay(secsOfDay, instant.nano()); - return new OffsetTime(time, offset); - }; - OffsetTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_OFFSET_TIME; - } +/***/ }), - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, OffsetTime.FROM); - }; +/***/ 80970: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function OffsetTime(time, offset) { - var _this; +// Copyright 2011 Mark Cavage All rights reserved. - _this = _DefaultInterfaceTemp.call(this) || this; - requireNonNull(time, 'time'); - requireInstance(time, LocalTime, 'time'); - requireNonNull(offset, 'offset'); - requireInstance(offset, ZoneOffset, 'offset'); - _this._time = time; - _this._offset = offset; - return _this; - } +// If you have no idea what ASN.1 or BER is, see this: +// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc - var _proto = OffsetTime.prototype; +var Ber = __nccwpck_require__(194); - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.NANO_OF_DAY, this._time.toNanoOfDay()).with(ChronoField.OFFSET_SECONDS, this.offset().totalSeconds()); - }; - _proto.atDate = function atDate(date) { - return OffsetDateTime.of(date, this._time, this._offset); - }; - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this, OffsetTime.FROM); - }; +// --- Exported API - _proto.get = function get(field) { - return _DefaultInterfaceTemp.prototype.get.call(this, field); - }; +module.exports = { - _proto.getLong = function getLong(field) { - if (field instanceof ChronoField) { - if (field === ChronoField.OFFSET_SECONDS) { - return this._offset.totalSeconds(); - } + Ber: Ber, - return this._time.getLong(field); - } + BerReader: Ber.Reader, - return field.getFrom(this); - }; + BerWriter: Ber.Writer - _proto.hour = function hour() { - return this._time.hour(); - }; +}; - _proto.minute = function minute() { - return this._time.minute(); - }; - _proto.second = function second() { - return this._time.second(); - }; +/***/ }), - _proto.nano = function nano() { - return this._time.nano(); - }; +/***/ 66631: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.offset = function offset() { - return this._offset; - }; +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - return this._toEpochNano() > other._toEpochNano(); - }; +var assert = __nccwpck_require__(42357); +var Stream = __nccwpck_require__(92413).Stream; +var util = __nccwpck_require__(31669); - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - return this._toEpochNano() < other._toEpochNano(); - }; - _proto.isEqual = function isEqual(other) { - requireNonNull(other, 'other'); - return this._toEpochNano() === other._toEpochNano(); - }; +///--- Globals - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isTimeBased() || fieldOrUnit === ChronoField.OFFSET_SECONDS; - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isTimeBased(); - } +/* JSSTYLED */ +var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; - _proto.minusHours = function minusHours(hours) { - return this._withLocalTimeOffset(this._time.minusHours(hours), this._offset); - }; +///--- Internal - _proto.minusMinutes = function minusMinutes(minutes) { - return this._withLocalTimeOffset(this._time.minusMinutes(minutes), this._offset); - }; +function _capitalize(str) { + return (str.charAt(0).toUpperCase() + str.slice(1)); +} - _proto.minusSeconds = function minusSeconds(seconds) { - return this._withLocalTimeOffset(this._time.minusSeconds(seconds), this._offset); - }; +function _toss(name, expected, oper, arg, actual) { + throw new assert.AssertionError({ + message: util.format('%s (%s) is required', name, expected), + actual: (actual === undefined) ? typeof (arg) : actual(arg), + expected: expected, + operator: oper || '===', + stackStartFunction: _toss.caller + }); +} - _proto.minusNanos = function minusNanos(nanos) { - return this._withLocalTimeOffset(this._time.minusNanos(nanos), this._offset); - }; +function _getClass(arg) { + return (Object.prototype.toString.call(arg).slice(8, -1)); +} - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount); - return amount.subtractFrom(this); - }; +function noop() { + // Why even bother with asserts? +} - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return this.plus(-1 * amountToSubtract, unit); - }; - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount); - return amount.addTo(this); - }; +///--- Exports - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - if (unit instanceof ChronoUnit) { - return this._withLocalTimeOffset(this._time.plus(amountToAdd, unit), this._offset); +var types = { + bool: { + check: function (arg) { return typeof (arg) === 'boolean'; } + }, + func: { + check: function (arg) { return typeof (arg) === 'function'; } + }, + string: { + check: function (arg) { return typeof (arg) === 'string'; } + }, + object: { + check: function (arg) { + return typeof (arg) === 'object' && arg !== null; } + }, + number: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg); + } + }, + finite: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); + } + }, + buffer: { + check: function (arg) { return Buffer.isBuffer(arg); }, + operator: 'Buffer.isBuffer' + }, + array: { + check: function (arg) { return Array.isArray(arg); }, + operator: 'Array.isArray' + }, + stream: { + check: function (arg) { return arg instanceof Stream; }, + operator: 'instanceof', + actual: _getClass + }, + date: { + check: function (arg) { return arg instanceof Date; }, + operator: 'instanceof', + actual: _getClass + }, + regexp: { + check: function (arg) { return arg instanceof RegExp; }, + operator: 'instanceof', + actual: _getClass + }, + uuid: { + check: function (arg) { + return typeof (arg) === 'string' && UUID_REGEXP.test(arg); + }, + operator: 'isUUID' + } +}; - return unit.addTo(this, amountToAdd); - }; - - _proto.plusHours = function plusHours(hours) { - return this._withLocalTimeOffset(this._time.plusHours(hours), this._offset); - }; - - _proto.plusMinutes = function plusMinutes(minutes) { - return this._withLocalTimeOffset(this._time.plusMinutes(minutes), this._offset); - }; - - _proto.plusSeconds = function plusSeconds(seconds) { - return this._withLocalTimeOffset(this._time.plusSeconds(seconds), this._offset); - }; - - _proto.plusNanos = function plusNanos(nanos) { - return this._withLocalTimeOffset(this._time.plusNanos(nanos), this._offset); - }; +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); + /* re-export standard assert */ + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function (arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; + } - if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.offset() || _query === TemporalQueries.zone()) { - return this.offset(); - } else if (_query === TemporalQueries.localTime()) { - return this._time; - } else if (_query === TemporalQueries.chronology() || _query === TemporalQueries.localDate() || _query === TemporalQueries.zoneId()) { - return null; + /* standard checks */ + keys.forEach(function (k) { + if (ndebug) { + out[k] = noop; + return; } + var type = types[k]; + out[k] = function (arg, msg) { + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; - - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (field === ChronoField.OFFSET_SECONDS) { - return field.range(); - } - - return this._time.range(field); + /* optional checks */ + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; } + var type = types[k]; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); - return field.rangeRefinedBy(this); - }; + /* arrayOf checks */ + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); - _proto.toLocalTime = function toLocalTime() { - return this._time; - }; + /* optionalArrayOf checks */ + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); - _proto.truncatedTo = function truncatedTo(unit) { - return this._withLocalTimeOffset(this._time.truncatedTo(unit), this._offset); - }; + /* re-export built-in assertions */ + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; + } + if (ndebug) { + out[k] = noop; + return; + } + out[k] = assert[k]; + }); - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - var end = OffsetTime.from(endExclusive); + /* export ourselves (for unit tests _only_) */ + out._setExports = _setExports; - if (unit instanceof ChronoUnit) { - var nanosUntil = end._toEpochNano() - this._toEpochNano(); + return out; +} - switch (unit) { - case ChronoUnit.NANOS: - return nanosUntil; +module.exports = _setExports(process.env.NODE_NDEBUG); - case ChronoUnit.MICROS: - return Math.floor(nanosUntil / 1000); - case ChronoUnit.MILLIS: - return Math.floor(nanosUntil / 1000000); +/***/ }), - case ChronoUnit.SECONDS: - return Math.floor(nanosUntil / LocalTime.NANOS_PER_SECOND); +/***/ 57888: +/***/ (function(__unused_webpack_module, exports) { - case ChronoUnit.MINUTES: - return Math.floor(nanosUntil / LocalTime.NANOS_PER_MINUTE); +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; - case ChronoUnit.HOURS: - return Math.floor(nanosUntil / LocalTime.NANOS_PER_HOUR); + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); + } - case ChronoUnit.HALF_DAYS: - return Math.floor(nanosUntil / (12 * LocalTime.NANOS_PER_HOUR)); - } + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } + /* istanbul ignore file */ - return unit.between(this, end); - }; + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - _proto.withHour = function withHour(hour) { - return this._withLocalTimeOffset(this._time.withHour(hour), this._offset); - }; + function fallback(fn) { + setTimeout(fn, 0); + } - _proto.withMinute = function withMinute(minute) { - return this._withLocalTimeOffset(this._time.withMinute(minute), this._offset); - }; + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } - _proto.withSecond = function withSecond(second) { - return this._withLocalTimeOffset(this._time.withSecond(second), this._offset); - }; + var _defer; - _proto.withNano = function withNano(nano) { - return this._withLocalTimeOffset(this._time.withNano(nano), this._offset); - }; + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } else { + _defer = fallback; + } - _proto.withOffsetSameInstant = function withOffsetSameInstant(offset) { - requireNonNull(offset, 'offset'); + var setImmediate$1 = wrap(_defer); - if (offset.equals(this._offset)) { - return this; + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } } - var difference = offset.totalSeconds() - this._offset.totalSeconds(); - - var adjusted = this._time.plusSeconds(difference); - - return new OffsetTime(adjusted, offset); - }; - - _proto.withOffsetSameLocal = function withOffsetSameLocal(offset) { - return offset != null && offset.equals(this._offset) ? this : new OffsetTime(this._time, offset); - }; + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); + } - _proto._toEpochNano = function _toEpochNano() { - var nod = this._time.toNanoOfDay(); + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); + } - var offsetNanos = this._offset.totalSeconds() * LocalTime.NANOS_PER_SECOND; - return nod - offsetNanos; - }; + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } - if (adjuster instanceof LocalTime) { - return this._withLocalTimeOffset(adjuster, this._offset); - } else if (adjuster instanceof ZoneOffset) { - return this._withLocalTimeOffset(this._time, adjuster); - } else if (adjuster instanceof OffsetTime) { - return adjuster; - } + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } - return adjuster.adjustInto(this); - }; + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } - if (field instanceof ChronoField) { - if (field === ChronoField.OFFSET_SECONDS) { - return this._withLocalTimeOffset(this._time, ZoneOffset.ofTotalSeconds(field.checkValidIntValue(newValue))); - } + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity = asyncFn.length) { + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } - return this._withLocalTimeOffset(this._time.with(field, newValue), this._offset); + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) } - return field.adjustInto(this, newValue); - }; + return awaitable + } - _proto._withLocalTimeOffset = function _withLocalTimeOffset(time, offset) { - if (this._time === time && this._offset.equals(offset)) { - return this; - } + function applyEach (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } - return new OffsetTime(time, offset); - }; + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, OffsetTime, 'other'); + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } - if (this._offset.equals(other._offset)) { - return this._time.compareTo(other._time); - } + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } - var compare = MathUtil.compareNumbers(this._toEpochNano(), other._toEpochNano()); + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; - if (compare === 0) { - return this._time.compareTo(other._time); + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); } + Object.assign(wrapper, fn); + return wrapper + } - return compare; - }; + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } - _proto.equals = function equals(other) { - if (this === other) { - return true; + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; } + } - if (other instanceof OffsetTime) { - return this._time.equals(other._time) && this._offset.equals(other._offset); + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; } + } - return false; - }; - - _proto.hashCode = function hashCode() { - return this._time.hashCode() ^ this._offset.hashCode(); - }; + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? {value: obj[key], key} : null; + }; + } - _proto.toString = function toString() { - return this._time.toString() + this._offset.toString(); - }; + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } - _proto.toJSON = function toJSON() { - return this.toString(); - }; + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } - return OffsetTime; - }(DefaultInterfaceTemporal); - function _init$f() { - OffsetTime.MIN = OffsetTime.ofNumbers(0, 0, 0, 0, ZoneOffset.MAX); - OffsetTime.MAX = OffsetTime.ofNumbers(23, 59, 59, 999999999, ZoneOffset.MIN); - OffsetTime.FROM = createTemporalQuery('OffsetTime.FROM', function (temporal) { - return OffsetTime.from(temporal); - }); + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; } - var ChronoZonedDateTime = function (_DefaultInterfaceTemp) { - _inheritsLoose(ChronoZonedDateTime, _DefaultInterfaceTemp); + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } - function ChronoZonedDateTime() { - return _DefaultInterfaceTemp.apply(this, arguments) || this; - } + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) - var _proto = ChronoZonedDateTime.prototype; + if (err === false) { + done = true; + canceled = true; + return + } - _proto.query = function query(_query) { - if (_query === TemporalQueries.zoneId() || _query === TemporalQueries.zone()) { - return this.zone(); - } else if (_query === TemporalQueries.chronology()) { - return this.toLocalDate().chronology(); - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.offset()) { - return this.offset(); - } else if (_query === TemporalQueries.localDate()) { - return LocalDate.ofEpochDay(this.toLocalDate().toEpochDay()); - } else if (_query === TemporalQueries.localTime()) { - return this.toLocalTime(); + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); } - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; + replenish(); + } - _proto.toInstant = function toInstant() { - return Instant.ofEpochSecond(this.toEpochSecond(), this.toLocalTime().nano()); - }; + var eachOfLimit = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; - _proto.toEpochSecond = function toEpochSecond() { - var epochDay = this.toLocalDate().toEpochDay(); - var secs = epochDay * 86400 + this.toLocalTime().toSecondOfDay(); - secs -= this.offset().totalSeconds(); - return secs; - }; + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - var cmp = MathUtil.compareNumbers(this.toEpochSecond(), other.toEpochSecond()); + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } - if (cmp === 0) { - cmp = this.toLocalTime().nano() - other.toLocalTime().nano(); + replenish(); + }; + }; - if (cmp === 0) { - cmp = this.toLocalDateTime().compareTo(other.toLocalDateTime()); + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); + } + + var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); + + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } - if (cmp === 0) { - cmp = strcmp(this.zone().id(), other.zone().id()); + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); } - } } - return cmp; - }; - - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - var thisEpochSec = this.toEpochSecond(); - var otherEpochSec = other.toEpochSecond(); - return thisEpochSec > otherEpochSec || thisEpochSec === otherEpochSec && this.toLocalTime().nano() > other.toLocalTime().nano(); - }; - - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - var thisEpochSec = this.toEpochSecond(); - var otherEpochSec = other.toEpochSecond(); - return thisEpochSec < otherEpochSec || thisEpochSec === otherEpochSec && this.toLocalTime().nano() < other.toLocalTime().nano(); - }; + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } - _proto.isEqual = function isEqual(other) { - requireNonNull(other, 'other'); - return this.toEpochSecond() === other.toEpochSecond() && this.toLocalTime().nano() === other.toLocalTime().nano(); - }; + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$2(coll, Infinity, iteratee, callback); + } - _proto.equals = function equals(other) { - if (this === other) { - return true; - } + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } + + var eachOf$1 = awaitify(eachOf, 3); + + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) + } + var map$1 = awaitify(map, 3); - if (other instanceof ChronoZonedDateTime) { - return this.compareTo(other) === 0; - } + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ + var applyEach$1 = applyEach(map$1); - return false; - }; + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$2(coll, 1, iteratee, callback) + } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); + + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) + } + var mapSeries$1 = awaitify(mapSeries, 3); + + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ + var applyEachSeries = applyEach(mapSeries$1); - return ChronoZonedDateTime; - }(DefaultInterfaceTemporal); + const PROMISE_SYMBOL = Symbol('promiseCallback'); - function strcmp(a, b) { - if (a < b) { - return -1; - } + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } - if (a > b) { - return 1; - } + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); - return 0; + return callback } - var ZonedDateTime = function (_ChronoZonedDateTime) { - _inheritsLoose(ZonedDateTime, _ChronoZonedDateTime); + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } - ZonedDateTime.now = function now(clockOrZone) { - var clock; + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; - if (clockOrZone instanceof ZoneId) { - clock = Clock.system(clockOrZone); - } else { - clock = clockOrZone == null ? Clock.systemDefaultZone() : clockOrZone; - } + var listeners = Object.create(null); - return ZonedDateTime.ofInstant(clock.instant(), clock.zone()); - }; + var readyTasks = []; - ZonedDateTime.of = function of() { - if (arguments.length <= 2) { - return ZonedDateTime.of2.apply(this, arguments); - } else if (arguments.length === 3 && arguments[0] instanceof LocalDate) { - return ZonedDateTime.of3.apply(this, arguments); - } else { - return ZonedDateTime.of8.apply(this, arguments); - } - }; + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; - ZonedDateTime.of3 = function of3(date, time, zone) { - return ZonedDateTime.of2(LocalDateTime.of(date, time), zone); - }; + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } - ZonedDateTime.of2 = function of2(localDateTime, zone) { - return ZonedDateTime.ofLocal(localDateTime, zone, null); - }; + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; - ZonedDateTime.of8 = function of8(year, month, dayOfMonth, hour, minute, second, nanoOfSecond, zone) { - var dt = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond); - return ZonedDateTime.ofLocal(dt, zone, null); - }; + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); - ZonedDateTime.ofLocal = function ofLocal(localDateTime, zone, preferredOffset) { - requireNonNull(localDateTime, 'localDateTime'); - requireNonNull(zone, 'zone'); + checkForDeadlocks(); + processQueue(); - if (zone instanceof ZoneOffset) { - return new ZonedDateTime(localDateTime, zone, zone); + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); } - var offset = null; - var rules = zone.rules(); - var validOffsets = rules.validOffsets(localDateTime); + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } - if (validOffsets.length === 1) { - offset = validOffsets[0]; - } else if (validOffsets.length === 0) { - var trans = rules.transition(localDateTime); - localDateTime = localDateTime.plusSeconds(trans.duration().seconds()); - offset = trans.offsetAfter(); - } else { - if (preferredOffset != null && validOffsets.some(function (validOffset) { - return validOffset.equals(preferredOffset); - })) { - offset = preferredOffset; - } else { - offset = requireNonNull(validOffsets[0], 'offset'); - } } - return new ZonedDateTime(localDateTime, offset, zone); - }; + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } - ZonedDateTime.ofInstant = function ofInstant() { - if (arguments.length === 2) { - return ZonedDateTime.ofInstant2.apply(this, arguments); - } else { - return ZonedDateTime.ofInstant3.apply(this, arguments); + taskListeners.push(fn); } - }; - - ZonedDateTime.ofInstant2 = function ofInstant2(instant, zone) { - requireNonNull(instant, 'instant'); - requireNonNull(zone, 'zone'); - return ZonedDateTime._create(instant.epochSecond(), instant.nano(), zone); - }; - ZonedDateTime.ofInstant3 = function ofInstant3(localDateTime, offset, zone) { - requireNonNull(localDateTime, 'localDateTime'); - requireNonNull(offset, 'offset'); - requireNonNull(zone, 'zone'); - return ZonedDateTime._create(localDateTime.toEpochSecond(offset), localDateTime.nano(), zone); - }; + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } - ZonedDateTime._create = function _create(epochSecond, nanoOfSecond, zone) { - var rules = zone.rules(); - var instant = Instant.ofEpochSecond(epochSecond, nanoOfSecond); - var offset = rules.offset(instant); - var ldt = LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, offset); - return new ZonedDateTime(ldt, offset, zone); - }; - ZonedDateTime.ofStrict = function ofStrict(localDateTime, offset, zone) { - requireNonNull(localDateTime, 'localDateTime'); - requireNonNull(offset, 'offset'); - requireNonNull(zone, 'zone'); - var rules = zone.rules(); + function runTask(key, task) { + if (hasError) return; - if (rules.isValidOffset(localDateTime, offset) === false) { - var trans = rules.transition(localDateTime); + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); - if (trans != null && trans.isGap()) { - throw new DateTimeException('LocalDateTime ' + localDateTime + ' does not exist in zone ' + zone + ' due to a gap in the local time-line, typically caused by daylight savings'); - } + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } - throw new DateTimeException('ZoneOffset "' + offset + '" is not valid for LocalDateTime "' + localDateTime + '" in zone "' + zone + '"'); + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } } - return new ZonedDateTime(localDateTime, offset, zone); - }; - - ZonedDateTime.ofLenient = function ofLenient(localDateTime, offset, zone) { - requireNonNull(localDateTime, 'localDateTime'); - requireNonNull(offset, 'offset'); - requireNonNull(zone, 'zone'); - - if (zone instanceof ZoneOffset && offset.equals(zone) === false) { - throw new IllegalArgumentException('ZoneId must match ZoneOffset'); + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; } - return new ZonedDateTime(localDateTime, offset, zone); - }; + return callback[PROMISE_SYMBOL] + } - ZonedDateTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); + var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - if (temporal instanceof ZonedDateTime) { - return temporal; + function parseParams(func) { + const src = func.toString().replace(STRIP_COMMENTS, ''); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); + } - var zone = ZoneId.from(temporal); - - if (temporal.isSupported(ChronoField.INSTANT_SECONDS)) { - var zdt = ZonedDateTime._from(temporal, zone); + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } - if (zdt != null) return zdt; - } + // remove callback param + if (!fnIsAsync) params.pop(); - var ldt = LocalDateTime.from(temporal); - return ZonedDateTime.of2(ldt, zone); - }; + newTasks[key] = params.concat(newTask); + } - ZonedDateTime._from = function _from(temporal, zone) { - try { - return ZonedDateTime.__from(temporal, zone); - } catch (ex) { - if (!(ex instanceof DateTimeException)) throw ex; - } - }; + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); - ZonedDateTime.__from = function __from(temporal, zone) { - var epochSecond = temporal.getLong(ChronoField.INSTANT_SECONDS); - var nanoOfSecond = temporal.get(ChronoField.NANO_OF_SECOND); - return ZonedDateTime._create(epochSecond, nanoOfSecond, zone); - }; + return auto(newTasks, callback); + } - ZonedDateTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; } - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, ZonedDateTime.FROM); - }; - - function ZonedDateTime(dateTime, offset, zone) { - var _this; + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; - requireNonNull(dateTime, 'dateTime'); - requireNonNull(offset, 'offset'); - requireNonNull(zone, 'zone'); - _this = _ChronoZonedDateTime.call(this) || this; - _this._dateTime = dateTime; - _this._offset = offset; - _this._zone = zone; - return _this; - } + node.prev = node.next = null; + this.length -= 1; + return node; + } - var _proto = ZonedDateTime.prototype; + empty () { + while(this.head) this.shift(); + return this; + } - _proto._resolveLocal = function _resolveLocal(newDateTime) { - requireNonNull(newDateTime, 'newDateTime'); - return ZonedDateTime.ofLocal(newDateTime, this._zone, this._offset); - }; + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } - _proto._resolveInstant = function _resolveInstant(newDateTime) { - return ZonedDateTime.ofInstant3(newDateTime, this._offset, this._zone); - }; + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } - _proto._resolveOffset = function _resolveOffset(offset) { - if (offset.equals(this._offset) === false && this._zone.rules().isValidOffset(this._dateTime, offset)) { - return new ZonedDateTime(this._dateTime, offset, this._zone); + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); } - return this; - }; + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return true; - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); + shift() { + return this.head && this.removeLink(this.head); } - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; + pop() { + return this.tail && this.removeLink(this.tail); + } - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (field === ChronoField.INSTANT_SECONDS || field === ChronoField.OFFSET_SECONDS) { - return field.range(); - } + toArray() { + return [...this] + } - return this._dateTime.range(field); + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } } - return field.rangeRefinedBy(this); - }; + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } + } - _proto.get = function get(field) { - return this.getLong(field); - }; + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } - _proto.getLong = function getLong(field) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.INSTANT_SECONDS: - return this.toEpochSecond(); + function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } - case ChronoField.OFFSET_SECONDS: - return this._offset.totalSeconds(); - } + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; - return this._dateTime.getLong(field); + function on (event, handler) { + events[event].push(handler); } - requireNonNull(field, 'field'); - return field.getFrom(this); - }; + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } - _proto.offset = function offset() { - return this._offset; - }; + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } - _proto.withEarlierOffsetAtOverlap = function withEarlierOffsetAtOverlap() { - var trans = this._zone.rules().transition(this._dateTime); + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } - if (trans != null && trans.isOverlap()) { - var earlierOffset = trans.offsetBefore(); + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; - if (earlierOffset.equals(this._offset) === false) { - return new ZonedDateTime(this._dateTime, earlierOffset, this._zone); - } - } + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } - return this; - }; + var item = { + data, + callback: rejectOnError ? + promiseCallback : + (callback || promiseCallback) + }; - _proto.withLaterOffsetAtOverlap = function withLaterOffsetAtOverlap() { - var trans = this._zone.rules().transition(this.toLocalDateTime()); + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } - if (trans != null) { - var laterOffset = trans.offsetAfter(); + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } - if (laterOffset.equals(this._offset) === false) { - return new ZonedDateTime(this._dateTime, laterOffset, this._zone); - } + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } } - return this; - }; + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; - _proto.zone = function zone() { - return this._zone; - }; + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; - _proto.withZoneSameLocal = function withZoneSameLocal(zone) { - requireNonNull(zone, 'zone'); - return this._zone.equals(zone) ? this : ZonedDateTime.ofLocal(this._dateTime, zone, this._offset); - }; + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } - _proto.withZoneSameInstant = function withZoneSameInstant(zone) { - requireNonNull(zone, 'zone'); - return this._zone.equals(zone) ? this : ZonedDateTime._create(this._dateTime.toEpochSecond(this._offset), this._dateTime.nano(), zone); - }; + task.callback(err, ...args); - _proto.withFixedOffsetZone = function withFixedOffsetZone() { - return this._zone.equals(this._offset) ? this : new ZonedDateTime(this._dateTime, this._offset, this._offset); - }; + if (err != null) { + trigger('error', err, task.data); + } + } - _proto.year = function year() { - return this._dateTime.year(); - }; + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } - _proto.monthValue = function monthValue() { - return this._dateTime.monthValue(); - }; + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } - _proto.month = function month() { - return this._dateTime.month(); - }; + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } - _proto.dayOfMonth = function dayOfMonth() { - return this._dateTime.dayOfMonth(); - }; + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); - _proto.dayOfYear = function dayOfYear() { - return this._dateTime.dayOfYear(); - }; + }; - _proto.dayOfWeek = function dayOfWeek() { - return this._dateTime.dayOfWeek(); - }; + var isProcessing = false; + var q = { + _tasks: new DLL(), + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } - _proto.hour = function hour() { - return this._dateTime.hour(); - }; + numRunning += 1; - _proto.minute = function minute() { - return this._dateTime.minute(); - }; + if (q._tasks.length === 0) { + trigger('empty'); + } - _proto.second = function second() { - return this._dateTime.second(); - }; + if (numRunning === q.concurrency) { + trigger('saturated'); + } - _proto.nano = function nano() { - return this._dateTime.nano(); - }; + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } - _proto.withAdjuster = function withAdjuster(adjuster) { - if (adjuster instanceof LocalDate) { - return this._resolveLocal(LocalDateTime.of(adjuster, this._dateTime.toLocalTime())); - } else if (adjuster instanceof LocalTime) { - return this._resolveLocal(LocalDateTime.of(this._dateTime.toLocalDate(), adjuster)); - } else if (adjuster instanceof LocalDateTime) { - return this._resolveLocal(adjuster); - } else if (adjuster instanceof Instant) { - var instant = adjuster; - return ZonedDateTime._create(instant.epochSecond(), instant.nano(), this._zone); - } else if (adjuster instanceof ZoneOffset) { - return this._resolveOffset(adjuster); - } - - requireNonNull(adjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); + + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; - _proto.withFieldValue = function withFieldValue(field, newValue) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.INSTANT_SECONDS: - return ZonedDateTime._create(newValue, this.nano(), this._zone); + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } - case ChronoField.OFFSET_SECONDS: - { - var offset = ZoneOffset.ofTotalSeconds(field.checkValidIntValue(newValue)); - return this._resolveOffset(offset); - } - } + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); - return this._resolveLocal(this._dateTime.with(field, newValue)); - } + return cb[PROMISE_SYMBOL] + }; + } - return field.adjustInto(this, newValue); - }; + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); + } - _proto.withYear = function withYear(year) { - return this._resolveLocal(this._dateTime.withYear(year)); - }; + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) + } + var mapLimit$1 = awaitify(mapLimit, 4); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } - _proto.withMonth = function withMonth(month) { - return this._resolveLocal(this._dateTime.withMonth(month)); - }; + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - return this._resolveLocal(this._dateTime.withDayOfMonth(dayOfMonth)); - }; + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { + * // files is now a list of filenames that exist in the 3 directories + * }); + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); - _proto.withDayOfYear = function withDayOfYear(dayOfYear) { - return this._resolveLocal(this._dateTime.withDayOfYear(dayOfYear)); - }; + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); + + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } - _proto.withHour = function withHour(hour) { - return this._resolveLocal(this._dateTime.withHour(hour)); - }; + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); - _proto.withMinute = function withMinute(minute) { - return this._resolveLocal(this._dateTime.withMinute(minute)); - }; + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } - _proto.withSecond = function withSecond(second) { - return this._resolveLocal(this._dateTime.withSecond(second)); - }; + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. - _proto.withNano = function withNano(nanoOfSecond) { - return this._resolveLocal(this._dateTime.withNano(nanoOfSecond)); - }; + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns A Promise, if no callback is passed + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); - _proto.truncatedTo = function truncatedTo(unit) { - return this._resolveLocal(this._dateTime.truncatedTo(unit)); - }; + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) + } + var detectLimit$1 = awaitify(detectLimit, 4); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) + } + + var detectSeries$1 = awaitify(detectSeries, 3); + + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + resultArgs.forEach(x => console[name](x)); + } + } + }) + } - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount); - return amount.addTo(this); - }; + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - if (unit instanceof ChronoUnit) { - if (unit.isDateBased()) { - return this._resolveLocal(this._dateTime.plus(amountToAdd, unit)); - } else { - return this._resolveInstant(this._dateTime.plus(amountToAdd, unit)); - } + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); } - requireNonNull(unit, 'unit'); - return unit.addTo(this, amountToAdd); - }; - - _proto.plusYears = function plusYears(years) { - return this._resolveLocal(this._dateTime.plusYears(years)); - }; + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } - _proto.plusMonths = function plusMonths(months) { - return this._resolveLocal(this._dateTime.plusMonths(months)); - }; + return check(null, true); + } - _proto.plusWeeks = function plusWeeks(weeks) { - return this._resolveLocal(this._dateTime.plusWeeks(weeks)); - }; + var doWhilst$1 = awaitify(doWhilst, 3); - _proto.plusDays = function plusDays(days) { - return this._resolveLocal(this._dateTime.plusDays(days)); - }; + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } + + function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } + + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ + function eachLimit(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + + var each = awaitify(eachLimit, 3); + + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + var eachLimit$2 = awaitify(eachLimit$1, 4); + + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$2(coll, 1, iteratee, callback) + } + var eachSeries$1 = awaitify(eachSeries, 3); + + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } - _proto.plusHours = function plusHours(hours) { - return this._resolveInstant(this._dateTime.plusHours(hours)); - }; + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) + } + var every$1 = awaitify(every, 3); - _proto.plusMinutes = function plusMinutes(minutes) { - return this._resolveInstant(this._dateTime.plusMinutes(minutes)); - }; + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) + } + var everyLimit$1 = awaitify(everyLimit, 4); + + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) + } + var everySeries$1 = awaitify(everySeries, 3); + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } - _proto.plusSeconds = function plusSeconds(seconds) { - return this._resolveInstant(this._dateTime.plusSeconds(seconds)); - }; + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); + } - _proto.plusNanos = function plusNanos(nanos) { - return this._resolveInstant(this._dateTime.plusNanos(nanos)); - }; + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) + } + var filter$1 = awaitify(filter, 3); - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit(limit), coll, iteratee, callback) + } + var filterLimit$1 = awaitify(filterLimit, 4); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) + } + var filterSeries$1 = awaitify(filterSeries, 3); + + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); - _proto.minusYears = function minusYears(years) { - return this.plusYears(-1 * years); - }; + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); - _proto.minusMonths = function minusMonths(months) { - return this.plusMonths(-1 * months); - }; + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } - _proto.minusWeeks = function minusWeeks(weeks) { - return this.plusWeeks(-1 * weeks); - }; + return callback(err, result); + }); + } - _proto.minusDays = function minusDays(days) { - return this.plusDays(-1 * days); - }; + var groupByLimit$1 = awaitify(groupByLimit, 4); - _proto.minusHours = function minusHours(hours) { - return this.plusHours(-1 * hours); - }; + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) + } - _proto.minusMinutes = function minusMinutes(minutes) { - return this.plusMinutes(-1 * minutes); - }; + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) + } + + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); - _proto.minusSeconds = function minusSeconds(seconds) { - return this.plusSeconds(-1 * seconds); - }; + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); + } + + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) + } + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) + } + + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } - _proto.minusNanos = function minusNanos(nanos) { - return this.plusNanos(-1 * nanos); - }; + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer$1; - _proto.query = function query(_query) { - if (_query === TemporalQueries.localDate()) { - return this.toLocalDate(); - } + if (hasNextTick) { + _defer$1 = process.nextTick; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else { + _defer$1 = fallback; + } - requireNonNull(_query, 'query'); - return _ChronoZonedDateTime.prototype.query.call(this, _query); - }; + var nextTick = wrap(_defer$1); - _proto.until = function until(endExclusive, unit) { - var end = ZonedDateTime.from(endExclusive); + var parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; - if (unit instanceof ChronoUnit) { - end = end.withZoneSameInstant(this._zone); + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); - if (unit.isDateBased()) { - return this._dateTime.until(end._dateTime, unit); - } else { - var difference = this._offset.totalSeconds() - end._offset.totalSeconds(); + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ + function parallel$1(tasks, callback) { + return parallel(eachOf$1, tasks, callback); + } + + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return parallel(eachOfLimit(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = aync.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ - var adjustedEnd = end._dateTime.plusSeconds(difference); + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue$1 (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); + } - return this._dateTime.until(adjustedEnd, unit); - } + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; } - return unit.between(this, end); - }; - - _proto.toLocalDateTime = function toLocalDateTime() { - return this._dateTime; - }; - - _proto.toLocalDate = function toLocalDate() { - return this._dateTime.toLocalDate(); - }; - - _proto.toLocalTime = function toLocalTime() { - return this._dateTime.toLocalTime(); - }; - - _proto.toOffsetDateTime = function toOffsetDateTime() { - return OffsetDateTime.of(this._dateTime, this._offset); - }; - - _proto.equals = function equals(other) { - if (this === other) { - return true; + get length() { + return this.heap.length; } - if (other instanceof ZonedDateTime) { - return this._dateTime.equals(other._dateTime) && this._offset.equals(other._offset) && this._zone.equals(other._zone); + empty () { + this.heap = []; + return this; } - return false; - }; - - _proto.hashCode = function hashCode() { - return MathUtil.hashCode(this._dateTime.hashCode(), this._offset.hashCode(), this._zone.hashCode()); - }; + percUp(index) { + let p; - _proto.toString = function toString() { - var str = this._dateTime.toString() + this._offset.toString(); + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; - if (this._offset !== this._zone) { - str += '[' + this._zone.toString() + ']'; + index = p; + } } - return str; - }; - - _proto.toJSON = function toJSON() { - return this.toString(); - }; - - _proto.format = function format(formatter) { - return _ChronoZonedDateTime.prototype.format.call(this, formatter); - }; - - return ZonedDateTime; - }(ChronoZonedDateTime); - function _init$g() { - ZonedDateTime.FROM = createTemporalQuery('ZonedDateTime.FROM', function (temporal) { - return ZonedDateTime.from(temporal); - }); - } - - var OffsetDateTime = function (_DefaultInterfaceTemp) { - _inheritsLoose(OffsetDateTime, _DefaultInterfaceTemp); + percDown(index) { + let l; - OffsetDateTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } - if (temporal instanceof OffsetDateTime) { - return temporal; - } + if (smaller(this.heap[index], this.heap[l])) { + break; + } - try { - var offset = ZoneOffset.from(temporal); + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; - try { - var ldt = LocalDateTime.from(temporal); - return OffsetDateTime.of(ldt, offset); - } catch (_) { - var instant = Instant.from(temporal); - return OffsetDateTime.ofInstant(instant, offset); - } - } catch (ex) { - throw new DateTimeException("Unable to obtain OffsetDateTime TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); + index = l; + } } - }; - - OffsetDateTime.now = function now(clockOrZone) { - if (arguments.length === 0) { - return OffsetDateTime.now(Clock.systemDefaultZone()); - } else { - requireNonNull(clockOrZone, 'clockOrZone'); - if (clockOrZone instanceof ZoneId) { - return OffsetDateTime.now(Clock.system(clockOrZone)); - } else if (clockOrZone instanceof Clock) { - var now = clockOrZone.instant(); - return OffsetDateTime.ofInstant(now, clockOrZone.zone().rules().offset(now)); - } else { - throw new IllegalArgumentException('clockOrZone must be an instance of ZoneId or Clock'); - } + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); } - }; - OffsetDateTime.of = function of() { - if (arguments.length <= 2) { - return OffsetDateTime.ofDateTime.apply(this, arguments); - } else if (arguments.length === 3) { - return OffsetDateTime.ofDateAndTime.apply(this, arguments); - } else { - return OffsetDateTime.ofNumbers.apply(this, arguments); + unshift(node) { + return this.heap.push(node); } - }; - OffsetDateTime.ofDateTime = function ofDateTime(dateTime, offset) { - return new OffsetDateTime(dateTime, offset); - }; + shift() { + let [top] = this.heap; - OffsetDateTime.ofDateAndTime = function ofDateAndTime(date, time, offset) { - var dt = LocalDateTime.of(date, time); - return new OffsetDateTime(dt, offset); - }; + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); - OffsetDateTime.ofNumbers = function ofNumbers(year, month, dayOfMonth, hour, minute, second, nanoOfSecond, offset) { - if (hour === void 0) { - hour = 0; + return top; } - if (minute === void 0) { - minute = 0; + toArray() { + return [...this]; } - if (second === void 0) { - second = 0; + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } } - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } - var dt = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond); - return new OffsetDateTime(dt, offset); - }; + this.heap.splice(j); - OffsetDateTime.ofInstant = function ofInstant(instant, zone) { - requireNonNull(instant, 'instant'); - requireNonNull(zone, 'zone'); - var rules = zone.rules(); - var offset = rules.offset(instant); - var ldt = LocalDateTime.ofEpochSecond(instant.epochSecond(), instant.nano(), offset); - return new OffsetDateTime(ldt, offset); - }; + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } - OffsetDateTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + return this; } + } - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, OffsetDateTime.FROM); - }; - - function OffsetDateTime(dateTime, offset) { - var _this; - - _this = _DefaultInterfaceTemp.call(this) || this; - requireNonNull(dateTime, 'dateTime'); - requireInstance(dateTime, LocalDateTime, 'dateTime'); - requireNonNull(offset, 'offset'); - requireInstance(offset, ZoneOffset, 'offset'); - _this._dateTime = dateTime; - _this._offset = offset; - return _this; - } - - var _proto = OffsetDateTime.prototype; - - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.EPOCH_DAY, this.toLocalDate().toEpochDay()).with(ChronoField.NANO_OF_DAY, this.toLocalTime().toNanoOfDay()).with(ChronoField.OFFSET_SECONDS, this.offset().totalSeconds()); - }; + function leftChi(i) { + return (i<<1)+1; + } - _proto.until = function until(endExclusive, unit) { - var end = OffsetDateTime.from(endExclusive); + function parent(i) { + return ((i+1)>>1)-1; + } - if (unit instanceof ChronoUnit) { - end = end.withOffsetSameInstant(this._offset); - return this._dateTime.until(end._dateTime, unit); + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; } - - return unit.between(this, end); - }; - - _proto.atZoneSameInstant = function atZoneSameInstant(zone) { - return ZonedDateTime.ofInstant(this._dateTime, this._offset, zone); - }; - - _proto.atZoneSimilarLocal = function atZoneSimilarLocal(zone) { - return ZonedDateTime.ofLocal(this._dateTime, zone, this._offset); - }; - - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - - if (_query === TemporalQueries.chronology()) { - return IsoChronology.INSTANCE; - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.offset() || _query === TemporalQueries.zone()) { - return this.offset(); - } else if (_query === TemporalQueries.localDate()) { - return this.toLocalDate(); - } else if (_query === TemporalQueries.localTime()) { - return this.toLocalTime(); - } else if (_query === TemporalQueries.zoneId()) { - return null; + else { + return x.pushCount < y.pushCount; } + } - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue$1(worker, concurrency); + + q._tasks = new Heap(); + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback = () => {}) { + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!Array.isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(() => q.drain()); + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority, + callback + }; - _proto.get = function get(field) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.INSTANT_SECONDS: - throw new DateTimeException('Field too large for an int: ' + field); + q._tasks.push(item); + } - case ChronoField.OFFSET_SECONDS: - return this.offset().totalSeconds(); - } + setImmediate$1(q.process); + }; - return this._dateTime.get(field); - } + // Remove unshift function + delete q.unshift; - return _DefaultInterfaceTemp.prototype.get.call(this, field); - }; + return q; + } - _proto.getLong = function getLong(field) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.INSTANT_SECONDS: - return this.toEpochSecond(); + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + var race$1 = awaitify(race, 2); + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); + } + + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); - case ChronoField.OFFSET_SECONDS: - return this.offset().totalSeconds(); - } + return _fn.apply(this, args); + }); + } - return this._dateTime.getLong(field); + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); } + return results; + } - return field.getFrom(this); - }; - - _proto.offset = function offset() { - return this._offset; - }; - - _proto.year = function year() { - return this._dateTime.year(); - }; + function reject(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } - _proto.monthValue = function monthValue() { - return this._dateTime.monthValue(); - }; + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ + function reject$1 (coll, iteratee, callback) { + return reject(eachOf$1, coll, iteratee, callback) + } + var reject$2 = awaitify(reject$1, 3); - _proto.month = function month() { - return this._dateTime.month(); - }; + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject(eachOfLimit(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject(eachOfSeries$1, coll, iteratee, callback) + } + var rejectSeries$1 = awaitify(rejectSeries, 3); + + function constant$1(value) { + return function () { + return value; + } + } - _proto.dayOfMonth = function dayOfMonth() { - return this._dateTime.dayOfMonth(); - }; + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; - _proto.dayOfYear = function dayOfYear() { - return this._dateTime.dayOfYear(); - }; + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant$1(DEFAULT_INTERVAL) + }; - _proto.dayOfWeek = function dayOfWeek() { - return this._dateTime.dayOfWeek(); - }; + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } - _proto.hour = function hour() { - return this._dateTime.hour(); - }; + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } - _proto.minute = function minute() { - return this._dateTime.minute(); - }; + var _task = wrapAsync(task); - _proto.second = function second() { - return this._dateTime.second(); - }; + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } - _proto.nano = function nano() { - return this._dateTime.nano(); - }; + retryAttempt(); + return callback[PROMISE_SYMBOL] + } - _proto.toLocalDateTime = function toLocalDateTime() { - return this._dateTime; - }; + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; - _proto.toLocalDate = function toLocalDate() { - return this._dateTime.toLocalDate(); - }; + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant$1(+t.interval || DEFAULT_INTERVAL); - _proto.toLocalTime = function toLocalTime() { - return this._dateTime.toLocalTime(); - }; + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } - _proto.toOffsetTime = function toOffsetTime() { - return OffsetTime.of(this._dateTime.toLocalTime(), this._offset); - }; + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } - _proto.toZonedDateTime = function toZonedDateTime() { - return ZonedDateTime.of(this._dateTime, this._offset); - }; + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); - _proto.toInstant = function toInstant() { - return this._dateTime.toInstant(this._offset); - }; + return callback[PROMISE_SYMBOL] + }); + } - _proto.toEpochSecond = function toEpochSecond() { - return this._dateTime.toEpochSecond(this._offset); - }; + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ + function series(tasks, callback) { + return parallel(eachOfSeries$1, tasks, callback); + } + + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) + } + var some$1 = awaitify(some, 3); - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); - } + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) + } + var someLimit$1 = awaitify(someLimit, 4); + + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); + + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); - if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; } + } + var sortBy$1 = awaitify(sortBy, 3); - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (field === ChronoField.INSTANT_SECONDS || field === ChronoField.OFFSET_SECONDS) { - return field.range(); - } + return initialParams((args, callback) => { + var timedOut = false; + var timer; - return this._dateTime.range(field); - } + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } - return field.rangeRefinedBy(this); - }; + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster); + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); + } - if (adjuster instanceof LocalDate || adjuster instanceof LocalTime || adjuster instanceof LocalDateTime) { - return this._withDateTimeOffset(this._dateTime.with(adjuster), this._offset); - } else if (adjuster instanceof Instant) { - return OffsetDateTime.ofInstant(adjuster, this._offset); - } else if (adjuster instanceof ZoneOffset) { - return this._withDateTimeOffset(this._dateTime, adjuster); - } else if (adjuster instanceof OffsetDateTime) { - return adjuster; + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; } + return result; + } - return adjuster.adjustInto(this); - }; - - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field); + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); + } + + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) + } - if (field instanceof ChronoField) { - var f = field; + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) + } + + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc[index] = item * 2 + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] + } + + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); - switch (f) { - case ChronoField.INSTANT_SECONDS: - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(newValue, this.nano()), this._offset); + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } - case ChronoField.OFFSET_SECONDS: - { - return this._withDateTimeOffset(this._dateTime, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue))); - } - } + var tryEach$1 = awaitify(tryEach); - return this._withDateTimeOffset(this._dateTime.with(field, newValue), this._offset); - } + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } - return field.adjustInto(this, newValue); - }; + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; - _proto._withDateTimeOffset = function _withDateTimeOffset(dateTime, offset) { - if (this._dateTime === dateTime && this._offset.equals(offset)) { - return this; + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); } - return new OffsetDateTime(dateTime, offset); - }; + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } - _proto.withYear = function withYear(year) { - return this._withDateTimeOffset(this._dateTime.withYear(year), this._offset); - }; + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); - _proto.withMonth = function withMonth(month) { - return this._withDateTimeOffset(this._dateTime.withMonth(month), this._offset); - }; + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(page, cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } + + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); + } + + var waterfall$1 = awaitify(waterfall); + + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + var index = { + apply, + applyEach: applyEach$1, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo, + cargoQueue: cargo$1, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$2, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$2, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel: parallel$1, + parallelLimit, + priorityQueue, + queue: queue$1, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$2, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$2, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$2, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; + + exports.default = index; + exports.apply = apply; + exports.applyEach = applyEach$1; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo; + exports.cargoQueue = cargo$1; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.each = each; + exports.eachLimit = eachLimit$2; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$2; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel$1; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue$1; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$2; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.forEach = each; + exports.forEachSeries = eachSeries$1; + exports.forEachLimit = eachLimit$2; + exports.forEachOf = eachOf$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachOfLimit = eachOfLimit$2; + exports.inject = reduce$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.wrapSync = asyncify; + exports.during = whilst$1; + exports.doDuring = doWhilst$1; - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - return this._withDateTimeOffset(this._dateTime.withDayOfMonth(dayOfMonth), this._offset); - }; + Object.defineProperty(exports, '__esModule', { value: true }); - _proto.withDayOfYear = function withDayOfYear(dayOfYear) { - return this._withDateTimeOffset(this._dateTime.withDayOfYear(dayOfYear), this._offset); - }; +}))); - _proto.withHour = function withHour(hour) { - return this._withDateTimeOffset(this._dateTime.withHour(hour), this._offset); - }; - _proto.withMinute = function withMinute(minute) { - return this._withDateTimeOffset(this._dateTime.withMinute(minute), this._offset); - }; +/***/ }), - _proto.withSecond = function withSecond(second) { - return this._withDateTimeOffset(this._dateTime.withSecond(second), this._offset); - }; +/***/ 14812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.withNano = function withNano(nanoOfSecond) { - return this._withDateTimeOffset(this._dateTime.withNano(nanoOfSecond), this._offset); - }; +module.exports = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(50445), + serialOrdered : __nccwpck_require__(3578) +}; - _proto.withOffsetSameLocal = function withOffsetSameLocal(offset) { - requireNonNull(offset, 'offset'); - return this._withDateTimeOffset(this._dateTime, offset); - }; - _proto.withOffsetSameInstant = function withOffsetSameInstant(offset) { - requireNonNull(offset, 'offset'); +/***/ }), - if (offset.equals(this._offset)) { - return this; - } +/***/ 1700: +/***/ ((module) => { - var difference = offset.totalSeconds() - this._offset.totalSeconds(); +// API +module.exports = abort; - var adjusted = this._dateTime.plusSeconds(difference); +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); - return new OffsetDateTime(adjusted, offset); - }; + // reset leftover jobs + state.jobs = {}; +} - _proto.truncatedTo = function truncatedTo(unit) { - return this._withDateTimeOffset(this._dateTime.truncatedTo(unit), this._offset); - }; +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } +} - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - if (unit instanceof ChronoUnit) { - return this._withDateTimeOffset(this._dateTime.plus(amountToAdd, unit), this._offset); - } +/***/ }), - return unit.addTo(this, amountToAdd); - }; +/***/ 72794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.plusYears = function plusYears(years) { - return this._withDateTimeOffset(this._dateTime.plusYears(years), this._offset); - }; +var defer = __nccwpck_require__(15295); - _proto.plusMonths = function plusMonths(months) { - return this._withDateTimeOffset(this._dateTime.plusMonths(months), this._offset); - }; +// API +module.exports = async; - _proto.plusWeeks = function plusWeeks(weeks) { - return this._withDateTimeOffset(this._dateTime.plusWeeks(weeks), this._offset); - }; +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; - _proto.plusDays = function plusDays(days) { - return this._withDateTimeOffset(this._dateTime.plusDays(days), this._offset); - }; + // check if async happened + defer(function() { isAsync = true; }); - _proto.plusHours = function plusHours(hours) { - return this._withDateTimeOffset(this._dateTime.plusHours(hours), this._offset); - }; + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} - _proto.plusMinutes = function plusMinutes(minutes) { - return this._withDateTimeOffset(this._dateTime.plusMinutes(minutes), this._offset); - }; - _proto.plusSeconds = function plusSeconds(seconds) { - return this._withDateTimeOffset(this._dateTime.plusSeconds(seconds), this._offset); - }; +/***/ }), - _proto.plusNanos = function plusNanos(nanos) { - return this._withDateTimeOffset(this._dateTime.plusNanos(nanos), this._offset); - }; +/***/ 15295: +/***/ ((module) => { - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount); - return amount.subtractFrom(this); - }; +module.exports = defer; - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return this.plus(-1 * amountToSubtract, unit); - }; +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); - _proto.minusYears = function minusYears(years) { - return this._withDateTimeOffset(this._dateTime.minusYears(years), this._offset); - }; + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} - _proto.minusMonths = function minusMonths(months) { - return this._withDateTimeOffset(this._dateTime.minusMonths(months), this._offset); - }; - _proto.minusWeeks = function minusWeeks(weeks) { - return this._withDateTimeOffset(this._dateTime.minusWeeks(weeks), this._offset); - }; +/***/ }), - _proto.minusDays = function minusDays(days) { - return this._withDateTimeOffset(this._dateTime.minusDays(days), this._offset); - }; +/***/ 9023: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.minusHours = function minusHours(hours) { - return this._withDateTimeOffset(this._dateTime.minusHours(hours), this._offset); - }; +var async = __nccwpck_require__(72794) + , abort = __nccwpck_require__(1700) + ; - _proto.minusMinutes = function minusMinutes(minutes) { - return this._withDateTimeOffset(this._dateTime.minusMinutes(minutes), this._offset); - }; +// API +module.exports = iterate; - _proto.minusSeconds = function minusSeconds(seconds) { - return this._withDateTimeOffset(this._dateTime.minusSeconds(seconds), this._offset); - }; +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - _proto.minusNanos = function minusNanos(nanos) { - return this._withDateTimeOffset(this._dateTime.minusNanos(nanos), this._offset); - }; + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, OffsetDateTime, 'other'); + // clean up jobs + delete state.jobs[key]; - if (this.offset().equals(other.offset())) { - return this.toLocalDateTime().compareTo(other.toLocalDateTime()); - } + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } - var cmp = MathUtil.compareNumbers(this.toEpochSecond(), other.toEpochSecond()); + // return salvaged results + callback(error, state.results); + }); +} - if (cmp === 0) { - cmp = this.toLocalTime().nano() - other.toLocalTime().nano(); +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; - if (cmp === 0) { - cmp = this.toLocalDateTime().compareTo(other.toLocalDateTime()); - } - } + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } - return cmp; - }; + return aborter; +} - _proto.isAfter = function isAfter(other) { - requireNonNull(other, 'other'); - var thisEpochSec = this.toEpochSecond(); - var otherEpochSec = other.toEpochSecond(); - return thisEpochSec > otherEpochSec || thisEpochSec === otherEpochSec && this.toLocalTime().nano() > other.toLocalTime().nano(); - }; - _proto.isBefore = function isBefore(other) { - requireNonNull(other, 'other'); - var thisEpochSec = this.toEpochSecond(); - var otherEpochSec = other.toEpochSecond(); - return thisEpochSec < otherEpochSec || thisEpochSec === otherEpochSec && this.toLocalTime().nano() < other.toLocalTime().nano(); - }; +/***/ }), - _proto.isEqual = function isEqual(other) { - requireNonNull(other, 'other'); - return this.toEpochSecond() === other.toEpochSecond() && this.toLocalTime().nano() === other.toLocalTime().nano(); - }; +/***/ 42474: +/***/ ((module) => { - _proto.equals = function equals(other) { - if (this === other) { - return true; - } +// API +module.exports = state; - if (other instanceof OffsetDateTime) { - return this._dateTime.equals(other._dateTime) && this._offset.equals(other._offset); - } +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; - return false; - }; + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } - _proto.hashCode = function hashCode() { - return this._dateTime.hashCode() ^ this._offset.hashCode(); - }; + return initState; +} - _proto.toString = function toString() { - return this._dateTime.toString() + this._offset.toString(); - }; - _proto.toJSON = function toJSON() { - return this.toString(); - }; +/***/ }), - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return OffsetDateTime; - }(DefaultInterfaceTemporal); - function _init$h() { - OffsetDateTime.MIN = LocalDateTime.MIN.atOffset(ZoneOffset.MAX); - OffsetDateTime.MAX = LocalDateTime.MAX.atOffset(ZoneOffset.MIN); - OffsetDateTime.FROM = createTemporalQuery('OffsetDateTime.FROM', function (temporal) { - return OffsetDateTime.from(temporal); - }); - } +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(72794) + ; - var DAYS_PER_CYCLE = 146097; - var DAYS_0000_TO_1970 = DAYS_PER_CYCLE * 5 - (30 * 365 + 7); - var LocalDate = function (_ChronoLocalDate) { - _inheritsLoose(LocalDate, _ChronoLocalDate); +// API +module.exports = terminator; - LocalDate.now = function now(clockOrZone) { - var clock; +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } - if (clockOrZone == null) { - clock = Clock.systemDefaultZone(); - } else if (clockOrZone instanceof ZoneId) { - clock = Clock.system(clockOrZone); - } else { - clock = clockOrZone; - } + // fast forward iteration index + this.index = this.size; - return LocalDate.ofInstant(clock.instant(), clock.zone()); - }; + // abort jobs + abort(this); - LocalDate.ofInstant = function ofInstant(instant, zone) { - if (zone === void 0) { - zone = ZoneId.systemDefault(); - } + // send back results we have so far + async(callback)(null, this.results); +} - requireNonNull(instant, 'instant'); - var offset = zone.rules().offset(instant); - var epochSec = instant.epochSecond() + offset.totalSeconds(); - var epochDay = MathUtil.floorDiv(epochSec, LocalTime.SECONDS_PER_DAY); - return LocalDate.ofEpochDay(epochDay); - }; - LocalDate.of = function of(year, month, dayOfMonth) { - return new LocalDate(year, month, dayOfMonth); - }; +/***/ }), - LocalDate.ofYearDay = function ofYearDay(year, dayOfYear) { - ChronoField.YEAR.checkValidValue(year); - var leap = IsoChronology.isLeapYear(year); +/***/ 8210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (dayOfYear === 366 && leap === false) { - assert(false, 'Invalid date \'DayOfYear 366\' as \'' + year + '\' is not a leap year', DateTimeException); - } +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - var moy = Month.of(Math.floor((dayOfYear - 1) / 31 + 1)); - var monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1; +// Public API +module.exports = parallel; - if (dayOfYear > monthEnd) { - moy = moy.plus(1); - } +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); - var dom = dayOfYear - moy.firstDayOfYear(leap) + 1; - return new LocalDate(year, moy.value(), dom); - }; + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } - LocalDate.ofEpochDay = function ofEpochDay(epochDay) { - if (epochDay === void 0) { - epochDay = 0; - } + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); - var adjust, adjustCycles, doyEst, yearEst, zeroDay; - zeroDay = epochDay + DAYS_0000_TO_1970; - zeroDay -= 60; - adjust = 0; + state.index++; + } - if (zeroDay < 0) { - adjustCycles = MathUtil.intDiv(zeroDay + 1, DAYS_PER_CYCLE) - 1; - adjust = adjustCycles * 400; - zeroDay += -adjustCycles * DAYS_PER_CYCLE; - } + return terminator.bind(state, callback); +} - yearEst = MathUtil.intDiv(400 * zeroDay + 591, DAYS_PER_CYCLE); - doyEst = zeroDay - (365 * yearEst + MathUtil.intDiv(yearEst, 4) - MathUtil.intDiv(yearEst, 100) + MathUtil.intDiv(yearEst, 400)); - if (doyEst < 0) { - yearEst--; - doyEst = zeroDay - (365 * yearEst + MathUtil.intDiv(yearEst, 4) - MathUtil.intDiv(yearEst, 100) + MathUtil.intDiv(yearEst, 400)); - } +/***/ }), - yearEst += adjust; - var marchDoy0 = doyEst; - var marchMonth0 = MathUtil.intDiv(marchDoy0 * 5 + 2, 153); - var month = (marchMonth0 + 2) % 12 + 1; - var dom = marchDoy0 - MathUtil.intDiv(marchMonth0 * 306 + 5, 10) + 1; - yearEst += MathUtil.intDiv(marchMonth0, 10); - var year = yearEst; - return new LocalDate(year, month, dom); - }; +/***/ 50445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - LocalDate.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - var date = temporal.query(TemporalQueries.localDate()); +var serialOrdered = __nccwpck_require__(3578); - if (date == null) { - throw new DateTimeException("Unable to obtain LocalDate from TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); - } +// Public API +module.exports = serial; - return date; - }; +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} - LocalDate.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_LOCAL_DATE; - } - assert(formatter != null, 'formatter', NullPointerException); - return formatter.parse(text, LocalDate.FROM); - }; +/***/ }), - LocalDate._resolvePreviousValid = function _resolvePreviousValid(year, month, day) { - switch (month) { - case 2: - day = Math.min(day, IsoChronology.isLeapYear(year) ? 29 : 28); - break; +/***/ 3578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case 4: - case 6: - case 9: - case 11: - day = Math.min(day, 30); - break; - } +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - return LocalDate.of(year, month, day); - }; +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; - function LocalDate(year, month, dayOfMonth) { - var _this; +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); - _this = _ChronoLocalDate.call(this) || this; - requireNonNull(year, 'year'); - requireNonNull(month, 'month'); - requireNonNull(dayOfMonth, 'dayOfMonth'); + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } - if (month instanceof Month) { - month = month.value(); - } + state.index++; - _this._year = MathUtil.safeToInt(year); - _this._month = MathUtil.safeToInt(month); - _this._day = MathUtil.safeToInt(dayOfMonth); + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } - LocalDate._validate(_this._year, _this._month, _this._day); + // done here + callback(null, state.results); + }); - return _this; - } + return terminator.bind(state, callback); +} - LocalDate._validate = function _validate(year, month, dayOfMonth) { - var dom; - ChronoField.YEAR.checkValidValue(year); - ChronoField.MONTH_OF_YEAR.checkValidValue(month); - ChronoField.DAY_OF_MONTH.checkValidValue(dayOfMonth); +/* + * -- Sort methods + */ - if (dayOfMonth > 28) { - dom = 31; +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} - switch (month) { - case 2: - dom = IsoChronology.isLeapYear(year) ? 29 : 28; - break; +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} - case 4: - case 6: - case 9: - case 11: - dom = 30; - } - if (dayOfMonth > dom) { - if (dayOfMonth === 29) { - assert(false, 'Invalid date \'February 29\' as \'' + year + '\' is not a leap year', DateTimeException); - } else { - assert(false, 'Invalid date \'' + year + '\' \'' + month + '\' \'' + dayOfMonth + '\'', DateTimeException); - } - } - } - }; +/***/ }), - var _proto = LocalDate.prototype; +/***/ 96342: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.isSupported = function isSupported(field) { - return _ChronoLocalDate.prototype.isSupported.call(this, field); - }; - _proto.range = function range(field) { - if (field instanceof ChronoField) { - if (field.isDateBased()) { - switch (field) { - case ChronoField.DAY_OF_MONTH: - return ValueRange.of(1, this.lengthOfMonth()); +/*! + * Copyright 2010 LearnBoost + * + * 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. + */ - case ChronoField.DAY_OF_YEAR: - return ValueRange.of(1, this.lengthOfYear()); +/** + * Module dependencies. + */ - case ChronoField.ALIGNED_WEEK_OF_MONTH: - return ValueRange.of(1, this.month() === Month.FEBRUARY && this.isLeapYear() === false ? 4 : 5); +var crypto = __nccwpck_require__(76417) + , parse = __nccwpck_require__(78835).parse + ; - case ChronoField.YEAR_OF_ERA: - return this._year <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE); - } +/** + * Valid keys. + */ + +var keys = + [ 'acl' + , 'location' + , 'logging' + , 'notification' + , 'partNumber' + , 'policy' + , 'requestPayment' + , 'torrent' + , 'uploadId' + , 'uploads' + , 'versionId' + , 'versioning' + , 'versions' + , 'website' + ] - return field.range(); - } +/** + * Return an "Authorization" header value with the given `options` + * in the form of "AWS :" + * + * @param {Object} options + * @return {String} + * @api private + */ - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +function authorization (options) { + return 'AWS ' + options.key + ':' + sign(options) +} - return field.rangeRefinedBy(this); - }; +module.exports = authorization +module.exports.authorization = authorization - _proto.get = function get(field) { - return this.getLong(field); - }; +/** + * Simple HMAC-SHA1 Wrapper + * + * @param {Object} options + * @return {String} + * @api private + */ - _proto.getLong = function getLong(field) { - assert(field != null, '', NullPointerException); +function hmacSha1 (options) { + return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +} - if (field instanceof ChronoField) { - return this._get0(field); - } +module.exports.hmacSha1 = hmacSha1 - return field.getFrom(this); - }; +/** + * Create a base64 sha1 HMAC for `options`. + * + * @param {Object} options + * @return {String} + * @api private + */ - _proto._get0 = function _get0(field) { - switch (field) { - case ChronoField.DAY_OF_WEEK: - return this.dayOfWeek().value(); +function sign (options) { + options.message = stringToSign(options) + return hmacSha1(options) +} +module.exports.sign = sign - case ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH: - return MathUtil.intMod(this._day - 1, 7) + 1; +/** + * Create a base64 sha1 HMAC for `options`. + * + * Specifically to be used with S3 presigned URLs + * + * @param {Object} options + * @return {String} + * @api private + */ - case ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR: - return MathUtil.intMod(this.dayOfYear() - 1, 7) + 1; +function signQuery (options) { + options.message = queryStringToSign(options) + return hmacSha1(options) +} +module.exports.signQuery= signQuery - case ChronoField.DAY_OF_MONTH: - return this._day; +/** + * Return a string for sign() with the given `options`. + * + * Spec: + * + * \n + * \n + * \n + * \n + * [headers\n] + * + * + * @param {Object} options + * @return {String} + * @api private + */ - case ChronoField.DAY_OF_YEAR: - return this.dayOfYear(); +function stringToSign (options) { + var headers = options.amazonHeaders || '' + if (headers) headers += '\n' + var r = + [ options.verb + , options.md5 + , options.contentType + , options.date ? options.date.toUTCString() : '' + , headers + options.resource + ] + return r.join('\n') +} +module.exports.stringToSign = stringToSign - case ChronoField.EPOCH_DAY: - return this.toEpochDay(); +/** + * Return a string for sign() with the given `options`, but is meant exclusively + * for S3 presigned URLs + * + * Spec: + * + * \n + * + * + * @param {Object} options + * @return {String} + * @api private + */ - case ChronoField.ALIGNED_WEEK_OF_MONTH: - return MathUtil.intDiv(this._day - 1, 7) + 1; +function queryStringToSign (options){ + return 'GET\n\n\n' + options.date + '\n' + options.resource +} +module.exports.queryStringToSign = queryStringToSign - case ChronoField.ALIGNED_WEEK_OF_YEAR: - return MathUtil.intDiv(this.dayOfYear() - 1, 7) + 1; +/** + * Perform the following: + * + * - ignore non-amazon headers + * - lowercase fields + * - sort lexicographically + * - trim whitespace between ":" + * - join with newline + * + * @param {Object} headers + * @return {String} + * @api private + */ - case ChronoField.MONTH_OF_YEAR: - return this._month; +function canonicalizeHeaders (headers) { + var buf = [] + , fields = Object.keys(headers) + ; + for (var i = 0, len = fields.length; i < len; ++i) { + var field = fields[i] + , val = headers[field] + , field = field.toLowerCase() + ; + if (0 !== field.indexOf('x-amz')) continue + buf.push(field + ':' + val) + } + return buf.sort().join('\n') +} +module.exports.canonicalizeHeaders = canonicalizeHeaders - case ChronoField.PROLEPTIC_MONTH: - return this._prolepticMonth(); +/** + * Perform the following: + * + * - ignore non sub-resources + * - sort lexicographically + * + * @param {String} resource + * @return {String} + * @api private + */ - case ChronoField.YEAR_OF_ERA: - return this._year >= 1 ? this._year : 1 - this._year; +function canonicalizeResource (resource) { + var url = parse(resource, true) + , path = url.pathname + , buf = [] + ; - case ChronoField.YEAR: - return this._year; + Object.keys(url.query).forEach(function(key){ + if (!~keys.indexOf(key)) return + var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) + buf.push(key + val) + }) - case ChronoField.ERA: - return this._year >= 1 ? 1 : 0; - } + return path + (buf.length ? '?' + buf.sort().join('&') : '') +} +module.exports.canonicalizeResource = canonicalizeResource - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - }; - _proto._prolepticMonth = function _prolepticMonth() { - return this._year * 12 + (this._month - 1); - }; +/***/ }), - _proto.chronology = function chronology() { - return IsoChronology.INSTANCE; - }; +/***/ 16071: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _proto.year = function year() { - return this._year; - }; +var aws4 = exports, + url = __nccwpck_require__(78835), + querystring = __nccwpck_require__(71191), + crypto = __nccwpck_require__(76417), + lru = __nccwpck_require__(74225), + credentialsCache = lru(1000) - _proto.monthValue = function monthValue() { - return this._month; - }; +// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html - _proto.month = function month() { - return Month.of(this._month); - }; +function hmac(key, string, encoding) { + return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) +} - _proto.dayOfMonth = function dayOfMonth() { - return this._day; - }; +function hash(string, encoding) { + return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) +} - _proto.dayOfYear = function dayOfYear() { - return this.month().firstDayOfYear(this.isLeapYear()) + this._day - 1; - }; +// This function assumes the string has already been percent encoded +function encodeRfc3986(urlEncodedString) { + return urlEncodedString.replace(/[!'()*]/g, function(c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) +} - _proto.dayOfWeek = function dayOfWeek() { - var dow0 = MathUtil.floorMod(this.toEpochDay() + 3, 7); - return DayOfWeek.of(dow0 + 1); - }; +function encodeRfc3986Full(str) { + return encodeRfc3986(encodeURIComponent(str)) +} - _proto.isLeapYear = function isLeapYear() { - return IsoChronology.isLeapYear(this._year); - }; +// A bit of a combination of: +// https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59 +// https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199 +// https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34 +var HEADERS_TO_IGNORE = { + 'authorization': true, + 'connection': true, + 'x-amzn-trace-id': true, + 'user-agent': true, + 'expect': true, + 'presigned-expires': true, + 'range': true, +} - _proto.lengthOfMonth = function lengthOfMonth() { - switch (this._month) { - case 2: - return this.isLeapYear() ? 29 : 28; +// request: { path | body, [host], [method], [headers], [service], [region] } +// credentials: { accessKeyId, secretAccessKey, [sessionToken] } +function RequestSigner(request, credentials) { - case 4: - case 6: - case 9: - case 11: - return 30; + if (typeof request === 'string') request = url.parse(request) - default: - return 31; - } - }; + var headers = request.headers = (request.headers || {}), + hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) - _proto.lengthOfYear = function lengthOfYear() { - return this.isLeapYear() ? 366 : 365; - }; + this.request = request + this.credentials = credentials || this.defaultCredentials() - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); + this.service = request.service || hostParts[0] || '' + this.region = request.region || hostParts[1] || 'us-east-1' - if (adjuster instanceof LocalDate) { - return adjuster; - } + // SES uses a different domain from the service name + if (this.service === 'email') this.service = 'ses' - assert(typeof adjuster.adjustInto === 'function', 'adjuster', IllegalArgumentException); - return adjuster.adjustInto(this); - }; + if (!request.method && request.body) + request.method = 'POST' - _proto.withFieldValue = function withFieldValue(field, newValue) { - assert(field != null, 'field', NullPointerException); + if (!headers.Host && !headers.host) { + headers.Host = request.hostname || request.host || this.createHost() - if (field instanceof ChronoField) { - var f = field; - f.checkValidValue(newValue); + // If a port is specified explicitly, use it as is + if (request.port) + headers.Host += ':' + request.port + } + if (!request.hostname && !request.host) + request.hostname = headers.Host || headers.host - switch (f) { - case ChronoField.DAY_OF_WEEK: - return this.plusDays(newValue - this.dayOfWeek().value()); + this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' +} - case ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH: - return this.plusDays(newValue - this.getLong(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)); +RequestSigner.prototype.matchHost = function(host) { + var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) + var hostParts = (match || []).slice(1, 3) - case ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR: - return this.plusDays(newValue - this.getLong(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR)); + // ES's hostParts are sometimes the other way round, if the value that is expected + // to be region equals ‘es’ switch them back + // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com + if (hostParts[1] === 'es') + hostParts = hostParts.reverse() - case ChronoField.DAY_OF_MONTH: - return this.withDayOfMonth(newValue); + if (hostParts[1] == 's3') { + hostParts[0] = 's3' + hostParts[1] = 'us-east-1' + } else { + for (var i = 0; i < 2; i++) { + if (/^s3-/.test(hostParts[i])) { + hostParts[1] = hostParts[i].slice(3) + hostParts[0] = 's3' + break + } + } + } - case ChronoField.DAY_OF_YEAR: - return this.withDayOfYear(newValue); + return hostParts +} - case ChronoField.EPOCH_DAY: - return LocalDate.ofEpochDay(newValue); +// http://docs.aws.amazon.com/general/latest/gr/rande.html +RequestSigner.prototype.isSingleRegion = function() { + // Special case for S3 and SimpleDB in us-east-1 + if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true - case ChronoField.ALIGNED_WEEK_OF_MONTH: - return this.plusWeeks(newValue - this.getLong(ChronoField.ALIGNED_WEEK_OF_MONTH)); + return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] + .indexOf(this.service) >= 0 +} - case ChronoField.ALIGNED_WEEK_OF_YEAR: - return this.plusWeeks(newValue - this.getLong(ChronoField.ALIGNED_WEEK_OF_YEAR)); +RequestSigner.prototype.createHost = function() { + var region = this.isSingleRegion() ? '' : '.' + this.region, + subdomain = this.service === 'ses' ? 'email' : this.service + return subdomain + region + '.amazonaws.com' +} - case ChronoField.MONTH_OF_YEAR: - return this.withMonth(newValue); +RequestSigner.prototype.prepareRequest = function() { + this.parsePath() - case ChronoField.PROLEPTIC_MONTH: - return this.plusMonths(newValue - this.getLong(ChronoField.PROLEPTIC_MONTH)); + var request = this.request, headers = request.headers, query - case ChronoField.YEAR_OF_ERA: - return this.withYear(this._year >= 1 ? newValue : 1 - newValue); + if (request.signQuery) { - case ChronoField.YEAR: - return this.withYear(newValue); + this.parsedPath.query = query = this.parsedPath.query || {} - case ChronoField.ERA: - return this.getLong(ChronoField.ERA) === newValue ? this : this.withYear(1 - this._year); - } + if (this.credentials.sessionToken) + query['X-Amz-Security-Token'] = this.credentials.sessionToken - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } + if (this.service === 's3' && !query['X-Amz-Expires']) + query['X-Amz-Expires'] = 86400 - return field.adjustInto(this, newValue); - }; + if (query['X-Amz-Date']) + this.datetime = query['X-Amz-Date'] + else + query['X-Amz-Date'] = this.getDateTime() - _proto.withYear = function withYear(year) { - if (this._year === year) { - return this; - } + query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' + query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() + query['X-Amz-SignedHeaders'] = this.signedHeaders() - ChronoField.YEAR.checkValidValue(year); - return LocalDate._resolvePreviousValid(year, this._month, this._day); - }; + } else { - _proto.withMonth = function withMonth(month) { - var m = month instanceof Month ? month.value() : month; + if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { + if (request.body && !headers['Content-Type'] && !headers['content-type']) + headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' - if (this._month === m) { - return this; - } + if (request.body && !headers['Content-Length'] && !headers['content-length']) + headers['Content-Length'] = Buffer.byteLength(request.body) - ChronoField.MONTH_OF_YEAR.checkValidValue(m); - return LocalDate._resolvePreviousValid(this._year, m, this._day); - }; + if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) + headers['X-Amz-Security-Token'] = this.credentials.sessionToken - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - if (this._day === dayOfMonth) { - return this; - } + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) + headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') - return LocalDate.of(this._year, this._month, dayOfMonth); - }; + if (headers['X-Amz-Date'] || headers['x-amz-date']) + this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] + else + headers['X-Amz-Date'] = this.getDateTime() + } - _proto.withDayOfYear = function withDayOfYear(dayOfYear) { - if (this.dayOfYear() === dayOfYear) { - return this; - } + delete headers.Authorization + delete headers.authorization + } +} - return LocalDate.ofYearDay(this._year, dayOfYear); - }; +RequestSigner.prototype.sign = function() { + if (!this.parsedPath) this.prepareRequest() - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature() + } else { + this.request.headers.Authorization = this.authHeader() + } - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(amountToAdd, 'amountToAdd'); - requireNonNull(unit, 'unit'); + this.request.path = this.formatPath() - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.DAYS: - return this.plusDays(amountToAdd); + return this.request +} - case ChronoUnit.WEEKS: - return this.plusWeeks(amountToAdd); +RequestSigner.prototype.getDateTime = function() { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date) - case ChronoUnit.MONTHS: - return this.plusMonths(amountToAdd); + this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') - case ChronoUnit.YEARS: - return this.plusYears(amountToAdd); + // Remove the trailing 'Z' on the timestamp string for CodeCommit git access + if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) + } + return this.datetime +} - case ChronoUnit.DECADES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 10)); +RequestSigner.prototype.getDate = function() { + return this.getDateTime().substr(0, 8) +} - case ChronoUnit.CENTURIES: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 100)); +RequestSigner.prototype.authHeader = function() { + return [ + 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), + 'SignedHeaders=' + this.signedHeaders(), + 'Signature=' + this.signature(), + ].join(', ') +} - case ChronoUnit.MILLENNIA: - return this.plusYears(MathUtil.safeMultiply(amountToAdd, 1000)); +RequestSigner.prototype.signature = function() { + var date = this.getDate(), + cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), + kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) + if (!kCredentials) { + kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) + kRegion = hmac(kDate, this.region) + kService = hmac(kRegion, this.service) + kCredentials = hmac(kService, 'aws4_request') + credentialsCache.set(cacheKey, kCredentials) + } + return hmac(kCredentials, this.stringToSign(), 'hex') +} - case ChronoUnit.ERAS: - return this.with(ChronoField.ERA, MathUtil.safeAdd(this.getLong(ChronoField.ERA), amountToAdd)); - } +RequestSigner.prototype.stringToSign = function() { + return [ + 'AWS4-HMAC-SHA256', + this.getDateTime(), + this.credentialString(), + hash(this.canonicalString(), 'hex'), + ].join('\n') +} - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +RequestSigner.prototype.canonicalString = function() { + if (!this.parsedPath) this.prepareRequest() - return unit.addTo(this, amountToAdd); - }; + var pathStr = this.parsedPath.path, + query = this.parsedPath.query, + headers = this.request.headers, + queryStr = '', + normalizePath = this.service !== 's3', + decodePath = this.service === 's3' || this.request.doNotEncodePath, + decodeSlashesInPath = this.service === 's3', + firstValOnly = this.service === 's3', + bodyHash - _proto.plusYears = function plusYears(yearsToAdd) { - if (yearsToAdd === 0) { - return this; - } + if (this.service === 's3' && this.request.signQuery) { + bodyHash = 'UNSIGNED-PAYLOAD' + } else if (this.isCodeCommitGit) { + bodyHash = '' + } else { + bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || + hash(this.request.body || '', 'hex') + } - var newYear = ChronoField.YEAR.checkValidIntValue(this._year + yearsToAdd); - return LocalDate._resolvePreviousValid(newYear, this._month, this._day); - }; + if (query) { + var reducedQuery = Object.keys(query).reduce(function(obj, key) { + if (!key) return obj + obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : + (firstValOnly ? query[key][0] : query[key]) + return obj + }, {}) + var encodedQueryPieces = [] + Object.keys(reducedQuery).sort().forEach(function(key) { + if (!Array.isArray(reducedQuery[key])) { + encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) + } else { + reducedQuery[key].map(encodeRfc3986Full).sort() + .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) + } + }) + queryStr = encodedQueryPieces.join('&') + } + if (pathStr !== '/') { + if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') + pathStr = pathStr.split('/').reduce(function(path, piece) { + if (normalizePath && piece === '..') { + path.pop() + } else if (!normalizePath || piece !== '.') { + if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' ')) + path.push(encodeRfc3986Full(piece)) + } + return path + }, []).join('/') + if (pathStr[0] !== '/') pathStr = '/' + pathStr + if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') + } + + return [ + this.request.method || 'GET', + pathStr, + queryStr, + this.canonicalHeaders() + '\n', + this.signedHeaders(), + bodyHash, + ].join('\n') +} + +RequestSigner.prototype.canonicalHeaders = function() { + var headers = this.request.headers + function trimAll(header) { + return header.toString().trim().replace(/\s+/g, ' ') + } + return Object.keys(headers) + .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null }) + .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) + .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) + .join('\n') +} + +RequestSigner.prototype.signedHeaders = function() { + return Object.keys(this.request.headers) + .map(function(key) { return key.toLowerCase() }) + .filter(function(key) { return HEADERS_TO_IGNORE[key] == null }) + .sort() + .join(';') +} + +RequestSigner.prototype.credentialString = function() { + return [ + this.getDate(), + this.region, + this.service, + 'aws4_request', + ].join('/') +} + +RequestSigner.prototype.defaultCredentials = function() { + var env = process.env + return { + accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, + secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, + sessionToken: env.AWS_SESSION_TOKEN, + } +} - _proto.plusMonths = function plusMonths(monthsToAdd) { - if (monthsToAdd === 0) { - return this; - } +RequestSigner.prototype.parsePath = function() { + var path = this.request.path || '/' - var monthCount = this._year * 12 + (this._month - 1); - var calcMonths = monthCount + monthsToAdd; - var newYear = ChronoField.YEAR.checkValidIntValue(MathUtil.floorDiv(calcMonths, 12)); - var newMonth = MathUtil.floorMod(calcMonths, 12) + 1; - return LocalDate._resolvePreviousValid(newYear, newMonth, this._day); - }; + // S3 doesn't always encode characters > 127 correctly and + // all services don't encode characters > 255 correctly + // So if there are non-reserved chars (and it's not already all % encoded), just encode them all + if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) { + path = encodeURI(decodeURI(path)) + } - _proto.plusWeeks = function plusWeeks(weeksToAdd) { - return this.plusDays(MathUtil.safeMultiply(weeksToAdd, 7)); - }; + var queryIx = path.indexOf('?'), + query = null - _proto.plusDays = function plusDays(daysToAdd) { - if (daysToAdd === 0) { - return this; - } + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)) + path = path.slice(0, queryIx) + } - var mjDay = MathUtil.safeAdd(this.toEpochDay(), daysToAdd); - return LocalDate.ofEpochDay(mjDay); - }; + this.parsedPath = { + path: path, + query: query, + } +} - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; +RequestSigner.prototype.formatPath = function() { + var path = this.parsedPath.path, + query = this.parsedPath.query - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(amountToSubtract, 'amountToSubtract'); - requireNonNull(unit, 'unit'); - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; + if (!query) return path - _proto.minusYears = function minusYears(yearsToSubtract) { - return this.plusYears(yearsToSubtract * -1); - }; + // Services don't support empty query string keys + if (query[''] != null) delete query[''] - _proto.minusMonths = function minusMonths(monthsToSubtract) { - return this.plusMonths(monthsToSubtract * -1); - }; + return path + '?' + encodeRfc3986(querystring.stringify(query)) +} - _proto.minusWeeks = function minusWeeks(weeksToSubtract) { - return this.plusWeeks(weeksToSubtract * -1); - }; +aws4.RequestSigner = RequestSigner - _proto.minusDays = function minusDays(daysToSubtract) { - return this.plusDays(daysToSubtract * -1); - }; +aws4.sign = function(request, credentials) { + return new RequestSigner(request, credentials).sign() +} - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); - if (_query === TemporalQueries.localDate()) { - return this; - } +/***/ }), - return _ChronoLocalDate.prototype.query.call(this, _query); - }; +/***/ 74225: +/***/ ((module) => { - _proto.adjustInto = function adjustInto(temporal) { - return _ChronoLocalDate.prototype.adjustInto.call(this, temporal); - }; +module.exports = function(size) { + return new LruCache(size) +} - _proto.until = function until(p1, p2) { - if (arguments.length < 2) { - return this.until1(p1); - } else { - return this.until2(p1, p2); - } - }; +function LruCache(size) { + this.capacity = size | 0 + this.map = Object.create(null) + this.list = new DoublyLinkedList() +} - _proto.until2 = function until2(endExclusive, unit) { - var end = LocalDate.from(endExclusive); +LruCache.prototype.get = function(key) { + var node = this.map[key] + if (node == null) return undefined + this.used(node) + return node.val +} - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.DAYS: - return this.daysUntil(end); +LruCache.prototype.set = function(key, val) { + var node = this.map[key] + if (node != null) { + node.val = val + } else { + if (!this.capacity) this.prune() + if (!this.capacity) return false + node = new DoublyLinkedNode(key, val) + this.map[key] = node + this.capacity-- + } + this.used(node) + return true +} - case ChronoUnit.WEEKS: - return MathUtil.intDiv(this.daysUntil(end), 7); +LruCache.prototype.used = function(node) { + this.list.moveToFront(node) +} - case ChronoUnit.MONTHS: - return this._monthsUntil(end); +LruCache.prototype.prune = function() { + var node = this.list.pop() + if (node != null) { + delete this.map[node.key] + this.capacity++ + } +} - case ChronoUnit.YEARS: - return MathUtil.intDiv(this._monthsUntil(end), 12); - case ChronoUnit.DECADES: - return MathUtil.intDiv(this._monthsUntil(end), 120); +function DoublyLinkedList() { + this.firstNode = null + this.lastNode = null +} - case ChronoUnit.CENTURIES: - return MathUtil.intDiv(this._monthsUntil(end), 1200); +DoublyLinkedList.prototype.moveToFront = function(node) { + if (this.firstNode == node) return - case ChronoUnit.MILLENNIA: - return MathUtil.intDiv(this._monthsUntil(end), 12000); + this.remove(node) - case ChronoUnit.ERAS: - return end.getLong(ChronoField.ERA) - this.getLong(ChronoField.ERA); - } + if (this.firstNode == null) { + this.firstNode = node + this.lastNode = node + node.prev = null + node.next = null + } else { + node.prev = null + node.next = this.firstNode + node.next.prev = node + this.firstNode = node + } +} - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +DoublyLinkedList.prototype.pop = function() { + var lastNode = this.lastNode + if (lastNode != null) { + this.remove(lastNode) + } + return lastNode +} - return unit.between(this, end); - }; +DoublyLinkedList.prototype.remove = function(node) { + if (this.firstNode == node) { + this.firstNode = node.next + } else if (node.prev != null) { + node.prev.next = node.next + } + if (this.lastNode == node) { + this.lastNode = node.prev + } else if (node.next != null) { + node.next.prev = node.prev + } +} - _proto.daysUntil = function daysUntil(end) { - return end.toEpochDay() - this.toEpochDay(); - }; - _proto._monthsUntil = function _monthsUntil(end) { - var packed1 = this._prolepticMonth() * 32 + this.dayOfMonth(); - var packed2 = end._prolepticMonth() * 32 + end.dayOfMonth(); - return MathUtil.intDiv(packed2 - packed1, 32); - }; +function DoublyLinkedNode(key, val) { + this.key = key + this.val = val + this.prev = null + this.next = null +} - _proto.until1 = function until1(endDate) { - var end = LocalDate.from(endDate); - var totalMonths = end._prolepticMonth() - this._prolepticMonth(); +/***/ }), - var days = end._day - this._day; +/***/ 96545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (totalMonths > 0 && days < 0) { - totalMonths--; - var calcDate = this.plusMonths(totalMonths); - days = end.toEpochDay() - calcDate.toEpochDay(); - } else if (totalMonths < 0 && days > 0) { - totalMonths++; - days -= end.lengthOfMonth(); - } +module.exports = __nccwpck_require__(52618); - var years = MathUtil.intDiv(totalMonths, 12); - var months = MathUtil.intMod(totalMonths, 12); - return Period.of(years, months, days); - }; +/***/ }), - _proto.atTime = function atTime() { - if (arguments.length === 1) { - return this.atTime1.apply(this, arguments); - } else { - return this.atTime4.apply(this, arguments); - } - }; +/***/ 68104: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.atTime1 = function atTime1(time) { - requireNonNull(time, 'time'); +"use strict"; - if (time instanceof LocalTime) { - return LocalDateTime.of(this, time); - } else if (time instanceof OffsetTime) { - return this._atTimeOffsetTime(time); - } else { - throw new IllegalArgumentException('time must be an instance of LocalTime or OffsetTime' + (time && time.constructor && time.constructor.name ? ', but is ' + time.constructor.name : '')); - } - }; - _proto.atTime4 = function atTime4(hour, minute, second, nanoOfSecond) { - if (second === void 0) { - second = 0; - } +var utils = __nccwpck_require__(20328); +var settle = __nccwpck_require__(13211); +var buildFullPath = __nccwpck_require__(41934); +var buildURL = __nccwpck_require__(30646); +var http = __nccwpck_require__(98605); +var https = __nccwpck_require__(57211); +var httpFollow = __nccwpck_require__(67707).http; +var httpsFollow = __nccwpck_require__(67707).https; +var url = __nccwpck_require__(78835); +var zlib = __nccwpck_require__(78761); +var pkg = __nccwpck_require__(20696); +var createError = __nccwpck_require__(15226); +var enhanceError = __nccwpck_require__(21516); - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } +var isHttps = /https:?/; - return this.atTime1(LocalTime.of(hour, minute, second, nanoOfSecond)); - }; +/** + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} proxy + * @param {string} location + */ +function setProxy(options, proxy, location) { + options.hostname = proxy.host; + options.host = proxy.host; + options.port = proxy.port; + options.path = location; - _proto._atTimeOffsetTime = function _atTimeOffsetTime(time) { - return OffsetDateTime.of(LocalDateTime.of(this, time.toLocalTime()), time.offset()); - }; + // Basic proxy authorization + if (proxy.auth) { + var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } - _proto.atStartOfDay = function atStartOfDay(zone) { - if (zone != null) { - return this.atStartOfDayWithZone(zone); - } else { - return LocalDateTime.of(this, LocalTime.MIDNIGHT); - } - }; + // If a proxy is used, any redirects must also pass through the proxy + options.beforeRedirect = function beforeRedirect(redirection) { + redirection.headers.host = redirection.host; + setProxy(redirection, proxy, redirection.href); + }; +} - _proto.atStartOfDayWithZone = function atStartOfDayWithZone(zone) { - requireNonNull(zone, 'zone'); - var ldt = this.atTime(LocalTime.MIDNIGHT); +/*eslint consistent-return:0*/ +module.exports = function httpAdapter(config) { + return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { + var resolve = function resolve(value) { + resolvePromise(value); + }; + var reject = function reject(value) { + rejectPromise(value); + }; + var data = config.data; + var headers = config.headers; - if (zone instanceof ZoneOffset === false) { - var trans = zone.rules().transition(ldt); + // Set User-Agent (required by some servers) + // Only set header if it hasn't been set in config + // See https://github.com/axios/axios/issues/69 + if (!headers['User-Agent'] && !headers['user-agent']) { + headers['User-Agent'] = 'axios/' + pkg.version; + } - if (trans != null && trans.isGap()) { - ldt = trans.dateTimeAfter(); - } - } + if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(createError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + config + )); + } - return ZonedDateTime.of(ldt, zone); - }; + // Add Content-Length header if data exists + headers['Content-Length'] = data.length; + } + + // HTTP basic authentication + var auth = undefined; + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + auth = username + ':' + password; + } - _proto.toEpochDay = function toEpochDay() { - var y = this._year; - var m = this._month; - var total = 0; - total += 365 * y; + // Parse url + var fullPath = buildFullPath(config.baseURL, config.url); + var parsed = url.parse(fullPath); + var protocol = parsed.protocol || 'http:'; - if (y >= 0) { - total += MathUtil.intDiv(y + 3, 4) - MathUtil.intDiv(y + 99, 100) + MathUtil.intDiv(y + 399, 400); - } else { - total -= MathUtil.intDiv(y, -4) - MathUtil.intDiv(y, -100) + MathUtil.intDiv(y, -400); - } + if (!auth && parsed.auth) { + var urlAuth = parsed.auth.split(':'); + var urlUsername = urlAuth[0] || ''; + var urlPassword = urlAuth[1] || ''; + auth = urlUsername + ':' + urlPassword; + } - total += MathUtil.intDiv(367 * m - 362, 12); - total += this.dayOfMonth() - 1; + if (auth) { + delete headers.Authorization; + } - if (m > 2) { - total--; + var isHttpsRequest = isHttps.test(protocol); + var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; - if (!IsoChronology.isLeapYear(y)) { - total--; - } - } + var options = { + path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), + method: config.method.toUpperCase(), + headers: headers, + agent: agent, + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth: auth + }; - return total - DAYS_0000_TO_1970; - }; + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname; + options.port = parsed.port; + } - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, LocalDate, 'other'); - return this._compareTo0(other); - }; + var proxy = config.proxy; + if (!proxy && proxy !== false) { + var proxyEnv = protocol.slice(0, -1) + '_proxy'; + var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; + if (proxyUrl) { + var parsedProxyUrl = url.parse(proxyUrl); + var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; + var shouldProxy = true; - _proto._compareTo0 = function _compareTo0(otherDate) { - var cmp = this._year - otherDate._year; + if (noProxyEnv) { + var noProxy = noProxyEnv.split(',').map(function trim(s) { + return s.trim(); + }); - if (cmp === 0) { - cmp = this._month - otherDate._month; + shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { + if (!proxyElement) { + return false; + } + if (proxyElement === '*') { + return true; + } + if (proxyElement[0] === '.' && + parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { + return true; + } - if (cmp === 0) { - cmp = this._day - otherDate._day; - } + return parsed.hostname === proxyElement; + }); } - return cmp; - }; - - _proto.isAfter = function isAfter(other) { - return this.compareTo(other) > 0; - }; + if (shouldProxy) { + proxy = { + host: parsedProxyUrl.hostname, + port: parsedProxyUrl.port, + protocol: parsedProxyUrl.protocol + }; - _proto.isBefore = function isBefore(other) { - return this.compareTo(other) < 0; - }; + if (parsedProxyUrl.auth) { + var proxyUrlAuth = parsedProxyUrl.auth.split(':'); + proxy.auth = { + username: proxyUrlAuth[0], + password: proxyUrlAuth[1] + }; + } + } + } + } - _proto.isEqual = function isEqual(other) { - return this.compareTo(other) === 0; - }; + if (proxy) { + options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); + setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + } - _proto.equals = function equals(other) { - if (this === other) { - return true; - } + var transport; + var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsProxy ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + transport = isHttpsProxy ? httpsFollow : httpFollow; + } - if (other instanceof LocalDate) { - return this._compareTo0(other) === 0; - } + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } - return false; - }; + // Create the request + var req = transport.request(options, function handleResponse(res) { + if (req.aborted) return; - _proto.hashCode = function hashCode() { - var yearValue = this._year; - var monthValue = this._month; - var dayValue = this._day; - return MathUtil.hash(yearValue & 0xFFFFF800 ^ (yearValue << 11) + (monthValue << 6) + dayValue); - }; + // uncompress the response body transparently if required + var stream = res; - _proto.toString = function toString() { - var dayString, monthString, yearString; - var yearValue = this._year; - var monthValue = this._month; - var dayValue = this._day; - var absYear = Math.abs(yearValue); + // return the last request in case of redirects + var lastRequest = res.req || req; - if (absYear < 1000) { - if (yearValue < 0) { - yearString = '-' + ('' + (yearValue - 10000)).slice(-4); - } else { - yearString = ('' + (yearValue + 10000)).slice(-4); - } - } else { - if (yearValue > 9999) { - yearString = '+' + yearValue; - } else { - yearString = '' + yearValue; - } - } - if (monthValue < 10) { - monthString = '-0' + monthValue; - } else { - monthString = '-' + monthValue; - } + // if no content, is HEAD request or decompress disabled we should not decompress + if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { + switch (res.headers['content-encoding']) { + /*eslint default-case:0*/ + case 'gzip': + case 'compress': + case 'deflate': + // add the unzipper to the body stream processing pipeline + stream = stream.pipe(zlib.createUnzip()); - if (dayValue < 10) { - dayString = '-0' + dayValue; - } else { - dayString = '-' + dayValue; + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; } + } - return yearString + monthString + dayString; + var response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: res.headers, + config: config, + request: lastRequest }; - _proto.toJSON = function toJSON() { - return this.toString(); - }; + if (config.responseType === 'stream') { + response.data = stream; + settle(resolve, reject, response); + } else { + var responseBuffer = []; + stream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - requireInstance(formatter, DateTimeFormatter, 'formatter'); - return _ChronoLocalDate.prototype.format.call(this, formatter); - }; + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { + stream.destroy(); + reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + config, null, lastRequest)); + } + }); - return LocalDate; - }(ChronoLocalDate); - function _init$i() { - LocalDate.MIN = LocalDate.of(YearConstants.MIN_VALUE, 1, 1); - LocalDate.MAX = LocalDate.of(YearConstants.MAX_VALUE, 12, 31); - LocalDate.EPOCH_0 = LocalDate.ofEpochDay(0); - LocalDate.FROM = createTemporalQuery('LocalDate.FROM', function (temporal) { - return LocalDate.from(temporal); - }); - } + stream.on('error', function handleStreamError(err) { + if (req.aborted) return; + reject(enhanceError(err, config, null, lastRequest)); + }); - var ChronoLocalDateTime = function (_DefaultInterfaceTemp) { - _inheritsLoose(ChronoLocalDateTime, _DefaultInterfaceTemp); + stream.on('end', function handleStreamEnd() { + var responseData = Buffer.concat(responseBuffer); + if (config.responseType !== 'arraybuffer') { + responseData = responseData.toString(config.responseEncoding); + if (!config.responseEncoding || config.responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } - function ChronoLocalDateTime() { - return _DefaultInterfaceTemp.apply(this, arguments) || this; + response.data = responseData; + settle(resolve, reject, response); + }); } + }); - var _proto = ChronoLocalDateTime.prototype; - - _proto.chronology = function chronology() { - return this.toLocalDate().chronology(); - }; + // Handle errors + req.on('error', function handleRequestError(err) { + if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return; + reject(enhanceError(err, config, null, req)); + }); - _proto.query = function query(_query) { - if (_query === TemporalQueries.chronology()) { - return this.chronology(); - } else if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.localDate()) { - return LocalDate.ofEpochDay(this.toLocalDate().toEpochDay()); - } else if (_query === TemporalQueries.localTime()) { - return this.toLocalTime(); - } else if (_query === TemporalQueries.zone() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.offset()) { - return null; - } + // Handle request timeout + if (config.timeout) { + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devoring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(config.timeout, function handleRequestTimeout() { + req.abort(); + reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); + }); + } - return _DefaultInterfaceTemp.prototype.query.call(this, _query); - }; + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (req.aborted) return; - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(ChronoField.EPOCH_DAY, this.toLocalDate().toEpochDay()).with(ChronoField.NANO_OF_DAY, this.toLocalTime().toNanoOfDay()); - }; + req.abort(); + reject(cancel); + }); + } - _proto.toInstant = function toInstant(offset) { - requireInstance(offset, ZoneOffset, 'zoneId'); - return Instant.ofEpochSecond(this.toEpochSecond(offset), this.toLocalTime().nano()); - }; + // Send the request + if (utils.isStream(data)) { + data.on('error', function handleStreamError(err) { + reject(enhanceError(err, config, null, req)); + }).pipe(req); + } else { + req.end(data); + } + }); +}; - _proto.toEpochSecond = function toEpochSecond(offset) { - requireNonNull(offset, 'offset'); - var epochDay = this.toLocalDate().toEpochDay(); - var secs = epochDay * 86400 + this.toLocalTime().toSecondOfDay(); - secs -= offset.totalSeconds(); - return MathUtil.safeToInt(secs); - }; - return ChronoLocalDateTime; - }(DefaultInterfaceTemporal); +/***/ }), - var LocalDateTime = function (_ChronoLocalDateTime) { - _inheritsLoose(LocalDateTime, _ChronoLocalDateTime); +/***/ 3454: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - LocalDateTime.now = function now(clockOrZone) { - if (clockOrZone == null) { - return LocalDateTime._now(Clock.systemDefaultZone()); - } else if (clockOrZone instanceof Clock) { - return LocalDateTime._now(clockOrZone); - } else { - return LocalDateTime._now(Clock.system(clockOrZone)); - } - }; +"use strict"; - LocalDateTime._now = function _now(clock) { - requireNonNull(clock, 'clock'); - return LocalDateTime.ofInstant(clock.instant(), clock.zone()); - }; - LocalDateTime._ofEpochMillis = function _ofEpochMillis(epochMilli, offset) { - var localSecond = MathUtil.floorDiv(epochMilli, 1000) + offset.totalSeconds(); - var localEpochDay = MathUtil.floorDiv(localSecond, LocalTime.SECONDS_PER_DAY); - var secsOfDay = MathUtil.floorMod(localSecond, LocalTime.SECONDS_PER_DAY); - var nanoOfSecond = MathUtil.floorMod(epochMilli, 1000) * 1000000; - var date = LocalDate.ofEpochDay(localEpochDay); - var time = LocalTime.ofSecondOfDay(secsOfDay, nanoOfSecond); - return new LocalDateTime(date, time); - }; +var utils = __nccwpck_require__(20328); +var settle = __nccwpck_require__(13211); +var cookies = __nccwpck_require__(21545); +var buildURL = __nccwpck_require__(30646); +var buildFullPath = __nccwpck_require__(41934); +var parseHeaders = __nccwpck_require__(86455); +var isURLSameOrigin = __nccwpck_require__(33608); +var createError = __nccwpck_require__(15226); - LocalDateTime.of = function of() { - if (arguments.length <= 2) { - return LocalDateTime.ofDateAndTime.apply(this, arguments); - } else { - return LocalDateTime.ofNumbers.apply(this, arguments); - } - }; +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; - LocalDateTime.ofNumbers = function ofNumbers(year, month, dayOfMonth, hour, minute, second, nanoOfSecond) { - if (hour === void 0) { - hour = 0; - } + if (utils.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it + } - if (minute === void 0) { - minute = 0; - } + var request = new XMLHttpRequest(); - if (second === void 0) { - second = 0; - } + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - var date = LocalDate.of(year, month, dayOfMonth); - var time = LocalTime.of(hour, minute, second, nanoOfSecond); - return new LocalDateTime(date, time); - }; + // Set the request timeout in MS + request.timeout = config.timeout; - LocalDateTime.ofDateAndTime = function ofDateAndTime(date, time) { - requireNonNull(date, 'date'); - requireNonNull(time, 'time'); - return new LocalDateTime(date, time); - }; + // Listen for ready state + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } - LocalDateTime.ofInstant = function ofInstant(instant, zone) { - if (zone === void 0) { - zone = ZoneId.systemDefault(); - } + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } - requireNonNull(instant, 'instant'); - requireInstance(instant, Instant, 'instant'); - requireNonNull(zone, 'zone'); - var offset = zone.rules().offset(instant); - return LocalDateTime.ofEpochSecond(instant.epochSecond(), instant.nano(), offset); + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request }; - LocalDateTime.ofEpochSecond = function ofEpochSecond(epochSecond, nanoOfSecond, offset) { - if (epochSecond === void 0) { - epochSecond = 0; - } + settle(resolve, reject, response); - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + // Clean up request + request = null; + }; - if (arguments.length === 2 && nanoOfSecond instanceof ZoneOffset) { - offset = nanoOfSecond; - nanoOfSecond = 0; - } + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } - requireNonNull(offset, 'offset'); - var localSecond = epochSecond + offset.totalSeconds(); - var localEpochDay = MathUtil.floorDiv(localSecond, LocalTime.SECONDS_PER_DAY); - var secsOfDay = MathUtil.floorMod(localSecond, LocalTime.SECONDS_PER_DAY); - var date = LocalDate.ofEpochDay(localEpochDay); - var time = LocalTime.ofSecondOfDay(secsOfDay, nanoOfSecond); - return new LocalDateTime(date, time); - }; + reject(createError('Request aborted', config, 'ECONNABORTED', request)); - LocalDateTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); + // Clean up request + request = null; + }; - if (temporal instanceof LocalDateTime) { - return temporal; - } else if (temporal instanceof ZonedDateTime) { - return temporal.toLocalDateTime(); - } + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(createError('Network Error', config, null, request)); - try { - var date = LocalDate.from(temporal); - var time = LocalTime.from(temporal); - return new LocalDateTime(date, time); - } catch (ex) { - throw new DateTimeException("Unable to obtain LocalDateTime TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); - } - }; + // Clean up request + request = null; + }; - LocalDateTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; - } + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', + request)); - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, LocalDateTime.FROM); - }; + // Clean up request + request = null; + }; - function LocalDateTime(date, time) { - var _this; + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; - _this = _ChronoLocalDateTime.call(this) || this; - requireInstance(date, LocalDate, 'date'); - requireInstance(time, LocalTime, 'time'); - _this._date = date; - _this._time = time; - return _this; + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; } + } - var _proto = LocalDateTime.prototype; - - _proto._withDateTime = function _withDateTime(newDate, newTime) { - if (this._date.equals(newDate) && this._time.equals(newTime)) { - return this; + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); } + }); + } - return new LocalDateTime(newDate, newTime); - }; + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isDateBased() || fieldOrUnit.isTimeBased(); + // Add responseType to request if needed + if (config.responseType) { + try { + request.responseType = config.responseType; + } catch (e) { + // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. + // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. + if (config.responseType !== 'json') { + throw e; } + } + } - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; - - _proto.range = function range(field) { - if (field instanceof ChronoField) { - return field.isTimeBased() ? this._time.range(field) : this._date.range(field); - } + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } - return field.rangeRefinedBy(this); - }; + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } - _proto.get = function get(field) { - if (field instanceof ChronoField) { - return field.isTimeBased() ? this._time.get(field) : this._date.get(field); + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; } - return _ChronoLocalDateTime.prototype.get.call(this, field); - }; + request.abort(); + reject(cancel); + // Clean up request + request = null; + }); + } - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); + if (!requestData) { + requestData = null; + } - if (field instanceof ChronoField) { - return field.isTimeBased() ? this._time.getLong(field) : this._date.getLong(field); - } + // Send the request + request.send(requestData); + }); +}; - return field.getFrom(this); - }; - _proto.year = function year() { - return this._date.year(); - }; +/***/ }), - _proto.monthValue = function monthValue() { - return this._date.monthValue(); - }; +/***/ 52618: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.month = function month() { - return this._date.month(); - }; +"use strict"; - _proto.dayOfMonth = function dayOfMonth() { - return this._date.dayOfMonth(); - }; - _proto.dayOfYear = function dayOfYear() { - return this._date.dayOfYear(); - }; +var utils = __nccwpck_require__(20328); +var bind = __nccwpck_require__(77065); +var Axios = __nccwpck_require__(98178); +var mergeConfig = __nccwpck_require__(74831); +var defaults = __nccwpck_require__(98190); - _proto.dayOfWeek = function dayOfWeek() { - return this._date.dayOfWeek(); - }; +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); - _proto.hour = function hour() { - return this._time.hour(); - }; + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); - _proto.minute = function minute() { - return this._time.minute(); - }; + // Copy context to instance + utils.extend(instance, context); - _proto.second = function second() { - return this._time.second(); - }; + return instance; +} - _proto.nano = function nano() { - return this._time.nano(); - }; +// Create the default instance to be exported +var axios = createInstance(defaults); - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); +// Expose Axios class to allow class inheritance +axios.Axios = Axios; - if (adjuster instanceof LocalDate) { - return this._withDateTime(adjuster, this._time); - } else if (adjuster instanceof LocalTime) { - return this._withDateTime(this._date, adjuster); - } else if (adjuster instanceof LocalDateTime) { - return adjuster; - } +// Factory for creating new instances +axios.create = function create(instanceConfig) { + return createInstance(mergeConfig(axios.defaults, instanceConfig)); +}; - assert(typeof adjuster.adjustInto === 'function', 'adjuster', IllegalArgumentException); - return adjuster.adjustInto(this); - }; +// Expose Cancel & CancelToken +axios.Cancel = __nccwpck_require__(98875); +axios.CancelToken = __nccwpck_require__(71587); +axios.isCancel = __nccwpck_require__(64057); - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = __nccwpck_require__(74850); - if (field instanceof ChronoField) { - if (field.isTimeBased()) { - return this._withDateTime(this._date, this._time.with(field, newValue)); - } else { - return this._withDateTime(this._date.with(field, newValue), this._time); - } - } +// Expose isAxiosError +axios.isAxiosError = __nccwpck_require__(60650); - return field.adjustInto(this, newValue); - }; +module.exports = axios; - _proto.withYear = function withYear(year) { - return this._withDateTime(this._date.withYear(year), this._time); - }; +// Allow use of default import syntax in TypeScript +module.exports.default = axios; - _proto.withMonth = function withMonth(month) { - return this._withDateTime(this._date.withMonth(month), this._time); - }; - _proto.withDayOfMonth = function withDayOfMonth(dayOfMonth) { - return this._withDateTime(this._date.withDayOfMonth(dayOfMonth), this._time); - }; +/***/ }), - _proto.withDayOfYear = function withDayOfYear(dayOfYear) { - return this._withDateTime(this._date.withDayOfYear(dayOfYear), this._time); - }; +/***/ 98875: +/***/ ((module) => { - _proto.withHour = function withHour(hour) { - var newTime = this._time.withHour(hour); +"use strict"; - return this._withDateTime(this._date, newTime); - }; - _proto.withMinute = function withMinute(minute) { - var newTime = this._time.withMinute(minute); +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; +} - return this._withDateTime(this._date, newTime); - }; +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; - _proto.withSecond = function withSecond(second) { - var newTime = this._time.withSecond(second); +Cancel.prototype.__CANCEL__ = true; - return this._withDateTime(this._date, newTime); - }; +module.exports = Cancel; - _proto.withNano = function withNano(nanoOfSecond) { - var newTime = this._time.withNano(nanoOfSecond); - return this._withDateTime(this._date, newTime); - }; +/***/ }), - _proto.truncatedTo = function truncatedTo(unit) { - return this._withDateTime(this._date, this._time.truncatedTo(unit)); - }; +/***/ 71587: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; +"use strict"; - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(unit, 'unit'); - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this.plusNanos(amountToAdd); +var Cancel = __nccwpck_require__(98875); - case ChronoUnit.MICROS: - return this.plusDays(MathUtil.intDiv(amountToAdd, LocalTime.MICROS_PER_DAY)).plusNanos(MathUtil.intMod(amountToAdd, LocalTime.MICROS_PER_DAY) * 1000); +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } - case ChronoUnit.MILLIS: - return this.plusDays(MathUtil.intDiv(amountToAdd, LocalTime.MILLIS_PER_DAY)).plusNanos(MathUtil.intMod(amountToAdd, LocalTime.MILLIS_PER_DAY) * 1000000); + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); - case ChronoUnit.SECONDS: - return this.plusSeconds(amountToAdd); + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } - case ChronoUnit.MINUTES: - return this.plusMinutes(amountToAdd); + token.reason = new Cancel(message); + resolvePromise(token.reason); + }); +} - case ChronoUnit.HOURS: - return this.plusHours(amountToAdd); +/** + * Throws a `Cancel` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; - case ChronoUnit.HALF_DAYS: - return this.plusDays(MathUtil.intDiv(amountToAdd, 256)).plusHours(MathUtil.intMod(amountToAdd, 256) * 12); - } +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; - return this._withDateTime(this._date.plus(amountToAdd, unit), this._time); - } +module.exports = CancelToken; - return unit.addTo(this, amountToAdd); - }; - _proto.plusYears = function plusYears(years) { - var newDate = this._date.plusYears(years); +/***/ }), - return this._withDateTime(newDate, this._time); - }; +/***/ 64057: +/***/ ((module) => { - _proto.plusMonths = function plusMonths(months) { - var newDate = this._date.plusMonths(months); +"use strict"; - return this._withDateTime(newDate, this._time); - }; - _proto.plusWeeks = function plusWeeks(weeks) { - var newDate = this._date.plusWeeks(weeks); +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; - return this._withDateTime(newDate, this._time); - }; - _proto.plusDays = function plusDays(days) { - var newDate = this._date.plusDays(days); +/***/ }), - return this._withDateTime(newDate, this._time); - }; +/***/ 98178: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.plusHours = function plusHours(hours) { - return this._plusWithOverflow(this._date, hours, 0, 0, 0, 1); - }; +"use strict"; - _proto.plusMinutes = function plusMinutes(minutes) { - return this._plusWithOverflow(this._date, 0, minutes, 0, 0, 1); - }; - _proto.plusSeconds = function plusSeconds(seconds) { - return this._plusWithOverflow(this._date, 0, 0, seconds, 0, 1); - }; +var utils = __nccwpck_require__(20328); +var buildURL = __nccwpck_require__(30646); +var InterceptorManager = __nccwpck_require__(3214); +var dispatchRequest = __nccwpck_require__(85062); +var mergeConfig = __nccwpck_require__(74831); - _proto.plusNanos = function plusNanos(nanos) { - return this._plusWithOverflow(this._date, 0, 0, 0, nanos, 1); - }; +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; + } - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(unit, 'unit'); - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; + config = mergeConfig(this.defaults, config); - _proto.minusYears = function minusYears(years) { - return this.plusYears(-1 * years); - }; + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } - _proto.minusMonths = function minusMonths(months) { - return this.plusMonths(-1 * months); - }; + // Hook up interceptors middleware + var chain = [dispatchRequest, undefined]; + var promise = Promise.resolve(config); - _proto.minusWeeks = function minusWeeks(weeks) { - return this.plusWeeks(-1 * weeks); - }; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); - _proto.minusDays = function minusDays(days) { - return this.plusDays(-1 * days); - }; - - _proto.minusHours = function minusHours(hours) { - return this._plusWithOverflow(this._date, hours, 0, 0, 0, -1); - }; - - _proto.minusMinutes = function minusMinutes(minutes) { - return this._plusWithOverflow(this._date, 0, minutes, 0, 0, -1); - }; - - _proto.minusSeconds = function minusSeconds(seconds) { - return this._plusWithOverflow(this._date, 0, 0, seconds, 0, -1); - }; - - _proto.minusNanos = function minusNanos(nanos) { - return this._plusWithOverflow(this._date, 0, 0, 0, nanos, -1); - }; - - _proto._plusWithOverflow = function _plusWithOverflow(newDate, hours, minutes, seconds, nanos, sign) { - if (hours === 0 && minutes === 0 && seconds === 0 && nanos === 0) { - return this._withDateTime(newDate, this._time); - } + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + chain.push(interceptor.fulfilled, interceptor.rejected); + }); - var totDays = MathUtil.intDiv(nanos, LocalTime.NANOS_PER_DAY) + MathUtil.intDiv(seconds, LocalTime.SECONDS_PER_DAY) + MathUtil.intDiv(minutes, LocalTime.MINUTES_PER_DAY) + MathUtil.intDiv(hours, LocalTime.HOURS_PER_DAY); - totDays *= sign; - var totNanos = MathUtil.intMod(nanos, LocalTime.NANOS_PER_DAY) + MathUtil.intMod(seconds, LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + MathUtil.intMod(minutes, LocalTime.MINUTES_PER_DAY) * LocalTime.NANOS_PER_MINUTE + MathUtil.intMod(hours, LocalTime.HOURS_PER_DAY) * LocalTime.NANOS_PER_HOUR; + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } - var curNoD = this._time.toNanoOfDay(); + return promise; +}; - totNanos = totNanos * sign + curNoD; - totDays += MathUtil.floorDiv(totNanos, LocalTime.NANOS_PER_DAY); - var newNoD = MathUtil.floorMod(totNanos, LocalTime.NANOS_PER_DAY); - var newTime = newNoD === curNoD ? this._time : LocalTime.ofNanoOfDay(newNoD); - return this._withDateTime(newDate.plusDays(totDays), newTime); - }; +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); +}; - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; +}); - if (_query === TemporalQueries.localDate()) { - return this.toLocalDate(); - } +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: data + })); + }; +}); - return _ChronoLocalDateTime.prototype.query.call(this, _query); - }; +module.exports = Axios; - _proto.adjustInto = function adjustInto(temporal) { - return _ChronoLocalDateTime.prototype.adjustInto.call(this, temporal); - }; - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - var end = LocalDateTime.from(endExclusive); +/***/ }), - if (unit instanceof ChronoUnit) { - if (unit.isTimeBased()) { - var daysUntil = this._date.daysUntil(end._date); +/***/ 3214: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var timeUntil = end._time.toNanoOfDay() - this._time.toNanoOfDay(); +"use strict"; - if (daysUntil > 0 && timeUntil < 0) { - daysUntil--; - timeUntil += LocalTime.NANOS_PER_DAY; - } else if (daysUntil < 0 && timeUntil > 0) { - daysUntil++; - timeUntil -= LocalTime.NANOS_PER_DAY; - } - var amount = daysUntil; +var utils = __nccwpck_require__(20328); - switch (unit) { - case ChronoUnit.NANOS: - amount = MathUtil.safeMultiply(amount, LocalTime.NANOS_PER_DAY); - return MathUtil.safeAdd(amount, timeUntil); +function InterceptorManager() { + this.handlers = []; +} - case ChronoUnit.MICROS: - amount = MathUtil.safeMultiply(amount, LocalTime.MICROS_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, 1000)); +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; +}; - case ChronoUnit.MILLIS: - amount = MathUtil.safeMultiply(amount, LocalTime.MILLIS_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, 1000000)); +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; - case ChronoUnit.SECONDS: - amount = MathUtil.safeMultiply(amount, LocalTime.SECONDS_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, LocalTime.NANOS_PER_SECOND)); +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; - case ChronoUnit.MINUTES: - amount = MathUtil.safeMultiply(amount, LocalTime.MINUTES_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, LocalTime.NANOS_PER_MINUTE)); +module.exports = InterceptorManager; - case ChronoUnit.HOURS: - amount = MathUtil.safeMultiply(amount, LocalTime.HOURS_PER_DAY); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, LocalTime.NANOS_PER_HOUR)); - case ChronoUnit.HALF_DAYS: - amount = MathUtil.safeMultiply(amount, 2); - return MathUtil.safeAdd(amount, MathUtil.intDiv(timeUntil, LocalTime.NANOS_PER_HOUR * 12)); - } +/***/ }), - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } +/***/ 41934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var endDate = end._date; - var endTime = end._time; +"use strict"; - if (endDate.isAfter(this._date) && endTime.isBefore(this._time)) { - endDate = endDate.minusDays(1); - } else if (endDate.isBefore(this._date) && endTime.isAfter(this._time)) { - endDate = endDate.plusDays(1); - } - return this._date.until(endDate, unit); - } +var isAbsoluteURL = __nccwpck_require__(41301); +var combineURLs = __nccwpck_require__(57189); - return unit.between(this, end); - }; +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +}; - _proto.atOffset = function atOffset(offset) { - return OffsetDateTime.of(this, offset); - }; - _proto.atZone = function atZone(zone) { - return ZonedDateTime.of(this, zone); - }; +/***/ }), - _proto.toLocalDate = function toLocalDate() { - return this._date; - }; +/***/ 15226: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.toLocalTime = function toLocalTime() { - return this._time; - }; +"use strict"; - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, LocalDateTime, 'other'); - return this._compareTo0(other); - }; - _proto._compareTo0 = function _compareTo0(other) { - var cmp = this._date.compareTo(other.toLocalDate()); +var enhanceError = __nccwpck_require__(21516); - if (cmp === 0) { - cmp = this._time.compareTo(other.toLocalTime()); - } +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +module.exports = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError(error, config, code, request, response); +}; - return cmp; - }; - _proto.isAfter = function isAfter(other) { - return this.compareTo(other) > 0; - }; +/***/ }), - _proto.isBefore = function isBefore(other) { - return this.compareTo(other) < 0; - }; +/***/ 85062: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.isEqual = function isEqual(other) { - return this.compareTo(other) === 0; - }; +"use strict"; - _proto.equals = function equals(other) { - if (this === other) { - return true; - } - if (other instanceof LocalDateTime) { - return this._date.equals(other._date) && this._time.equals(other._time); - } +var utils = __nccwpck_require__(20328); +var transformData = __nccwpck_require__(19812); +var isCancel = __nccwpck_require__(64057); +var defaults = __nccwpck_require__(98190); - return false; - }; +/** + * Throws a `Cancel` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } +} - _proto.hashCode = function hashCode() { - return this._date.hashCode() ^ this._time.hashCode(); - }; +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); - _proto.toString = function toString() { - return this._date.toString() + 'T' + this._time.toString(); - }; + // Ensure headers exist + config.headers = config.headers || {}; - _proto.toJSON = function toJSON() { - return this.toString(); - }; + // Transform request data + config.data = transformData( + config.data, + config.headers, + config.transformRequest + ); - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); - return LocalDateTime; - }(ChronoLocalDateTime); - function _init$j() { - LocalDateTime.MIN = LocalDateTime.of(LocalDate.MIN, LocalTime.MIN); - LocalDateTime.MAX = LocalDateTime.of(LocalDate.MAX, LocalTime.MAX); - LocalDateTime.FROM = createTemporalQuery('LocalDateTime.FROM', function (temporal) { - return LocalDateTime.from(temporal); - }); + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; } + ); - var LocalTime = function (_Temporal) { - _inheritsLoose(LocalTime, _Temporal); - - LocalTime.now = function now(clockOrZone) { - if (clockOrZone == null) { - return LocalTime._now(Clock.systemDefaultZone()); - } else if (clockOrZone instanceof Clock) { - return LocalTime._now(clockOrZone); - } else { - return LocalTime._now(Clock.system(clockOrZone)); - } - }; - - LocalTime._now = function _now(clock) { - if (clock === void 0) { - clock = Clock.systemDefaultZone(); - } - - requireNonNull(clock, 'clock'); - return LocalTime.ofInstant(clock.instant(), clock.zone()); - }; - - LocalTime.ofInstant = function ofInstant(instant, zone) { - if (zone === void 0) { - zone = ZoneId.systemDefault(); - } - - var offset = zone.rules().offset(instant); - var secsOfDay = MathUtil.intMod(instant.epochSecond(), LocalTime.SECONDS_PER_DAY); - secsOfDay = MathUtil.intMod(secsOfDay + offset.totalSeconds(), LocalTime.SECONDS_PER_DAY); - - if (secsOfDay < 0) { - secsOfDay += LocalTime.SECONDS_PER_DAY; - } - - return LocalTime.ofSecondOfDay(secsOfDay, instant.nano()); - }; + var adapter = config.adapter || defaults.adapter; - LocalTime.of = function of(hour, minute, second, nanoOfSecond) { - return new LocalTime(hour, minute, second, nanoOfSecond); - }; + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); - LocalTime.ofSecondOfDay = function ofSecondOfDay(secondOfDay, nanoOfSecond) { - if (secondOfDay === void 0) { - secondOfDay = 0; - } + // Transform response data + response.data = transformData( + response.data, + response.headers, + config.transformResponse + ); - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); - ChronoField.SECOND_OF_DAY.checkValidValue(secondOfDay); - ChronoField.NANO_OF_SECOND.checkValidValue(nanoOfSecond); - var hours = MathUtil.intDiv(secondOfDay, LocalTime.SECONDS_PER_HOUR); - secondOfDay -= hours * LocalTime.SECONDS_PER_HOUR; - var minutes = MathUtil.intDiv(secondOfDay, LocalTime.SECONDS_PER_MINUTE); - secondOfDay -= minutes * LocalTime.SECONDS_PER_MINUTE; - return new LocalTime(hours, minutes, secondOfDay, nanoOfSecond); - }; + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData( + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } - LocalTime.ofNanoOfDay = function ofNanoOfDay(nanoOfDay) { - if (nanoOfDay === void 0) { - nanoOfDay = 0; - } + return Promise.reject(reason); + }); +}; - ChronoField.NANO_OF_DAY.checkValidValue(nanoOfDay); - var hours = MathUtil.intDiv(nanoOfDay, LocalTime.NANOS_PER_HOUR); - nanoOfDay -= hours * LocalTime.NANOS_PER_HOUR; - var minutes = MathUtil.intDiv(nanoOfDay, LocalTime.NANOS_PER_MINUTE); - nanoOfDay -= minutes * LocalTime.NANOS_PER_MINUTE; - var seconds = MathUtil.intDiv(nanoOfDay, LocalTime.NANOS_PER_SECOND); - nanoOfDay -= seconds * LocalTime.NANOS_PER_SECOND; - return new LocalTime(hours, minutes, seconds, nanoOfDay); - }; - LocalTime.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - var time = temporal.query(TemporalQueries.localTime()); +/***/ }), - if (time == null) { - throw new DateTimeException("Unable to obtain LocalTime TemporalAccessor: " + temporal + ", type " + (temporal.constructor != null ? temporal.constructor.name : '')); - } +/***/ 21516: +/***/ ((module) => { - return time; - }; +"use strict"; - LocalTime.parse = function parse(text, formatter) { - if (formatter === void 0) { - formatter = DateTimeFormatter.ISO_LOCAL_TIME; - } - requireNonNull(formatter, 'formatter'); - return formatter.parse(text, LocalTime.FROM); - }; +/** + * Update an Error with the specified config, error code, and response. + * + * @param {Error} error The error to update. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The error. + */ +module.exports = function enhanceError(error, config, code, request, response) { + error.config = config; + if (code) { + error.code = code; + } - function LocalTime(hour, minute, second, nanoOfSecond) { - var _this; + error.request = request; + error.response = response; + error.isAxiosError = true; - if (hour === void 0) { - hour = 0; - } + error.toJSON = function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code + }; + }; + return error; +}; - if (minute === void 0) { - minute = 0; - } - if (second === void 0) { - second = 0; - } +/***/ }), - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } +/***/ 74831: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _this = _Temporal.call(this) || this; +"use strict"; - var _hour = MathUtil.safeToInt(hour); - var _minute = MathUtil.safeToInt(minute); +var utils = __nccwpck_require__(20328); - var _second = MathUtil.safeToInt(second); +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; - var _nanoOfSecond = MathUtil.safeToInt(nanoOfSecond); + var valueFromConfig2Keys = ['url', 'method', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; + var defaultToConfig2Keys = [ + 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', + 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' + ]; + var directMergeKeys = ['validateStatus']; - LocalTime._validate(_hour, _minute, _second, _nanoOfSecond); + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } - if (_minute === 0 && _second === 0 && _nanoOfSecond === 0) { - if (!LocalTime.HOURS[_hour]) { - _this._hour = _hour; - _this._minute = _minute; - _this._second = _second; - _this._nano = _nanoOfSecond; - LocalTime.HOURS[_hour] = _assertThisInitialized(_this); - } + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + } - return LocalTime.HOURS[_hour] || _assertThisInitialized(_this); - } + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } + }); - _this._hour = _hour; - _this._minute = _minute; - _this._second = _second; - _this._nano = _nanoOfSecond; - return _this; - } + utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); - LocalTime._validate = function _validate(hour, minute, second, nanoOfSecond) { - ChronoField.HOUR_OF_DAY.checkValidValue(hour); - ChronoField.MINUTE_OF_HOUR.checkValidValue(minute); - ChronoField.SECOND_OF_MINUTE.checkValidValue(second); - ChronoField.NANO_OF_SECOND.checkValidValue(nanoOfSecond); - }; + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); - var _proto = LocalTime.prototype; + utils.forEach(directMergeKeys, function merge(prop) { + if (prop in config2) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit.isTimeBased(); - } else if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isTimeBased(); - } + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys) + .concat(directMergeKeys); - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; + var otherKeys = Object + .keys(config1) + .concat(Object.keys(config2)) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); - _proto.range = function range(field) { - requireNonNull(field); - return _Temporal.prototype.range.call(this, field); - }; + utils.forEach(otherKeys, mergeDeepProperties); - _proto.get = function get(field) { - return this.getLong(field); - }; + return config; +}; - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); - if (field instanceof ChronoField) { - return this._get0(field); - } +/***/ }), - return field.getFrom(this); - }; +/***/ 13211: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto._get0 = function _get0(field) { - switch (field) { - case ChronoField.NANO_OF_SECOND: - return this._nano; +"use strict"; - case ChronoField.NANO_OF_DAY: - return this.toNanoOfDay(); - case ChronoField.MICRO_OF_SECOND: - return MathUtil.intDiv(this._nano, 1000); +var createError = __nccwpck_require__(15226); - case ChronoField.MICRO_OF_DAY: - return MathUtil.intDiv(this.toNanoOfDay(), 1000); +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + */ +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(createError( + 'Request failed with status code ' + response.status, + response.config, + null, + response.request, + response + )); + } +}; - case ChronoField.MILLI_OF_SECOND: - return MathUtil.intDiv(this._nano, 1000000); - case ChronoField.MILLI_OF_DAY: - return MathUtil.intDiv(this.toNanoOfDay(), 1000000); +/***/ }), - case ChronoField.SECOND_OF_MINUTE: - return this._second; +/***/ 19812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case ChronoField.SECOND_OF_DAY: - return this.toSecondOfDay(); +"use strict"; - case ChronoField.MINUTE_OF_HOUR: - return this._minute; - case ChronoField.MINUTE_OF_DAY: - return this._hour * 60 + this._minute; +var utils = __nccwpck_require__(20328); - case ChronoField.HOUR_OF_AMPM: - return MathUtil.intMod(this._hour, 12); +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +module.exports = function transformData(data, headers, fns) { + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn(data, headers); + }); - case ChronoField.CLOCK_HOUR_OF_AMPM: - { - var ham = MathUtil.intMod(this._hour, 12); - return ham % 12 === 0 ? 12 : ham; - } + return data; +}; - case ChronoField.HOUR_OF_DAY: - return this._hour; - case ChronoField.CLOCK_HOUR_OF_DAY: - return this._hour === 0 ? 24 : this._hour; +/***/ }), - case ChronoField.AMPM_OF_DAY: - return MathUtil.intDiv(this._hour, 12); - } +/***/ 98190: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - }; +"use strict"; - _proto.hour = function hour() { - return this._hour; - }; - _proto.minute = function minute() { - return this._minute; - }; +var utils = __nccwpck_require__(20328); +var normalizeHeaderName = __nccwpck_require__(36240); - _proto.second = function second() { - return this._second; - }; +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; - _proto.nano = function nano() { - return this._nano; - }; +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } +} - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = __nccwpck_require__(3454); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = __nccwpck_require__(68104); + } + return adapter; +} - if (adjuster instanceof LocalTime) { - return adjuster; - } +var defaults = { + adapter: getDefaultAdapter(), - assert(typeof adjuster.adjustInto === 'function', 'adjuster', IllegalArgumentException); - return adjuster.adjustInto(this); - }; + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); - requireInstance(field, TemporalField, 'field'); + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], - if (field instanceof ChronoField) { - field.checkValidValue(newValue); + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, - switch (field) { - case ChronoField.NANO_OF_SECOND: - return this.withNano(newValue); + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', - case ChronoField.NANO_OF_DAY: - return LocalTime.ofNanoOfDay(newValue); + maxContentLength: -1, + maxBodyLength: -1, - case ChronoField.MICRO_OF_SECOND: - return this.withNano(newValue * 1000); + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } +}; - case ChronoField.MICRO_OF_DAY: - return LocalTime.ofNanoOfDay(newValue * 1000); +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } +}; - case ChronoField.MILLI_OF_SECOND: - return this.withNano(newValue * 1000000); +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); - case ChronoField.MILLI_OF_DAY: - return LocalTime.ofNanoOfDay(newValue * 1000000); +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); - case ChronoField.SECOND_OF_MINUTE: - return this.withSecond(newValue); +module.exports = defaults; - case ChronoField.SECOND_OF_DAY: - return this.plusSeconds(newValue - this.toSecondOfDay()); - case ChronoField.MINUTE_OF_HOUR: - return this.withMinute(newValue); +/***/ }), - case ChronoField.MINUTE_OF_DAY: - return this.plusMinutes(newValue - (this._hour * 60 + this._minute)); +/***/ 77065: +/***/ ((module) => { - case ChronoField.HOUR_OF_AMPM: - return this.plusHours(newValue - MathUtil.intMod(this._hour, 12)); +"use strict"; - case ChronoField.CLOCK_HOUR_OF_AMPM: - return this.plusHours((newValue === 12 ? 0 : newValue) - MathUtil.intMod(this._hour, 12)); - case ChronoField.HOUR_OF_DAY: - return this.withHour(newValue); +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; - case ChronoField.CLOCK_HOUR_OF_DAY: - return this.withHour(newValue === 24 ? 0 : newValue); - case ChronoField.AMPM_OF_DAY: - return this.plusHours((newValue - MathUtil.intDiv(this._hour, 12)) * 12); - } +/***/ }), - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +/***/ 30646: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return field.adjustInto(this, newValue); - }; +"use strict"; - _proto.withHour = function withHour(hour) { - if (hour === void 0) { - hour = 0; - } - if (this._hour === hour) { - return this; - } +var utils = __nccwpck_require__(20328); - return new LocalTime(hour, this._minute, this._second, this._nano); - }; +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} - _proto.withMinute = function withMinute(minute) { - if (minute === void 0) { - minute = 0; - } +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } - if (this._minute === minute) { - return this; - } + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; - return new LocalTime(this._hour, minute, this._second, this._nano); - }; + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } - _proto.withSecond = function withSecond(second) { - if (second === void 0) { - second = 0; - } + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } - if (this._second === second) { - return this; + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); } + parts.push(encode(key) + '=' + encode(v)); + }); + }); - return new LocalTime(this._hour, this._minute, second, this._nano); - }; - - _proto.withNano = function withNano(nanoOfSecond) { - if (nanoOfSecond === void 0) { - nanoOfSecond = 0; - } + serializedParams = parts.join('&'); + } - if (this._nano === nanoOfSecond) { - return this; - } + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } - return new LocalTime(this._hour, this._minute, this._second, nanoOfSecond); - }; + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } - _proto.truncatedTo = function truncatedTo(unit) { - requireNonNull(unit, 'unit'); + return url; +}; - if (unit === ChronoUnit.NANOS) { - return this; - } - var unitDur = unit.duration(); +/***/ }), - if (unitDur.seconds() > LocalTime.SECONDS_PER_DAY) { - throw new DateTimeException('Unit is too large to be used for truncation'); - } +/***/ 57189: +/***/ ((module) => { - var dur = unitDur.toNanos(); +"use strict"; - if (MathUtil.intMod(LocalTime.NANOS_PER_DAY, dur) !== 0) { - throw new DateTimeException('Unit must divide into a standard day without remainder'); - } - var nod = this.toNanoOfDay(); - return LocalTime.ofNanoOfDay(MathUtil.intDiv(nod, dur) * dur); - }; +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(unit, 'unit'); +/***/ }), - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this.plusNanos(amountToAdd); +/***/ 21545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case ChronoUnit.MICROS: - return this.plusNanos(MathUtil.intMod(amountToAdd, LocalTime.MICROS_PER_DAY) * 1000); +"use strict"; - case ChronoUnit.MILLIS: - return this.plusNanos(MathUtil.intMod(amountToAdd, LocalTime.MILLIS_PER_DAY) * 1000000); - case ChronoUnit.SECONDS: - return this.plusSeconds(amountToAdd); +var utils = __nccwpck_require__(20328); - case ChronoUnit.MINUTES: - return this.plusMinutes(amountToAdd); +module.exports = ( + utils.isStandardBrowserEnv() ? - case ChronoUnit.HOURS: - return this.plusHours(amountToAdd); + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); - case ChronoUnit.HALF_DAYS: - return this.plusHours(MathUtil.intMod(amountToAdd, 2) * 12); + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); } - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } - - return unit.addTo(this, amountToAdd); - }; + if (utils.isString(path)) { + cookie.push('path=' + path); + } - _proto.plusHours = function plusHours(hoursToAdd) { - if (hoursToAdd === 0) { - return this; - } + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } - var newHour = MathUtil.intMod(MathUtil.intMod(hoursToAdd, LocalTime.HOURS_PER_DAY) + this._hour + LocalTime.HOURS_PER_DAY, LocalTime.HOURS_PER_DAY); - return new LocalTime(newHour, this._minute, this._second, this._nano); - }; + if (secure === true) { + cookie.push('secure'); + } - _proto.plusMinutes = function plusMinutes(minutesToAdd) { - if (minutesToAdd === 0) { - return this; - } + document.cookie = cookie.join('; '); + }, - var mofd = this._hour * LocalTime.MINUTES_PER_HOUR + this._minute; - var newMofd = MathUtil.intMod(MathUtil.intMod(minutesToAdd, LocalTime.MINUTES_PER_DAY) + mofd + LocalTime.MINUTES_PER_DAY, LocalTime.MINUTES_PER_DAY); + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, - if (mofd === newMofd) { - return this; + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); } - - var newHour = MathUtil.intDiv(newMofd, LocalTime.MINUTES_PER_HOUR); - var newMinute = MathUtil.intMod(newMofd, LocalTime.MINUTES_PER_HOUR); - return new LocalTime(newHour, newMinute, this._second, this._nano); }; + })() : - _proto.plusSeconds = function plusSeconds(secondsToAdd) { - if (secondsToAdd === 0) { - return this; - } - - var sofd = this._hour * LocalTime.SECONDS_PER_HOUR + this._minute * LocalTime.SECONDS_PER_MINUTE + this._second; - var newSofd = MathUtil.intMod(MathUtil.intMod(secondsToAdd, LocalTime.SECONDS_PER_DAY) + sofd + LocalTime.SECONDS_PER_DAY, LocalTime.SECONDS_PER_DAY); - - if (sofd === newSofd) { - return this; - } - - var newHour = MathUtil.intDiv(newSofd, LocalTime.SECONDS_PER_HOUR); - var newMinute = MathUtil.intMod(MathUtil.intDiv(newSofd, LocalTime.SECONDS_PER_MINUTE), LocalTime.MINUTES_PER_HOUR); - var newSecond = MathUtil.intMod(newSofd, LocalTime.SECONDS_PER_MINUTE); - return new LocalTime(newHour, newMinute, newSecond, this._nano); + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} }; + })() +); - _proto.plusNanos = function plusNanos(nanosToAdd) { - if (nanosToAdd === 0) { - return this; - } - - var nofd = this.toNanoOfDay(); - var newNofd = MathUtil.intMod(MathUtil.intMod(nanosToAdd, LocalTime.NANOS_PER_DAY) + nofd + LocalTime.NANOS_PER_DAY, LocalTime.NANOS_PER_DAY); - if (nofd === newNofd) { - return this; - } +/***/ }), - var newHour = MathUtil.intDiv(newNofd, LocalTime.NANOS_PER_HOUR); - var newMinute = MathUtil.intMod(MathUtil.intDiv(newNofd, LocalTime.NANOS_PER_MINUTE), LocalTime.MINUTES_PER_HOUR); - var newSecond = MathUtil.intMod(MathUtil.intDiv(newNofd, LocalTime.NANOS_PER_SECOND), LocalTime.SECONDS_PER_MINUTE); - var newNano = MathUtil.intMod(newNofd, LocalTime.NANOS_PER_SECOND); - return new LocalTime(newHour, newMinute, newSecond, newNano); - }; +/***/ 41301: +/***/ ((module) => { - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; +"use strict"; - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - requireNonNull(unit, 'unit'); - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; - _proto.minusHours = function minusHours(hoursToSubtract) { - return this.plusHours(-1 * MathUtil.intMod(hoursToSubtract, LocalTime.HOURS_PER_DAY)); - }; +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); +}; - _proto.minusMinutes = function minusMinutes(minutesToSubtract) { - return this.plusMinutes(-1 * MathUtil.intMod(minutesToSubtract, LocalTime.MINUTES_PER_DAY)); - }; - _proto.minusSeconds = function minusSeconds(secondsToSubtract) { - return this.plusSeconds(-1 * MathUtil.intMod(secondsToSubtract, LocalTime.SECONDS_PER_DAY)); - }; +/***/ }), - _proto.minusNanos = function minusNanos(nanosToSubtract) { - return this.plusNanos(-1 * MathUtil.intMod(nanosToSubtract, LocalTime.NANOS_PER_DAY)); - }; +/***/ 60650: +/***/ ((module) => { - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); +"use strict"; - if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } else if (_query === TemporalQueries.localTime()) { - return this; - } - if (_query === TemporalQueries.chronology() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.zone() || _query === TemporalQueries.offset() || _query === TemporalQueries.localDate()) { - return null; - } +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return (typeof payload === 'object') && (payload.isAxiosError === true); +}; - return _query.queryFrom(this); - }; - _proto.adjustInto = function adjustInto(temporal) { - return temporal.with(LocalTime.NANO_OF_DAY, this.toNanoOfDay()); - }; +/***/ }), - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - var end = LocalTime.from(endExclusive); +/***/ 33608: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (unit instanceof ChronoUnit) { - var nanosUntil = end.toNanoOfDay() - this.toNanoOfDay(); +"use strict"; - switch (unit) { - case ChronoUnit.NANOS: - return nanosUntil; - case ChronoUnit.MICROS: - return MathUtil.intDiv(nanosUntil, 1000); +var utils = __nccwpck_require__(20328); - case ChronoUnit.MILLIS: - return MathUtil.intDiv(nanosUntil, 1000000); +module.exports = ( + utils.isStandardBrowserEnv() ? - case ChronoUnit.SECONDS: - return MathUtil.intDiv(nanosUntil, LocalTime.NANOS_PER_SECOND); + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; - case ChronoUnit.MINUTES: - return MathUtil.intDiv(nanosUntil, LocalTime.NANOS_PER_MINUTE); + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; - case ChronoUnit.HOURS: - return MathUtil.intDiv(nanosUntil, LocalTime.NANOS_PER_HOUR); + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } - case ChronoUnit.HALF_DAYS: - return MathUtil.intDiv(nanosUntil, 12 * LocalTime.NANOS_PER_HOUR); - } + urlParsingNode.setAttribute('href', href); - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } - return unit.between(this, end); - }; + originURL = resolveURL(window.location.href); - _proto.atDate = function atDate(date) { - return LocalDateTime.of(date, this); + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); }; + })() : - _proto.toSecondOfDay = function toSecondOfDay() { - var total = this._hour * LocalTime.SECONDS_PER_HOUR; - total += this._minute * LocalTime.SECONDS_PER_MINUTE; - total += this._second; - return total; + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; }; + })() +); - _proto.toNanoOfDay = function toNanoOfDay() { - var total = this._hour * LocalTime.NANOS_PER_HOUR; - total += this._minute * LocalTime.NANOS_PER_MINUTE; - total += this._second * LocalTime.NANOS_PER_SECOND; - total += this._nano; - return total; - }; - _proto.compareTo = function compareTo(other) { - requireNonNull(other, 'other'); - requireInstance(other, LocalTime, 'other'); - var cmp = MathUtil.compareNumbers(this._hour, other._hour); +/***/ }), - if (cmp === 0) { - cmp = MathUtil.compareNumbers(this._minute, other._minute); +/***/ 36240: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (cmp === 0) { - cmp = MathUtil.compareNumbers(this._second, other._second); +"use strict"; - if (cmp === 0) { - cmp = MathUtil.compareNumbers(this._nano, other._nano); - } - } - } - return cmp; - }; +var utils = __nccwpck_require__(20328); - _proto.isAfter = function isAfter(other) { - return this.compareTo(other) > 0; - }; +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; + } + }); +}; - _proto.isBefore = function isBefore(other) { - return this.compareTo(other) < 0; - }; - _proto.equals = function equals(other) { - if (this === other) { - return true; - } +/***/ }), - if (other instanceof LocalTime) { - return this._hour === other._hour && this._minute === other._minute && this._second === other._second && this._nano === other._nano; - } +/***/ 86455: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return false; - }; +"use strict"; - _proto.hashCode = function hashCode() { - var nod = this.toNanoOfDay(); - return MathUtil.hash(nod); - }; - _proto.toString = function toString() { - var buf = ''; - var hourValue = this._hour; - var minuteValue = this._minute; - var secondValue = this._second; - var nanoValue = this._nano; - buf += hourValue < 10 ? '0' : ''; - buf += hourValue; - buf += minuteValue < 10 ? ':0' : ':'; - buf += minuteValue; - - if (secondValue > 0 || nanoValue > 0) { - buf += secondValue < 10 ? ':0' : ':'; - buf += secondValue; - - if (nanoValue > 0) { - buf += '.'; - - if (MathUtil.intMod(nanoValue, 1000000) === 0) { - buf += ('' + (MathUtil.intDiv(nanoValue, 1000000) + 1000)).substring(1); - } else if (MathUtil.intMod(nanoValue, 1000) === 0) { - buf += ('' + (MathUtil.intDiv(nanoValue, 1000) + 1000000)).substring(1); - } else { - buf += ('' + (nanoValue + 1000000000)).substring(1); - } - } - } +var utils = __nccwpck_require__(20328); - return buf; - }; +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; - _proto.toJSON = function toJSON() { - return this.toString(); - }; +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; - _proto.format = function format(formatter) { - requireNonNull(formatter, 'formatter'); - return formatter.format(this); - }; + if (!headers) { return parsed; } - return LocalTime; - }(Temporal); - function _init$k() { - LocalTime.HOURS = []; + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); - for (var hour = 0; hour < 24; hour++) { - LocalTime.of(hour, 0, 0, 0); + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } - - LocalTime.MIN = LocalTime.HOURS[0]; - LocalTime.MAX = new LocalTime(23, 59, 59, 999999999); - LocalTime.MIDNIGHT = LocalTime.HOURS[0]; - LocalTime.NOON = LocalTime.HOURS[12]; - LocalTime.FROM = createTemporalQuery('LocalTime.FROM', function (temporal) { - return LocalTime.from(temporal); - }); } - LocalTime.HOURS_PER_DAY = 24; - LocalTime.MINUTES_PER_HOUR = 60; - LocalTime.MINUTES_PER_DAY = LocalTime.MINUTES_PER_HOUR * LocalTime.HOURS_PER_DAY; - LocalTime.SECONDS_PER_MINUTE = 60; - LocalTime.SECONDS_PER_HOUR = LocalTime.SECONDS_PER_MINUTE * LocalTime.MINUTES_PER_HOUR; - LocalTime.SECONDS_PER_DAY = LocalTime.SECONDS_PER_HOUR * LocalTime.HOURS_PER_DAY; - LocalTime.MILLIS_PER_DAY = LocalTime.SECONDS_PER_DAY * 1000; - LocalTime.MICROS_PER_DAY = LocalTime.SECONDS_PER_DAY * 1000000; - LocalTime.NANOS_PER_SECOND = 1000000000; - LocalTime.NANOS_PER_MINUTE = LocalTime.NANOS_PER_SECOND * LocalTime.SECONDS_PER_MINUTE; - LocalTime.NANOS_PER_HOUR = LocalTime.NANOS_PER_MINUTE * LocalTime.MINUTES_PER_HOUR; - LocalTime.NANOS_PER_DAY = LocalTime.NANOS_PER_HOUR * LocalTime.HOURS_PER_DAY; - - var NANOS_PER_MILLI = 1000000; - var Instant = function (_Temporal) { - _inheritsLoose(Instant, _Temporal); - - Instant.now = function now(clock) { - if (clock === void 0) { - clock = Clock.systemUTC(); - } - - return clock.instant(); - }; - - Instant.ofEpochSecond = function ofEpochSecond(epochSecond, nanoAdjustment) { - if (nanoAdjustment === void 0) { - nanoAdjustment = 0; - } + }); - var secs = epochSecond + MathUtil.floorDiv(nanoAdjustment, LocalTime.NANOS_PER_SECOND); - var nos = MathUtil.floorMod(nanoAdjustment, LocalTime.NANOS_PER_SECOND); - return Instant._create(secs, nos); - }; + return parsed; +}; - Instant.ofEpochMilli = function ofEpochMilli(epochMilli) { - var secs = MathUtil.floorDiv(epochMilli, 1000); - var mos = MathUtil.floorMod(epochMilli, 1000); - return Instant._create(secs, mos * 1000000); - }; - Instant.from = function from(temporal) { - try { - var instantSecs = temporal.getLong(ChronoField.INSTANT_SECONDS); - var nanoOfSecond = temporal.get(ChronoField.NANO_OF_SECOND); - return Instant.ofEpochSecond(instantSecs, nanoOfSecond); - } catch (ex) { - throw new DateTimeException('Unable to obtain Instant from TemporalAccessor: ' + temporal + ', type ' + typeof temporal, ex); - } - }; +/***/ }), - Instant.parse = function parse(text) { - return DateTimeFormatter.ISO_INSTANT.parse(text, Instant.FROM); - }; +/***/ 74850: +/***/ ((module) => { - Instant._create = function _create(seconds, nanoOfSecond) { - if (seconds === 0 && nanoOfSecond === 0) { - return Instant.EPOCH; - } +"use strict"; - return new Instant(seconds, nanoOfSecond); - }; - Instant._validate = function _validate(seconds, nanoOfSecond) { - if (seconds < Instant.MIN_SECONDS || seconds > Instant.MAX_SECONDS) { - throw new DateTimeException('Instant exceeds minimum or maximum instant'); - } +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; - if (nanoOfSecond < 0 || nanoOfSecond > LocalTime.NANOS_PER_SECOND) { - throw new DateTimeException('Instant exceeds minimum or maximum instant'); - } - }; - function Instant(seconds, nanoOfSecond) { - var _this; +/***/ }), - _this = _Temporal.call(this) || this; +/***/ 20328: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Instant._validate(seconds, nanoOfSecond); +"use strict"; - _this._seconds = MathUtil.safeToInt(seconds); - _this._nanos = MathUtil.safeToInt(nanoOfSecond); - return _this; - } - var _proto = Instant.prototype; +var bind = __nccwpck_require__(77065); - _proto.isSupported = function isSupported(fieldOrUnit) { - if (fieldOrUnit instanceof ChronoField) { - return fieldOrUnit === ChronoField.INSTANT_SECONDS || fieldOrUnit === ChronoField.NANO_OF_SECOND || fieldOrUnit === ChronoField.MICRO_OF_SECOND || fieldOrUnit === ChronoField.MILLI_OF_SECOND; - } +/*global toString:true*/ - if (fieldOrUnit instanceof ChronoUnit) { - return fieldOrUnit.isTimeBased() || fieldOrUnit === ChronoUnit.DAYS; - } +// utils is a library of generic helper functions non-specific to axios - return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this); - }; +var toString = Object.prototype.toString; - _proto.range = function range(field) { - return _Temporal.prototype.range.call(this, field); - }; +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return toString.call(val) === '[object Array]'; +} - _proto.get = function get(field) { - return this.getLong(field); - }; +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} - _proto.getLong = function getLong(field) { - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.NANO_OF_SECOND: - return this._nanos; +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} - case ChronoField.MICRO_OF_SECOND: - return MathUtil.intDiv(this._nanos, 1000); +/** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; +} - case ChronoField.MILLI_OF_SECOND: - return MathUtil.intDiv(this._nanos, NANOS_PER_MILLI); +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); +} - case ChronoField.INSTANT_SECONDS: - return this._seconds; - } +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; +} - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} - return field.getFrom(this); - }; +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} - _proto.epochSecond = function epochSecond() { - return this._seconds; - }; - - _proto.nano = function nano() { - return this._nanos; - }; +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} - _proto.withAdjuster = function withAdjuster(adjuster) { - requireNonNull(adjuster, 'adjuster'); - return adjuster.adjustInto(this); - }; +/** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ +function isPlainObject(val) { + if (toString.call(val) !== '[object Object]') { + return false; + } - _proto.withFieldValue = function withFieldValue(field, newValue) { - requireNonNull(field, 'field'); + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; +} - if (field instanceof ChronoField) { - field.checkValidValue(newValue); +/** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +function isDate(val) { + return toString.call(val) === '[object Date]'; +} - switch (field) { - case ChronoField.MILLI_OF_SECOND: - { - var nval = newValue * NANOS_PER_MILLI; - return nval !== this._nanos ? Instant._create(this._seconds, nval) : this; - } +/** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +function isFile(val) { + return toString.call(val) === '[object File]'; +} - case ChronoField.MICRO_OF_SECOND: - { - var _nval = newValue * 1000; +/** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +function isBlob(val) { + return toString.call(val) === '[object Blob]'; +} - return _nval !== this._nanos ? Instant._create(this._seconds, _nval) : this; - } +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} - case ChronoField.NANO_OF_SECOND: - return newValue !== this._nanos ? Instant._create(this._seconds, newValue) : this; +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} - case ChronoField.INSTANT_SECONDS: - return newValue !== this._seconds ? Instant._create(newValue, this._nanos) : this; - } +/** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; +} - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); - } +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); +} - return field.adjustInto(this, newValue); - }; +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} - _proto.truncatedTo = function truncatedTo(unit) { - requireNonNull(unit, 'unit'); +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } - if (unit === ChronoUnit.NANOS) { - return this; - } + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } - var unitDur = unit.duration(); + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } +} - if (unitDur.seconds() > LocalTime.SECONDS_PER_DAY) { - throw new DateTimeException('Unit is too large to be used for truncation'); - } +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); + } else { + result[key] = val; + } + } - var dur = unitDur.toNanos(); + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} - if (MathUtil.intMod(LocalTime.NANOS_PER_DAY, dur) !== 0) { - throw new DateTimeException('Unit must divide into a standard day without remainder'); - } +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} - var nod = MathUtil.intMod(this._seconds, LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + this._nanos; +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * @return {string} content value without BOM + */ +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} - var result = MathUtil.intDiv(nod, dur) * dur; - return this.plusNanos(result - nod); - }; +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM +}; - _proto.plusAmount = function plusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.addTo(this); - }; - _proto.plusAmountUnit = function plusAmountUnit(amountToAdd, unit) { - requireNonNull(amountToAdd, 'amountToAdd'); - requireNonNull(unit, 'unit'); - requireInstance(unit, TemporalUnit); +/***/ }), - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this.plusNanos(amountToAdd); +/***/ 9417: +/***/ ((module) => { - case ChronoUnit.MICROS: - return this._plus(MathUtil.intDiv(amountToAdd, 1000000), MathUtil.intMod(amountToAdd, 1000000) * 1000); +"use strict"; - case ChronoUnit.MILLIS: - return this.plusMillis(amountToAdd); +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); - case ChronoUnit.SECONDS: - return this.plusSeconds(amountToAdd); + var r = range(a, b, str); - case ChronoUnit.MINUTES: - return this.plusSeconds(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_MINUTE)); + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} - case ChronoUnit.HOURS: - return this.plusSeconds(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_HOUR)); +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} - case ChronoUnit.HALF_DAYS: - return this.plusSeconds(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_DAY / 2)); +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; - case ChronoUnit.DAYS: - return this.plusSeconds(MathUtil.safeMultiply(amountToAdd, LocalTime.SECONDS_PER_DAY)); - } + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; } - return unit.addTo(this, amountToAdd); - }; - - _proto.plusSeconds = function plusSeconds(secondsToAdd) { - return this._plus(secondsToAdd, 0); - }; - - _proto.plusMillis = function plusMillis(millisToAdd) { - return this._plus(MathUtil.intDiv(millisToAdd, 1000), MathUtil.intMod(millisToAdd, 1000) * NANOS_PER_MILLI); - }; + bi = str.indexOf(b, i + 1); + } - _proto.plusNanos = function plusNanos(nanosToAdd) { - return this._plus(0, nanosToAdd); - }; + i = ai < bi && ai >= 0 ? ai : bi; + } - _proto._plus = function _plus(secondsToAdd, nanosToAdd) { - if (secondsToAdd === 0 && nanosToAdd === 0) { - return this; - } + if (begs.length) { + result = [ left, right ]; + } + } - var epochSec = this._seconds + secondsToAdd; - epochSec = epochSec + MathUtil.intDiv(nanosToAdd, LocalTime.NANOS_PER_SECOND); - var nanoAdjustment = this._nanos + nanosToAdd % LocalTime.NANOS_PER_SECOND; - return Instant.ofEpochSecond(epochSec, nanoAdjustment); - }; + return result; +} - _proto.minusAmount = function minusAmount(amount) { - requireNonNull(amount, 'amount'); - return amount.subtractFrom(this); - }; - _proto.minusAmountUnit = function minusAmountUnit(amountToSubtract, unit) { - return this.plusAmountUnit(-1 * amountToSubtract, unit); - }; +/***/ }), - _proto.minusSeconds = function minusSeconds(secondsToSubtract) { - return this.plusSeconds(secondsToSubtract * -1); - }; +/***/ 45447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _proto.minusMillis = function minusMillis(millisToSubtract) { - return this.plusMillis(-1 * millisToSubtract); - }; +"use strict"; - _proto.minusNanos = function minusNanos(nanosToSubtract) { - return this.plusNanos(-1 * nanosToSubtract); - }; - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); +var crypto_hash_sha512 = __nccwpck_require__(68729).lowlevel.crypto_hash; - if (_query === TemporalQueries.precision()) { - return ChronoUnit.NANOS; - } +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. + * + * Credit for the actual porting work goes to: + * Devi Mandiri + */ - if (_query === TemporalQueries.localDate() || _query === TemporalQueries.localTime() || _query === TemporalQueries.chronology() || _query === TemporalQueries.zoneId() || _query === TemporalQueries.zone() || _query === TemporalQueries.offset()) { - return null; - } +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + */ - return _query.queryFrom(this); - }; +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst + * + * Permission to use, copy, modify, and 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. + */ - _proto.adjustInto = function adjustInto(temporal) { - requireNonNull(temporal, 'temporal'); - return temporal.with(ChronoField.INSTANT_SECONDS, this._seconds).with(ChronoField.NANO_OF_SECOND, this._nanos); - }; +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and 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. + */ + +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 + +var BLF_J = 0; + +var Blowfish = function() { + this.S = [ + new Uint32Array([ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), + new Uint32Array([ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), + new Uint32Array([ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), + new Uint32Array([ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) + ]; + this.P = new Uint32Array([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b]); +}; - _proto.until = function until(endExclusive, unit) { - requireNonNull(endExclusive, 'endExclusive'); - requireNonNull(unit, 'unit'); - var end = Instant.from(endExclusive); +function F(S, x8, i) { + return (((S[0][x8[i+3]] + + S[1][x8[i+2]]) ^ + S[2][x8[i+1]]) + + S[3][x8[i]]); +}; - if (unit instanceof ChronoUnit) { - switch (unit) { - case ChronoUnit.NANOS: - return this._nanosUntil(end); +Blowfish.prototype.encipher = function(x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + } + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; +}; - case ChronoUnit.MICROS: - return MathUtil.intDiv(this._nanosUntil(end), 1000); +Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; - case ChronoUnit.MILLIS: - return MathUtil.safeSubtract(end.toEpochMilli(), this.toEpochMilli()); +function stream2word(data, databytes){ + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +}; - case ChronoUnit.SECONDS: - return this._secondsUntil(end); +Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); - case ChronoUnit.MINUTES: - return MathUtil.intDiv(this._secondsUntil(end), LocalTime.SECONDS_PER_MINUTE); + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; - case ChronoUnit.HOURS: - return MathUtil.intDiv(this._secondsUntil(end), LocalTime.SECONDS_PER_HOUR); + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } - case ChronoUnit.HALF_DAYS: - return MathUtil.intDiv(this._secondsUntil(end), 12 * LocalTime.SECONDS_PER_HOUR); + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; + } + } +}; - case ChronoUnit.DAYS: - return MathUtil.intDiv(this._secondsUntil(end), LocalTime.SECONDS_PER_DAY); - } +Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; - throw new UnsupportedTemporalTypeException('Unsupported unit: ' + unit); - } + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } - return unit.between(this, end); - }; + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } - _proto._nanosUntil = function _nanosUntil(end) { - var secsDiff = MathUtil.safeSubtract(end.epochSecond(), this.epochSecond()); - var totalNanos = MathUtil.safeMultiply(secsDiff, LocalTime.NANOS_PER_SECOND); - return MathUtil.safeAdd(totalNanos, end.nano() - this.nano()); - }; + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; + } + } + BLF_J = 0; +}; - _proto._secondsUntil = function _secondsUntil(end) { - var secsDiff = MathUtil.safeSubtract(end.epochSecond(), this.epochSecond()); - var nanosDiff = end.nano() - this.nano(); +Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i*2)); + } +}; - if (secsDiff > 0 && nanosDiff < 0) { - secsDiff--; - } else if (secsDiff < 0 && nanosDiff > 0) { - secsDiff++; - } +Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i*2)); + } +}; - return secsDiff; - }; +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; - _proto.atOffset = function atOffset(offset) { - return OffsetDateTime.ofInstant(this, offset); - }; +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), i, + ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, + 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, + 105,116,101]); //"OxychromaticBlowfishSwatDynamite" - _proto.atZone = function atZone(zone) { - return ZonedDateTime.ofInstant(this, zone); - }; + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } - _proto.toEpochMilli = function toEpochMilli() { - var millis = MathUtil.safeMultiply(this._seconds, 1000); - return millis + MathUtil.intDiv(this._nanos, NANOS_PER_MILLI); - }; + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); - _proto.compareTo = function compareTo(otherInstant) { - requireNonNull(otherInstant, 'otherInstant'); - requireInstance(otherInstant, Instant, 'otherInstant'); - var cmp = MathUtil.compareNumbers(this._seconds, otherInstant._seconds); + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4*i+3] = cdata[i] >>> 24; + out[4*i+2] = cdata[i] >>> 16; + out[4*i+1] = cdata[i] >>> 8; + out[4*i+0] = cdata[i]; + } +}; - if (cmp !== 0) { - return cmp; - } +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen+4), + i, j, amt, stride, dest, count, + origkeylen = keylen; - return this._nanos - otherInstant._nanos; - }; + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || + keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) + return -1; - _proto.isAfter = function isAfter(otherInstant) { - return this.compareTo(otherInstant) > 0; - }; + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); - _proto.isBefore = function isBefore(otherInstant) { - return this.compareTo(otherInstant) < 0; - }; + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; - _proto.equals = function equals(other) { - if (this === other) { - return true; - } + crypto_hash_sha512(sha2pass, pass, passlen); - if (other instanceof Instant) { - return this.epochSecond() === other.epochSecond() && this.nano() === other.nano(); - } + for (count = 1; keylen > 0; count++) { + countsalt[saltlen+0] = count >>> 24; + countsalt[saltlen+1] = count >>> 16; + countsalt[saltlen+2] = count >>> 8; + countsalt[saltlen+3] = count; - return false; - }; + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--;) + out[i] = tmpout[i]; - _proto.hashCode = function hashCode() { - return MathUtil.hashCode(this._seconds, this._nanos); - }; + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; + } - _proto.toString = function toString() { - return DateTimeFormatter.ISO_INSTANT.format(this); - }; + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; + } + keylen -= i; + } - _proto.toJSON = function toJSON() { - return this.toString(); - }; + return 0; +}; - return Instant; - }(Temporal); - function _init$l() { - Instant.MIN_SECONDS = -31619119219200; - Instant.MAX_SECONDS = 31494816403199; - Instant.EPOCH = new Instant(0, 0); - Instant.MIN = Instant.ofEpochSecond(Instant.MIN_SECONDS, 0); - Instant.MAX = Instant.ofEpochSecond(Instant.MAX_SECONDS, 999999999); - Instant.FROM = createTemporalQuery('Instant.FROM', function (temporal) { - return Instant.from(temporal); - }); - } +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf +}; - var Clock = function () { - function Clock() {} - Clock.systemUTC = function systemUTC() { - return new SystemClock(ZoneOffset.UTC); - }; +/***/ }), - Clock.systemDefaultZone = function systemDefaultZone() { - return new SystemClock(ZoneId.systemDefault()); - }; +/***/ 20336: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Clock.system = function system(zone) { - return new SystemClock(zone); - }; +"use strict"; - Clock.fixed = function fixed(fixedInstant, zoneId) { - return new FixedClock(fixedInstant, zoneId); - }; +var DuplexStream = __nccwpck_require__(85519).Duplex + , util = __nccwpck_require__(31669) - Clock.offset = function offset(baseClock, duration) { - return new OffsetClock(baseClock, duration); - }; +function BufferList (callback) { + if (!(this instanceof BufferList)) + return new BufferList(callback) - var _proto = Clock.prototype; + this._bufs = [] + this.length = 0 - _proto.millis = function millis() { - abstractMethodFail('Clock.millis'); - }; + if (typeof callback == 'function') { + this._callback = callback - _proto.instant = function instant() { - abstractMethodFail('Clock.instant'); - }; + var piper = function piper (err) { + if (this._callback) { + this._callback(err) + this._callback = null + } + }.bind(this) - _proto.zone = function zone() { - abstractMethodFail('Clock.zone'); - }; + this.on('pipe', function onPipe (src) { + src.on('error', piper) + }) + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper) + }) + } else { + this.append(callback) + } - _proto.withZone = function withZone() { - abstractMethodFail('Clock.withZone'); - }; + DuplexStream.call(this) +} - return Clock; - }(); - var SystemClock = function (_Clock) { - _inheritsLoose(SystemClock, _Clock); +util.inherits(BufferList, DuplexStream) - function SystemClock(zone) { - var _this; - requireNonNull(zone, 'zone'); - _this = _Clock.call(this) || this; - _this._zone = zone; - return _this; - } +BufferList.prototype._offset = function _offset (offset) { + var tot = 0, i = 0, _t + if (offset === 0) return [ 0, 0 ] + for (; i < this._bufs.length; i++) { + _t = tot + this._bufs[i].length + if (offset < _t || i == this._bufs.length - 1) { + return [ i, offset - tot ] + } + tot = _t + } +} - var _proto2 = SystemClock.prototype; +BufferList.prototype._reverseOffset = function (blOffset) { + var bufferId = blOffset[0] + var offset = blOffset[1] + for (var i = 0; i < bufferId; i++) { + offset += this._bufs[i].length + } + return offset +} - _proto2.zone = function zone() { - return this._zone; - }; +BufferList.prototype.append = function append (buf) { + var i = 0 - _proto2.millis = function millis() { - return new Date().getTime(); - }; + if (Buffer.isBuffer(buf)) { + this._appendBuffer(buf) + } else if (Array.isArray(buf)) { + for (; i < buf.length; i++) + this.append(buf[i]) + } else if (buf instanceof BufferList) { + // unwrap argument into individual BufferLists + for (; i < buf._bufs.length; i++) + this.append(buf._bufs[i]) + } else if (buf != null) { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf == 'number') + buf = buf.toString() - _proto2.instant = function instant() { - return Instant.ofEpochMilli(this.millis()); - }; + this._appendBuffer(Buffer.from(buf)) + } - _proto2.equals = function equals(obj) { - if (obj instanceof SystemClock) { - return this._zone.equals(obj._zone); - } + return this +} - return false; - }; - _proto2.withZone = function withZone(zone) { - if (zone.equals(this._zone)) { - return this; - } +BufferList.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf) + this.length += buf.length +} - return new SystemClock(zone); - }; - _proto2.toString = function toString() { - return 'SystemClock[' + this._zone.toString() + ']'; - }; +BufferList.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf) - return SystemClock; - }(Clock); + if (typeof callback == 'function') + callback() +} - var FixedClock = function (_Clock2) { - _inheritsLoose(FixedClock, _Clock2); - function FixedClock(fixedInstant, zoneId) { - var _this2; +BufferList.prototype._read = function _read (size) { + if (!this.length) + return this.push(null) - _this2 = _Clock2.call(this) || this; - _this2._instant = fixedInstant; - _this2._zoneId = zoneId; - return _this2; - } + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} - var _proto3 = FixedClock.prototype; - _proto3.instant = function instant() { - return this._instant; - }; +BufferList.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk) - _proto3.millis = function millis() { - return this._instant.toEpochMilli(); - }; + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null + } +} - _proto3.zone = function zone() { - return this._zoneId; - }; - _proto3.toString = function toString() { - return 'FixedClock[]'; - }; +BufferList.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined + } + var offset = this._offset(index) + return this._bufs[offset[0]][offset[1]] +} - _proto3.equals = function equals(obj) { - if (obj instanceof FixedClock) { - return this._instant.equals(obj._instant) && this._zoneId.equals(obj._zoneId); - } - return false; - }; +BufferList.prototype.slice = function slice (start, end) { + if (typeof start == 'number' && start < 0) + start += this.length + if (typeof end == 'number' && end < 0) + end += this.length + return this.copy(null, 0, start, end) +} - _proto3.withZone = function withZone(zone) { - if (zone.equals(this._zoneId)) { - return this; - } - return new FixedClock(this._instant, zone); - }; +BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart != 'number' || srcStart < 0) + srcStart = 0 + if (typeof srcEnd != 'number' || srcEnd > this.length) + srcEnd = this.length + if (srcStart >= this.length) + return dst || Buffer.alloc(0) + if (srcEnd <= 0) + return dst || Buffer.alloc(0) - return FixedClock; - }(Clock); + var copy = !!dst + , off = this._offset(srcStart) + , len = srcEnd - srcStart + , bytes = len + , bufoff = (copy && dstStart) || 0 + , start = off[1] + , l + , i - var OffsetClock = function (_Clock3) { - _inheritsLoose(OffsetClock, _Clock3); + // copy/slice everything + if (srcStart === 0 && srcEnd == this.length) { + if (!copy) { // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer.concat(this._bufs, this.length) + } - function OffsetClock(baseClock, offset) { - var _this3; + // copy, need to copy individual buffers + for (i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } - _this3 = _Clock3.call(this) || this; - _this3._baseClock = baseClock; - _this3._offset = offset; - return _this3; - } + return dst + } - var _proto4 = OffsetClock.prototype; + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } - _proto4.zone = function zone() { - return this._baseClock.zone(); - }; + if (!copy) // a slice, we need something to copy in to + dst = Buffer.allocUnsafe(len) - _proto4.withZone = function withZone(zone) { - if (zone.equals(this._baseClock.zone())) { - return this; - } + for (i = off[0]; i < this._bufs.length; i++) { + l = this._bufs[i].length - start - return new OffsetClock(this._baseClock.withZone(zone), this._offset); - }; + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + bufoff += l + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l + break + } - _proto4.millis = function millis() { - return this._baseClock.millis() + this._offset.toMillis(); - }; + bytes -= l - _proto4.instant = function instant() { - return this._baseClock.instant().plus(this._offset); - }; + if (start) + start = 0 + } - _proto4.equals = function equals(obj) { - if (obj instanceof OffsetClock) { - return this._baseClock.equals(obj._baseClock) && this._offset.equals(obj._offset); - } + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) - return false; - }; + return dst +} - _proto4.toString = function toString() { - return 'OffsetClock[' + this._baseClock + ',' + this._offset + ']'; - }; +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = typeof end !== 'number' ? this.length : end - return OffsetClock; - }(Clock); + if (start < 0) + start += this.length + if (end < 0) + end += this.length - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ZoneOffsetTransition = function () { - ZoneOffsetTransition.of = function of(transition, offsetBefore, offsetAfter) { - return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); - }; + if (start === end) { + return new BufferList() + } + var startOffset = this._offset(start) + , endOffset = this._offset(end) + , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - function ZoneOffsetTransition(transition, offsetBefore, offsetAfter) { - requireNonNull(transition, 'transition'); - requireNonNull(offsetBefore, 'offsetBefore'); - requireNonNull(offsetAfter, 'offsetAfter'); + if (endOffset[1] == 0) + buffers.pop() + else + buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) - if (offsetBefore.equals(offsetAfter)) { - throw new IllegalArgumentException('Offsets must not be equal'); - } + if (startOffset[1] != 0) + buffers[0] = buffers[0].slice(startOffset[1]) - if (transition.nano() !== 0) { - throw new IllegalArgumentException('Nano-of-second must be zero'); - } + return new BufferList(buffers) +} - if (transition instanceof LocalDateTime) { - this._transition = transition; - } else { - this._transition = LocalDateTime.ofEpochSecond(transition, 0, offsetBefore); - } +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} - this._offsetBefore = offsetBefore; - this._offsetAfter = offsetAfter; - } +BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this - var _proto = ZoneOffsetTransition.prototype; + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() + } else { + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break + } + } + return this +} - _proto.instant = function instant() { - return this._transition.toInstant(this._offsetBefore); - }; - _proto.toEpochSecond = function toEpochSecond() { - return this._transition.toEpochSecond(this._offsetBefore); - }; +BufferList.prototype.duplicate = function duplicate () { + var i = 0 + , copy = new BufferList() - _proto.dateTimeBefore = function dateTimeBefore() { - return this._transition; - }; + for (; i < this._bufs.length; i++) + copy.append(this._bufs[i]) - _proto.dateTimeAfter = function dateTimeAfter() { - return this._transition.plusSeconds(this.durationSeconds()); - }; + return copy +} - _proto.offsetBefore = function offsetBefore() { - return this._offsetBefore; - }; - _proto.offsetAfter = function offsetAfter() { - return this._offsetAfter; - }; +BufferList.prototype._destroy = function _destroy (err, cb) { + this._bufs.length = 0 + this.length = 0 + cb(err) +} - _proto.duration = function duration() { - return Duration.ofSeconds(this.durationSeconds()); - }; - _proto.durationSeconds = function durationSeconds() { - return this._offsetAfter.totalSeconds() - this._offsetBefore.totalSeconds(); - }; +BufferList.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + } + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer.from([search]) + } else if (typeof search === 'string') { + search = Buffer.from(search, encoding) + } else if (search instanceof BufferList) { + search = search.slice() + } else if (!Buffer.isBuffer(search)) { + search = Buffer.from(search) + } - _proto.isGap = function isGap() { - return this._offsetAfter.totalSeconds() > this._offsetBefore.totalSeconds(); - }; + offset = Number(offset || 0) + if (isNaN(offset)) { + offset = 0 + } - _proto.isOverlap = function isOverlap() { - return this._offsetAfter.totalSeconds() < this._offsetBefore.totalSeconds(); - }; + if (offset < 0) { + offset = this.length + offset + } - _proto.isValidOffset = function isValidOffset(offset) { - return this.isGap() ? false : this._offsetBefore.equals(offset) || this._offsetAfter.equals(offset); - }; + if (offset < 0) { + offset = 0 + } - _proto.validOffsets = function validOffsets() { - if (this.isGap()) { - return []; - } else { - return [this._offsetBefore, this._offsetAfter]; - } - }; + if (search.length === 0) { + return offset > this.length ? this.length : offset + } - _proto.compareTo = function compareTo(transition) { - return this.instant().compareTo(transition.instant()); - }; + var blOffset = this._offset(offset) + var blIndex = blOffset[0] // index of which internal buffer we're working on + var buffOffset = blOffset[1] // offset of the internal buffer we're working on - _proto.equals = function equals(other) { - if (other === this) { - return true; + // scan over each buffer + for (blIndex; blIndex < this._bufs.length; blIndex++) { + var buff = this._bufs[blIndex] + while(buffOffset < buff.length) { + var availableWindow = buff.length - buffOffset + if (availableWindow >= search.length) { + var nativeSearchResult = buff.indexOf(search, buffOffset) + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) } - - if (other instanceof ZoneOffsetTransition) { - var d = other; - return this._transition.equals(d._transition) && this._offsetBefore.equals(d.offsetBefore()) && this._offsetAfter.equals(d.offsetAfter()); + buffOffset = buff.length - search.length + 1 // end of native search window + } else { + var revOffset = this._reverseOffset([blIndex, buffOffset]) + if (this._match(revOffset, search)) { + return revOffset } + buffOffset++ + } + } + buffOffset = 0 + } + return -1 +} - return false; - }; - - _proto.hashCode = function hashCode() { - return this._transition.hashCode() ^ this._offsetBefore.hashCode() ^ this._offsetAfter.hashCode() >>> 16; - }; - - _proto.toString = function toString() { - return 'Transition[' + (this.isGap() ? 'Gap' : 'Overlap') + ' at ' + this._transition.toString() + this._offsetBefore.toString() + ' to ' + this._offsetAfter + ']'; - }; +BufferList.prototype._match = function(offset, search) { + if (this.length - offset < search.length) { + return false + } + for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) { + if(this.get(offset + searchOffset) !== search[searchOffset]){ + return false + } + } + return true +} - return ZoneOffsetTransition; - }(); - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - function _init$m() { - TemporalQueries.ZONE_ID = createTemporalQuery('ZONE_ID', function (temporal) { - return temporal.query(TemporalQueries.ZONE_ID); - }); - TemporalQueries.CHRONO = createTemporalQuery('CHRONO', function (temporal) { - return temporal.query(TemporalQueries.CHRONO); - }); - TemporalQueries.PRECISION = createTemporalQuery('PRECISION', function (temporal) { - return temporal.query(TemporalQueries.PRECISION); - }); - TemporalQueries.OFFSET = createTemporalQuery('OFFSET', function (temporal) { - if (temporal.isSupported(ChronoField.OFFSET_SECONDS)) { - return ZoneOffset.ofTotalSeconds(temporal.get(ChronoField.OFFSET_SECONDS)); +;(function () { + var methods = { + 'readDoubleBE' : 8 + , 'readDoubleLE' : 8 + , 'readFloatBE' : 4 + , 'readFloatLE' : 4 + , 'readInt32BE' : 4 + , 'readInt32LE' : 4 + , 'readUInt32BE' : 4 + , 'readUInt32LE' : 4 + , 'readInt16BE' : 2 + , 'readInt16LE' : 2 + , 'readUInt16BE' : 2 + , 'readUInt16LE' : 2 + , 'readInt8' : 1 + , 'readUInt8' : 1 + , 'readIntBE' : null + , 'readIntLE' : null + , 'readUIntBE' : null + , 'readUIntLE' : null + } + + for (var m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) } - - return null; - }); - TemporalQueries.ZONE = createTemporalQuery('ZONE', function (temporal) { - var zone = temporal.query(TemporalQueries.ZONE_ID); - return zone != null ? zone : temporal.query(TemporalQueries.OFFSET); - }); - TemporalQueries.LOCAL_DATE = createTemporalQuery('LOCAL_DATE', function (temporal) { - if (temporal.isSupported(ChronoField.EPOCH_DAY)) { - return LocalDate.ofEpochDay(temporal.getLong(ChronoField.EPOCH_DAY)); + } + else { + BufferList.prototype[m] = function (offset) { + return this.slice(offset, offset + methods[m])[m](0) } + } + }(m)) + } +}()) - return null; - }); - TemporalQueries.LOCAL_TIME = createTemporalQuery('LOCAL_TIME', function (temporal) { - if (temporal.isSupported(ChronoField.NANO_OF_DAY)) { - return LocalTime.ofNanoOfDay(temporal.getLong(ChronoField.NANO_OF_DAY)); - } - return null; - }); - } +module.exports = BufferList - var SystemDefaultZoneRules = function (_ZoneRules) { - _inheritsLoose(SystemDefaultZoneRules, _ZoneRules); - function SystemDefaultZoneRules() { - return _ZoneRules.apply(this, arguments) || this; - } +/***/ }), - var _proto = SystemDefaultZoneRules.prototype; +/***/ 97713: +/***/ ((module) => { - _proto.isFixedOffset = function isFixedOffset() { - return false; - }; +"use strict"; - _proto.offsetOfInstant = function offsetOfInstant(instant) { - var offsetInMinutes = new Date(instant.toEpochMilli()).getTimezoneOffset(); - return ZoneOffset.ofTotalMinutes(offsetInMinutes * -1); - }; - _proto.offsetOfEpochMilli = function offsetOfEpochMilli(epochMilli) { - var offsetInMinutes = new Date(epochMilli).getTimezoneOffset(); - return ZoneOffset.ofTotalMinutes(offsetInMinutes * -1); - }; +const codes = {}; - _proto.offsetOfLocalDateTime = function offsetOfLocalDateTime(localDateTime) { - var epochMilli = localDateTime.toEpochSecond(ZoneOffset.UTC) * 1000; - var offsetInMinutesBeforePossibleTransition = new Date(epochMilli).getTimezoneOffset(); - var epochMilliSystemZone = epochMilli + offsetInMinutesBeforePossibleTransition * 60000; - var offsetInMinutesAfterPossibleTransition = new Date(epochMilliSystemZone).getTimezoneOffset(); - return ZoneOffset.ofTotalMinutes(offsetInMinutesAfterPossibleTransition * -1); - }; +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } - _proto.validOffsets = function validOffsets(localDateTime) { - return [this.offsetOfLocalDateTime(localDateTime)]; - }; + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } - _proto.transition = function transition() { - return null; - }; + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } - _proto.standardOffset = function standardOffset(instant) { - return this.offsetOfInstant(instant); - }; + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; - _proto.daylightSavings = function daylightSavings() { - this._throwNotSupported(); - }; + codes[code] = NodeError; +} - _proto.isDaylightSavings = function isDaylightSavings() { - this._throwNotSupported(); - }; +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} - _proto.isValidOffset = function isValidOffset(dateTime, offset) { - return this.offsetOfLocalDateTime(dateTime).equals(offset); - }; +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} - _proto.nextTransition = function nextTransition() { - this._throwNotSupported(); - }; +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} - _proto.previousTransition = function previousTransition() { - this._throwNotSupported(); - }; +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } - _proto.transitions = function transitions() { - this._throwNotSupported(); - }; + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} - _proto.transitionRules = function transitionRules() { - this._throwNotSupported(); - }; +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } - _proto._throwNotSupported = function _throwNotSupported() { - throw new DateTimeException('not supported operation'); - }; + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } - _proto.equals = function equals(other) { - if (this === other || other instanceof SystemDefaultZoneRules) { - return true; - } else { - return false; - } - }; + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - _proto.toString = function toString() { - return 'SYSTEM'; - }; +module.exports.q = codes; - return SystemDefaultZoneRules; - }(ZoneRules); - var SystemDefaultZoneId = function (_ZoneId) { - _inheritsLoose(SystemDefaultZoneId, _ZoneId); +/***/ }), - function SystemDefaultZoneId() { - var _this; +/***/ 13928: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _this = _ZoneId.call(this) || this; - _this._rules = new SystemDefaultZoneRules(); - return _this; - } +"use strict"; +// 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. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. - var _proto = SystemDefaultZoneId.prototype; +/**/ - _proto.rules = function rules() { - return this._rules; - }; +var objectKeys = Object.keys || function (obj) { + var keys = []; - _proto.equals = function equals(other) { - if (this === other) { - return true; - } + for (var key in obj) { + keys.push(key); + } - return false; - }; + return keys; +}; +/**/ - _proto.id = function id() { - return 'SYSTEM'; - }; - return SystemDefaultZoneId; - }(ZoneId); +module.exports = Duplex; - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var ZoneIdFactory = function () { - function ZoneIdFactory() {} +var Readable = __nccwpck_require__(85209); - ZoneIdFactory.systemDefault = function systemDefault() { - return SYSTEM_DEFAULT_ZONE_ID_INSTANCE; - }; +var Writable = __nccwpck_require__(58729); - ZoneIdFactory.getAvailableZoneIds = function getAvailableZoneIds() { - return ZoneRulesProvider.getAvailableZoneIds(); - }; +__nccwpck_require__(44124)(Duplex, Readable); - ZoneIdFactory.of = function of(zoneId) { - requireNonNull(zoneId, 'zoneId'); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); - if (zoneId === 'Z') { - return ZoneOffset.UTC; - } + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} - if (zoneId.length === 1) { - throw new DateTimeException('Invalid zone: ' + zoneId); - } +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; - if (StringUtil.startsWith(zoneId, '+') || StringUtil.startsWith(zoneId, '-')) { - return ZoneOffset.of(zoneId); - } + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; - if (zoneId === 'UTC' || zoneId === 'GMT' || zoneId === 'GMT0' || zoneId === 'UT') { - return new ZoneRegion(zoneId, ZoneOffset.UTC.rules()); - } + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} - if (StringUtil.startsWith(zoneId, 'UTC+') || StringUtil.startsWith(zoneId, 'GMT+') || StringUtil.startsWith(zoneId, 'UTC-') || StringUtil.startsWith(zoneId, 'GMT-')) { - var offset = ZoneOffset.of(zoneId.substring(3)); +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer - if (offset.totalSeconds() === 0) { - return new ZoneRegion(zoneId.substring(0, 3), offset.rules()); - } +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. - return new ZoneRegion(zoneId.substring(0, 3) + offset.id(), offset.rules()); - } + process.nextTick(onEndNT, this); +} - if (StringUtil.startsWith(zoneId, 'UT+') || StringUtil.startsWith(zoneId, 'UT-')) { - var _offset = ZoneOffset.of(zoneId.substring(2)); +function onEndNT(self) { + self.end(); +} - if (_offset.totalSeconds() === 0) { - return new ZoneRegion('UT', _offset.rules()); - } +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } - return new ZoneRegion('UT' + _offset.id(), _offset.rules()); - } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - if (zoneId === 'SYSTEM') { - return ZoneId.systemDefault(); - } - return ZoneRegion.ofId(zoneId); - }; + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); - ZoneIdFactory.ofOffset = function ofOffset(prefix, offset) { - requireNonNull(prefix, 'prefix'); - requireNonNull(offset, 'offset'); +/***/ }), - if (prefix.length === 0) { - return offset; - } +/***/ 4991: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (prefix === 'GMT' || prefix === 'UTC' || prefix === 'UT') { - if (offset.totalSeconds() === 0) { - return new ZoneRegion(prefix, offset.rules()); - } +"use strict"; +// 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. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - return new ZoneRegion(prefix + offset.id(), offset.rules()); - } - throw new IllegalArgumentException('Invalid prefix, must be GMT, UTC or UT: ' + prefix); - }; +module.exports = PassThrough; - ZoneIdFactory.from = function from(temporal) { - requireNonNull(temporal, 'temporal'); - var obj = temporal.query(TemporalQueries.zone()); +var Transform = __nccwpck_require__(26753); - if (obj == null) { - throw new DateTimeException('Unable to obtain ZoneId from TemporalAccessor: ' + temporal + ', type ' + (temporal.constructor != null ? temporal.constructor.name : '')); - } +__nccwpck_require__(44124)(PassThrough, Transform); - return obj; - }; +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} - return ZoneIdFactory; - }(); - var SYSTEM_DEFAULT_ZONE_ID_INSTANCE = null; - function _init$n() { - SYSTEM_DEFAULT_ZONE_ID_INSTANCE = new SystemDefaultZoneId(); - ZoneId.systemDefault = ZoneIdFactory.systemDefault; - ZoneId.getAvailableZoneIds = ZoneIdFactory.getAvailableZoneIds; - ZoneId.of = ZoneIdFactory.of; - ZoneId.ofOffset = ZoneIdFactory.ofOffset; - ZoneId.from = ZoneIdFactory.from; - ZoneOffset.from = ZoneIdFactory.from; - ZoneId.SYSTEM = SYSTEM_DEFAULT_ZONE_ID_INSTANCE; - ZoneId.UTC = ZoneOffset.ofTotalSeconds(0); - } +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var isInit = false; +/***/ }), - function init() { - if (isInit) { - return; - } +/***/ 85209: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - isInit = true; - _init$1(); - _init(); - _init$2(); - _init$3(); - _init$k(); - _init$8(); - _init$m(); - _init$4(); - _init$l(); - _init$i(); - _init$j(); - _init$d(); - _init$5(); - _init$c(); - _init$b(); - _init$6(); - _init$7(); - _init$g(); - _init$n(); - _init$e(); - _init$a(); - _init$9(); - _init$h(); - _init$f(); - } - - init(); +"use strict"; +// 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. - /* - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - - var ToNativeJsConverter = function () { - function ToNativeJsConverter(temporal, zone) { - var zonedDateTime; - - if (temporal instanceof LocalDate) { - zone = zone == null ? ZoneId.systemDefault() : zone; - zonedDateTime = temporal.atStartOfDay(zone); - } else if (temporal instanceof LocalDateTime) { - zone = zone == null ? ZoneId.systemDefault() : zone; - zonedDateTime = temporal.atZone(zone); - } else if (temporal instanceof ZonedDateTime) { - if (zone == null) { - zonedDateTime = temporal; - } else { - zonedDateTime = temporal.withZoneSameInstant(zone); - } - } else { - throw new IllegalArgumentException('unsupported instance for convert operation:' + temporal); - } - this.instant = zonedDateTime.toInstant(); - } +module.exports = Readable; +/**/ - var _proto = ToNativeJsConverter.prototype; +var Duplex; +/**/ - _proto.toDate = function toDate() { - return new Date(this.instant.toEpochMilli()); - }; +Readable.ReadableState = ReadableState; +/**/ - _proto.toEpochMilli = function toEpochMilli() { - return this.instant.toEpochMilli(); - }; +var EE = __nccwpck_require__(28614).EventEmitter; + +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ + + +var Stream = __nccwpck_require__(36238); +/**/ + + +var Buffer = __nccwpck_require__(64293).Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + + +var debugUtil = __nccwpck_require__(31669); + +var debug; + +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + + +var BufferList = __nccwpck_require__(70662); + +var destroyImpl = __nccwpck_require__(36994); + +var _require = __nccwpck_require__(3533), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; + +__nccwpck_require__(44124)(Readable, Stream); + +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(13928); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - return ToNativeJsConverter; - }(); + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = __nccwpck_require__(94841)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __nccwpck_require__(13928); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} - function convert(temporal, zone) { - return new ToNativeJsConverter(temporal, zone); +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; } - var NativeJsTemporal = function (_TemporalAccessor) { - _inheritsLoose(NativeJsTemporal, _TemporalAccessor); + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - function NativeJsTemporal(date, zone) { - var _this; - if (zone === void 0) { - zone = ZoneId.systemDefault(); - } + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; + +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. - _this = _TemporalAccessor.call(this) || this; - _this._zone = zone; - if (date instanceof Date) { - _this._epochMilli = date.getTime(); - return _assertThisInitialized(_this); - } else if (typeof date.toDate === 'function' && date.toDate() instanceof Date) { - _this._epochMilli = date.toDate().getTime(); - return _assertThisInitialized(_this); - } +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; - assert(false, 'date must be either a javascript date or a moment'); - return _this; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; } - var _proto = NativeJsTemporal.prototype; + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } - _proto.query = function query(_query) { - requireNonNull(_query, 'query'); + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() - if (_query === TemporalQueries.localDate()) { - return LocalDate.ofInstant(Instant.ofEpochMilli(this._epochMilli), this._zone); - } else if (_query === TemporalQueries.localTime()) { - return LocalTime.ofInstant(Instant.ofEpochMilli(this._epochMilli), this._zone); - } else if (_query === TemporalQueries.zone()) { - return this._zone; - } - return _TemporalAccessor.prototype.query.call(this, _query); - }; +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; - _proto.get = function get(field) { - return this.getLong(field); - }; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; - _proto.getLong = function getLong(field) { - requireNonNull(field, 'field'); + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (field instanceof ChronoField) { - switch (field) { - case ChronoField.NANO_OF_SECOND: - return MathUtil.floorMod(this._epochMilli, 1000) * 1000000; + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } - case ChronoField.INSTANT_SECONDS: - return MathUtil.floorDiv(this._epochMilli, 1000); - } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; - throw new UnsupportedTemporalTypeException('Unsupported field: ' + field); + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. - return field.getFrom(this); - }; - _proto.isSupported = function isSupported(field) { - return field === ChronoField.INSTANT_SECONDS || field === ChronoField.NANO_OF_SECOND; - }; + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} - return NativeJsTemporal; - }(TemporalAccessor); +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } - function nativeJs(date, zone) { - return new NativeJsTemporal(date, zone); - } + maybeReadMore(stream, state); +} - function bindUse(jsJoda) { - var used = []; - return function use(fn) { - if (!~used.indexOf(fn)) { - fn(jsJoda); - used.push(fn); - } +function chunkInvalid(state, chunk) { + var er; - return jsJoda; - }; - } + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } - /** - * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper - * @license BSD-3-Clause (see LICENSE in the root directory of this source tree) - */ - var _ = { - assert: assert$1, - DateTimeBuilder: DateTimeBuilder, - DateTimeParseContext: DateTimeParseContext, - DateTimePrintContext: DateTimePrintContext, - MathUtil: MathUtil, - StringUtil: StringUtil, - StringBuilder: StringBuilder - }; - var jsJodaExports = { - _: _, - convert: convert, - nativeJs: nativeJs, - ArithmeticException: ArithmeticException, - DateTimeException: DateTimeException, - DateTimeParseException: DateTimeParseException, - IllegalArgumentException: IllegalArgumentException, - IllegalStateException: IllegalStateException, - UnsupportedTemporalTypeException: UnsupportedTemporalTypeException, - NullPointerException: NullPointerException, - Clock: Clock, - DayOfWeek: DayOfWeek, - Duration: Duration, - Instant: Instant, - LocalDate: LocalDate, - LocalTime: LocalTime, - LocalDateTime: LocalDateTime, - OffsetTime: OffsetTime, - OffsetDateTime: OffsetDateTime, - Month: Month, - MonthDay: MonthDay, - Period: Period, - Year: Year, - YearConstants: YearConstants, - YearMonth: YearMonth, - ZonedDateTime: ZonedDateTime, - ZoneOffset: ZoneOffset, - ZoneId: ZoneId, - ZoneRegion: ZoneRegion, - ZoneOffsetTransition: ZoneOffsetTransition, - ZoneRules: ZoneRules, - ZoneRulesProvider: ZoneRulesProvider, - ChronoLocalDate: ChronoLocalDate, - ChronoLocalDateTime: ChronoLocalDateTime, - ChronoZonedDateTime: ChronoZonedDateTime, - IsoChronology: IsoChronology, - ChronoField: ChronoField, - ChronoUnit: ChronoUnit, - IsoFields: IsoFields, - Temporal: Temporal, - TemporalAccessor: TemporalAccessor, - TemporalAdjuster: TemporalAdjuster, - TemporalAdjusters: TemporalAdjusters, - TemporalAmount: TemporalAmount, - TemporalField: TemporalField, - TemporalQueries: TemporalQueries, - TemporalQuery: TemporalQuery, - TemporalUnit: TemporalUnit, - ValueRange: ValueRange, - DateTimeFormatter: DateTimeFormatter, - DateTimeFormatterBuilder: DateTimeFormatterBuilder, - DecimalStyle: DecimalStyle, - ResolverStyle: ResolverStyle, - SignStyle: SignStyle, - TextStyle: TextStyle - }; - var use = bindUse(jsJodaExports); - jsJodaExports.use = use; - - exports.ArithmeticException = ArithmeticException; - exports.ChronoField = ChronoField; - exports.ChronoLocalDate = ChronoLocalDate; - exports.ChronoLocalDateTime = ChronoLocalDateTime; - exports.ChronoUnit = ChronoUnit; - exports.ChronoZonedDateTime = ChronoZonedDateTime; - exports.Clock = Clock; - exports.DateTimeException = DateTimeException; - exports.DateTimeFormatter = DateTimeFormatter; - exports.DateTimeFormatterBuilder = DateTimeFormatterBuilder; - exports.DateTimeParseException = DateTimeParseException; - exports.DayOfWeek = DayOfWeek; - exports.DecimalStyle = DecimalStyle; - exports.Duration = Duration; - exports.IllegalArgumentException = IllegalArgumentException; - exports.IllegalStateException = IllegalStateException; - exports.Instant = Instant; - exports.IsoChronology = IsoChronology; - exports.IsoFields = IsoFields; - exports.LocalDate = LocalDate; - exports.LocalDateTime = LocalDateTime; - exports.LocalTime = LocalTime; - exports.Month = Month; - exports.MonthDay = MonthDay; - exports.NullPointerException = NullPointerException; - exports.OffsetDateTime = OffsetDateTime; - exports.OffsetTime = OffsetTime; - exports.Period = Period; - exports.ResolverStyle = ResolverStyle; - exports.SignStyle = SignStyle; - exports.Temporal = Temporal; - exports.TemporalAccessor = TemporalAccessor; - exports.TemporalAdjuster = TemporalAdjuster; - exports.TemporalAdjusters = TemporalAdjusters; - exports.TemporalAmount = TemporalAmount; - exports.TemporalField = TemporalField; - exports.TemporalQueries = TemporalQueries; - exports.TemporalQuery = TemporalQuery; - exports.TemporalUnit = TemporalUnit; - exports.TextStyle = TextStyle; - exports.UnsupportedTemporalTypeException = UnsupportedTemporalTypeException; - exports.ValueRange = ValueRange; - exports.Year = Year; - exports.YearConstants = YearConstants; - exports.YearMonth = YearMonth; - exports.ZoneId = ZoneId; - exports.ZoneOffset = ZoneOffset; - exports.ZoneOffsetTransition = ZoneOffsetTransition; - exports.ZoneRegion = ZoneRegion; - exports.ZoneRules = ZoneRules; - exports.ZoneRulesProvider = ZoneRulesProvider; - exports.ZonedDateTime = ZonedDateTime; - exports._ = _; - exports.convert = convert; - exports.nativeJs = nativeJs; - exports.use = use; + return er; +} - Object.defineProperty(exports, '__esModule', { value: true }); +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. -}))); -//# sourceMappingURL=js-joda.js.map +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __nccwpck_require__(94841)/* .StringDecoder */ .s; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 -/***/ }), + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: -/***/ 31736: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var p = this._readableState.buffer.head; + var content = ''; -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseSqlConnectionString = exports.parseConnectionString = void 0; -const connection_string_1 = __nccwpck_require__(51226); -exports.parseConnectionString = connection_string_1.default; -const sql_connection_string_1 = __nccwpck_require__(25055); -exports.parseSqlConnectionString = sql_connection_string_1.default; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); -/***/ }), + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB -/***/ 51226: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var CollectionMode; -(function (CollectionMode) { - CollectionMode[CollectionMode["key"] = 0] = "key"; - CollectionMode[CollectionMode["value"] = 1] = "value"; -})(CollectionMode || (CollectionMode = {})); -const CONFIG = Object.freeze({ - key: { - terminator: '=', - quotes: {}, - }, - value: { - terminator: ';', - quotes: { - '"': '"', - "'": "'", - '{': '}', - }, - }, -}); -function connectionStringParser(connectionString, parserConfig = CONFIG) { - const parsed = {}; - let collectionMode = CollectionMode.key; - let started = false; - let finished = false; - let quoted = false; - let quote = ''; - let buffer = ''; - let currentKey = ''; - let pointer = 0; - function start() { - started = true; - } - function finish() { - finished = true; - } - function reset() { - started = false; - finished = false; - quoted = false; - quote = ''; - buffer = ''; - } - function config() { - return collectionMode === CollectionMode.key ? parserConfig.key : parserConfig.value; - } - function isTerminator(char) { - return config().terminator === char; - } - function isStartQuote(char) { - return Object.keys(config().quotes).some((val) => char === val); - } - function isEndQuote(char) { - return quoted && char === config().quotes[quote]; - } - function push(char) { - buffer += char; - } - function collect() { - if (!quoted) { - buffer = buffer.trim(); - } - switch (collectionMode) { - case CollectionMode.key: - currentKey = buffer.toLowerCase(); - collectionMode = CollectionMode.value; - break; - case CollectionMode.value: - collectionMode = CollectionMode.key; - parsed[currentKey] = buffer; - currentKey = ''; - break; - } - reset(); - } - while (pointer < connectionString.length) { - const current = connectionString.charAt(pointer); - if (!finished) { - if (!started) { - if (current.trim()) { - start(); - if (isStartQuote(current)) { - quoted = true; - quote = current; - } - else { - push(current); - } - } - } - else { - if (quoted && isEndQuote(current)) { - const next = connectionString.charAt(pointer + 1); - if (current === next) { - push(current); - pointer++; - } - else { - finish(); - } - } - else if (!quoted && isTerminator(current)) { - const next = connectionString.charAt(pointer + 1); - if (current === next) { - push(current); - pointer++; - } - else { - collect(); - } - } - else { - push(current); - } - } - } - else if (isTerminator(current)) { - collect(); - } - else if (current.trim()) { - throw new Error('Malformed connection string'); - } - pointer++; - } - if (quoted && !finished) { - throw new Error('Connection string terminated unexpectedly'); - } - else { - collect(); - } - return parsed; -} -exports.default = connectionStringParser; +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } -/***/ }), + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. -/***/ 25055: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SCHEMA = exports.SchemaTypes = void 0; -const connection_string_1 = __nccwpck_require__(51226); -var SchemaTypes; -(function (SchemaTypes) { - SchemaTypes[SchemaTypes["BOOL"] = 0] = "BOOL"; - SchemaTypes[SchemaTypes["STRING"] = 1] = "STRING"; - SchemaTypes[SchemaTypes["NUMBER"] = 2] = "NUMBER"; -})(SchemaTypes = exports.SchemaTypes || (exports.SchemaTypes = {})); -// schema for MSSQL connection strings (https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.connectionstring) -exports.SCHEMA = { - 'Application Name': { - type: SchemaTypes.STRING, - aliases: ['App'], - validator(val) { - return val.length <= 128; - }, - }, - 'ApplicationIntent': { - type: SchemaTypes.STRING, - allowedValues: ['ReadOnly', 'ReadWrite'], - default: 'ReadWrite', - }, - 'Asynchronous Processing': { - type: SchemaTypes.BOOL, - default: false, - aliases: ['Async'], - }, - 'AttachDBFilename': { - type: SchemaTypes.STRING, - aliases: ['Extended Properties', 'Initial File Name'], - }, - 'Authentication': { - type: SchemaTypes.STRING, - allowedValues: ['Active Directory Integrated', 'Active Directory Password', 'Sql Password'], - }, - 'Column Encryption Setting': { - type: SchemaTypes.STRING, - }, - 'Connection Timeout': { - type: SchemaTypes.NUMBER, - aliases: ['Connect Timeout', 'Timeout'], - default: 15, - }, - 'Connection Lifetime': { - type: SchemaTypes.NUMBER, - aliases: ['Load Balance Timeout'], - default: 0, - }, - 'ConnectRetryCount': { - type: SchemaTypes.NUMBER, - default: 1, - validator(val) { - return val > 0 && val <= 255; - }, - }, - 'ConnectRetryInterval': { - type: SchemaTypes.NUMBER, - default: 10, - }, - 'Context Connection': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Current Language': { - aliases: ['Language'], - type: SchemaTypes.STRING, - validator(val) { - return val.length <= 128; - }, - }, - 'Data Source': { - aliases: ['Addr', 'Address', 'Server', 'Network Address'], - type: SchemaTypes.STRING, - }, - 'Encrypt': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Enlist': { - type: SchemaTypes.BOOL, - default: true, - }, - 'Failover Partner': { - type: SchemaTypes.STRING, - }, - 'Initial Catalog': { - type: SchemaTypes.STRING, - aliases: ['Database'], - validator(val) { - return val.length <= 128; - }, - }, - 'Integrated Security': { - type: SchemaTypes.BOOL, - aliases: ['Trusted_Connection'], - coerce(val) { - return val === 'sspi' || null; - }, - }, - 'Max Pool Size': { - type: SchemaTypes.NUMBER, - default: 100, - validator(val) { - return val >= 1; - }, - }, - 'Min Pool Size': { - type: SchemaTypes.NUMBER, - default: 0, - validator(val) { - return val >= 0; - }, - }, - 'MultipleActiveResultSets': { - type: SchemaTypes.BOOL, - default: false, - }, - 'MultiSubnetFailover': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Network Library': { - type: SchemaTypes.STRING, - aliases: ['Network', 'Net'], - allowedValues: ['dbnmpntw', 'dbmsrpcn', 'dbmsadsn', 'dbmsgnet', 'dbmslpcn', 'dbmsspxn', 'dbmssocn', 'Dbmsvinn'], - }, - 'Packet Size': { - type: SchemaTypes.NUMBER, - default: 8000, - validator(val) { - return val >= 512 && val <= 32768; - }, - }, - 'Password': { - type: SchemaTypes.STRING, - aliases: ['PWD'], - validator(val) { - return val.length <= 128; - }, - }, - 'Persist Security Info': { - type: SchemaTypes.BOOL, - aliases: ['PersistSecurityInfo'], - default: false, - }, - 'PoolBlockingPeriod': { - type: SchemaTypes.NUMBER, - default: 0, - coerce(val) { - switch (val.toLowerCase()) { - case 'alwaysblock': - return 1; - case 'auto': - return 0; - case 'neverblock': - return 2; - } - return null; - }, - }, - 'Pooling': { - type: SchemaTypes.BOOL, - default: true, - }, - 'Replication': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Transaction Binding': { - type: SchemaTypes.STRING, - allowedValues: ['Implicit Unbind', 'Explicit Unbind'], - default: 'Implicit Unbind', - }, - 'TransparentNetworkIPResolution': { - type: SchemaTypes.BOOL, - default: true, - }, - 'TrustServerCertificate': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Type System Version': { - type: SchemaTypes.STRING, - allowedValues: ['SQL Server 2012', 'SQL Server 2008', 'SQL Server 2005', 'Latest'], - }, - 'User ID': { - type: SchemaTypes.STRING, - aliases: ['UID'], - validator(val) { - return val.length <= 128; - }, - }, - 'User Instance': { - type: SchemaTypes.BOOL, - default: false, - }, - 'Workstation ID': { - type: SchemaTypes.STRING, - aliases: ['WSID'], - validator(val) { - return val.length <= 128; - }, - }, -}; -function guessType(value) { - if (value.trim() === '') { - return SchemaTypes.STRING; - } - if (!Number.isNaN(parseInt(value, 10))) { - return SchemaTypes.NUMBER; - } - if (['true', 'false', 'yes', 'no'].includes(value.toLowerCase())) { - return SchemaTypes.BOOL; - } - return SchemaTypes.STRING; -} -function coerce(value, type, coercer) { - if (coercer) { - const coerced = coercer(value); - if (coerced !== null) { - return coerced; - } - } - switch (type) { - case SchemaTypes.BOOL: - if (['true', 'yes', '1'].includes(value.toLowerCase())) { - return true; - } - if (['false', 'no', '0'].includes(value.toLowerCase())) { - return false; - } - return value; - case SchemaTypes.NUMBER: - return parseInt(value, 10); - } - return value; -} -function validate(value, allowedValues, validator) { - let valid = true; - if (validator) { - valid = validator(value); - } - if (valid) { - valid = (allowedValues === null || allowedValues === void 0 ? void 0 : allowedValues.includes(value)) || false; - } - return valid; -} -function parseSqlConnectionString(connectionString, canonicalProps = false, allowUnknown = false, strict = false, schema = exports.SCHEMA) { - const flattenedSchema = Object.entries(schema).reduce((flattened, [key, item]) => { - var _a; - Object.assign(flattened, { - [key.toLowerCase()]: item, - }); - return ((_a = item.aliases) === null || _a === void 0 ? void 0 : _a.reduce((accum, alias) => { - return Object.assign(accum, { - [alias.toLowerCase()]: { - ...item, - canonical: key.toLowerCase(), - }, - }); - }, flattened)) || flattened; - }, {}); - return Object.entries(connection_string_1.default(connectionString)).reduce((config, [prop, value]) => { - if (!Object.prototype.hasOwnProperty.call(flattenedSchema, prop)) { - return Object.assign(config, { - [prop]: coerce(value, guessType(value)), - }); - } - let coercedValue = coerce(value, flattenedSchema[prop].type, flattenedSchema[prop].coerce); - if (strict && !validate(coercedValue, flattenedSchema[prop].allowedValues, flattenedSchema[prop].validator)) { - coercedValue = flattenedSchema[prop].default; - } - const propName = canonicalProps ? flattenedSchema[prop].canonical || prop : prop; - return Object.assign(config, { - [propName]: coercedValue, - }); - }, {}); -} -exports.default = parseSqlConnectionString; +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. -/***/ }), -/***/ 48566: -/***/ ((module, exports) => { + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough -module.exports = exports = abbrev.abbrev = abbrev + if (!state.ended) { + state.needReadable = true; + return 0; + } -abbrev.monkeyPatch = monkeyPatch + return state.length; +} // you can override either this method, or the async _read(n) below. -function monkeyPatch () { - Object.defineProperty(Array.prototype, 'abbrev', { - value: function () { return abbrev(this) }, - enumerable: false, configurable: true, writable: true - }) - Object.defineProperty(Object.prototype, 'abbrev', { - value: function () { return abbrev(Object.keys(this)) }, - enumerable: false, configurable: true, writable: true - }) -} +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. -function abbrev (list) { - if (arguments.length !== 1 || !Array.isArray(list)) { - list = Array.prototype.slice.call(arguments, 0) + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; } - for (var i = 0, l = list.length, args = [] ; i < l ; i ++) { - args[i] = typeof list[i] === "string" ? list[i] : String(list[i]) + + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); } - // sort them lexicographically, so that they're next to their nearest kin - args = args.sort(lexSort) + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - // walk through each, seeing how much it has in common with the next and previous - var abbrevs = {} - , prev = "" - for (var i = 0, l = args.length ; i < l ; i ++) { - var current = args[i] - , next = args[i + 1] || "" - , nextMatches = true - , prevMatches = true - if (current === next) continue - for (var j = 0, cl = current.length ; j < cl ; j ++) { - var curChar = current.charAt(j) - nextMatches = nextMatches && curChar === next.charAt(j) - prevMatches = prevMatches && curChar === prev.charAt(j) - if (!nextMatches && !prevMatches) { - j ++ - break - } - } - prev = current - if (j === cl) { - abbrevs[current] = current - continue + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; +}; + +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } - for (var a = current.substr(0, j) ; j <= cl ; j ++) { - abbrevs[a] = current - a += current.charAt(j) + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); } } - return abbrevs +} // Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. + + +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } } -function lexSort (a, b) { - return a === b ? 0 : a > b ? 1 : -1 +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. + + +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } } +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } -/***/ }), + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. -/***/ 35894: -/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var _ = __nccwpck_require__(83571); - -var ac = __nccwpck_require__(69775); -var authParams = __nccwpck_require__(74854); -var logging = __nccwpck_require__(92288); -var MemoryCache = __nccwpck_require__(92474); - -exports = {}; - -exports.Logging = logging.Logging; -exports.AuthenticationContext = ac.AuthenticationContext; -exports.setGlobalADALOptions = ac.setGlobalADALOptions; -exports.getGlobalADALOptions = ac.getGlobalADALOptions; -exports.MemoryCache = MemoryCache; -_.extend(exports, authParams); - -/** - * Creates a new AuthenticationContext object. By default the authority will be checked against - * a list of known Azure Active Directory authorities. If the authority is not recognized as - * one of these well known authorities then token acquisition will fail. This behavior can be - * turned off via the validateAuthority parameter below. - * @function - * @param {string} authority A URL that identifies a token authority. - * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true. - * @returns {AuthenticationContext} A new authentication context. - */ -exports.createAuthenticationContext = function(authority, validateAuthority) { - return new ac.AuthenticationContext(authority, validateAuthority); -}; - -module.exports = exports; +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; -/***/ }), + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; -/***/ 62432: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + case 1: + state.pipes = [state.pipes, dest]; + break; -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var _ = __nccwpck_require__(83571); -var constants = __nccwpck_require__(10282); - -var UserCodeResponseFields = constants.UserCodeResponseFields; - -var argumentValidation = { - /** - * Throws if the passed in parameter is not a string. - * @param {string} param The parameter to validate. - * @param {string} name The name of the parameter being validated. - * @throws {Error} If the parameter is not a valid string. - */ - validateStringParameter : function(param, name) { - if (!param) { - throw new Error('The ' + name + ' parameter is required.'); - } - if (!_.isString(param)) { - throw new Error('The ' + name + ' parameter must be of type String.'); - } - }, - - /** - * Validates that the callback passed in {@link AuthenticationContext.acquireToken} is a function - * @param {AcquireTokenCallback} callback - * @throws {Error} If the callback parameter is not a function - */ - validateCallbackType : function(callback) { - if (!callback || !_.isFunction(callback)) { - throw new Error('acquireToken requires a function callback parameter.'); - } - }, - - validateUserCodeInfo : function(userCodeInfo) { - if (!userCodeInfo){ - throw new Error('The userCodeInfo parameter is required'); - } - - if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.DEVICE_CODE)){ - throw new Error('The userCodeInfo is missing device_code'); - } - - if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.INTERVAL)){ - throw new Error('The userCodeInfo is missing interval'); - } - - if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.EXPIRES_IN)){ - throw new Error('The userCodeInfo is missing expires_in'); - } - } -}; - -module.exports = argumentValidation; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); -/***/ }), + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); -/***/ 69775: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var argument = __nccwpck_require__(62432); -var Authority = __nccwpck_require__(19270)/* .Authority */ .W; -var TokenRequest = __nccwpck_require__(21178); -var CodeRequest = __nccwpck_require__(66576); -var createLogContext = __nccwpck_require__(92288).createLogContext; -var MemoryCache = __nccwpck_require__(92474); -var util = __nccwpck_require__(5336); -var constants = __nccwpck_require__(10282); - -var globalADALOptions = {}; -var globalCache = new MemoryCache(); - - -/** - * This function is used to add or remove entries from a TokenCache - * @typedef {function} ModifyCacheFunction - * @param {Array} entries An array of entries to either add or remove from the TokenCache - * @param {function} callback A callback function to call when the add or remove operation is complete. - * This function can take a single error argument. - */ - -/** - * This function is called by a TokenCache when a find operation completes. - * @callback TokenCacheFindCallback - * @param {Error} [err] If an error occurred during the find operation then it should be passed here. - * @param {Array} [entries] If the find operation was succesful then the matched entries should be returned here. - */ - -/** - * This function is called by ADAL to query a TokenCache. The query parameter is - * a flat object which must be compared against entries in the cache. An entry - * matches if it has all of the fields in the query and the values of those fields match - * the values in the query. A matched object may have more fields than the query object. - * @typedef {function} FindCacheFunction - * @param {object} query This object should be compared to cache entries and matches should be returned. - * @param {TokenCacheFindCallback} callback This callback should be called when the find operation is complete. - */ - -/** - * This is an interface that can be implemented to provide custom token cache persistence. - * @public - * @class TokenCache - * @property {ModifyCacheFunction} add Called by ADAL when entries should be added to the cache. - * @property {ModifyCacheFunction} remove Called by ADAL when entries should be removed from the cache. - * @property {FindCacheFunction} find Called when ADAL needs to find entries in the cache. - */ - - -/** - * Creates a new AuthenticationContext object. By default the authority will be checked against - * a list of known Azure Active Directory authorities. If the authority is not recognized as - * one of these well known authorities then token acquisition will fail. This behavior can be - * turned off via the validateAuthority parameter below. - * @constructor - * @param {string} authority A URL that identifies a token authority. - * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true. - * @param {TokenCache} [cache] Sets the token cache used by this AuthenticationContext instance. If this parameter is not set - * then a default, in memory cache is used. The default in memory cache is global to the process and is - * shared by all AuthenticationContexts that are created with an empty cache parameter. To control the - * scope and lifetime of a cache you can either create a {@link MemoryCache} instance and pass it when - * constructing an AuthenticationContext or implement a custom {@link TokenCache} and pass that. Cache - * instances passed at AuthenticationContext construction time are only used by that instance of - * the AuthenticationContext and are not shared unless it has been manually passed during the - * construction of other AuthenticationContexts. - * - */ -function AuthenticationContext(authority, validateAuthority, cache, aadApiVersion) { - var validate = (validateAuthority === undefined || validateAuthority === null || validateAuthority); - - this._authority = new Authority(authority, validate); - this._authority.aadApiVersion = aadApiVersion; - this._oauth2client = null; - this._correlationId = null; - this._callContext = { options : globalADALOptions }; - this._cache = cache || globalCache; - this._tokenRequestWithUserCode = {}; -} - -/** - * Gets the authority url this AuthenticationContext was constructed with. - * @instance - * @memberOf AuthenticationContext - * @type {string} - * @name authority - */ -Object.defineProperty(AuthenticationContext.prototype, 'authority', { - get: function () { - return this._authority.url; - } -}); - -/** - * Gets/Sets the correlation id that will be used for the next acquireToken request. - * @instance - * @memberOf AuthenticationContext - * @type {string} - * @name correlationId - */ -Object.defineProperty(AuthenticationContext.prototype, 'correlationId', { - get: function () { - return this._correlationId; - }, - set: function (id) { - this._correlationId = id; - } -}); - -/** - * Get/Sets options that are applied to requests generated by this AuthenticationContext instance. - * @instance - * @memberOf AuthenticationContext - * @type {object} - * @name options - */ -Object.defineProperty(AuthenticationContext.prototype, 'options', { - get: function() { - return this._callContext.options; - }, - set: function (value) { - this._callContext.options = value; - } -}); - -/** - * Get the token cache used by this AuthenticationContext instance. - * @instance - * @memberOf AuthenticationContext - * @type {object} - * @name cache - */ -Object.defineProperty(AuthenticationContext.prototype, 'cache', { - get: function() { - return this._cache; - }, -}); - -/** - * This will be returned in case the OAuth 2 service returns an error. - * @typedef ErrorResponse - * @property {string} [error] A server error. - * @property {string} [errorDescription] A description of the error returned. - */ - -/** - * Contains tokens and metadata upon successful completion of an acquireToken call. - * @typedef TokenResponse - * @property {string} tokenType The type of token returned. - * @property {string} accessToken The returned access token. - * @property {string} [refreshToken] A refresh token. - * @property {Date} [createdOn] The date on which the access token was created. - * @property {Date} expiresOn The Date on which the access token expires. - * @property {int} expiresIn The amount of time, in seconds, for which the token is valid. - * @property {string} [userId] An id for the user. May be a displayable value if is_user_id_displayable is true. - * @property {bool} [isUserIdDisplayable] Indicates whether the user_id property will be meaningful if displayed to a user. - * @property {string} [tenantId] The identifier of the tenant under which the access token was issued. - * @property {string} [givenName] The given name of the principal represented by the access token. - * @property {string} [familyName] The family name of the principal represented by the access token. - * @property {string} [identityProvider] Identifies the identity provider that issued the access token. - */ - -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback AcquireTokenCallback - * @param {Error} [error] If the request fails this parameter will contain an Error object. - * @param {TokenResponse|ErrorResponse} [response] On a succesful request returns a {@link TokenResposne}. - */ - -/** - * This function implements code that is common to all acquireToken flows. - * @private - * @param {AcquireTokenCallback} callback - * @param {Function} tokenFunction This is the function to call to actually acquire the token after common flow has completed. - */ -AuthenticationContext.prototype._acquireToken = function(callback, tokenFunction) { - var self = this; - this._callContext._logContext = createLogContext(this.correlationId); - this._authority.validate(this._callContext, function(err) { - if (err) { - callback(err); - return; - } - tokenFunction.call(self); - }); -}; - -AuthenticationContext.prototype._acquireUserCode = function (callback, codeFunction) { - var self = this; - this._callContext._logContext = createLogContext(this.correlationId); - this._authority.validate(this._callContext, function (err) { - if (err) { - callback(err); - return; - } - - codeFunction.call(self); - }); -}; - -/** - * Gets a token for a given resource. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} [userId] The username of the user on behalf this application is authenticating. - * @param {string} [clientId] The OAuth client id of the calling application. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireToken = function(resource, userId, clientId, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(clientId, 'clientId'); - } catch(err) { - callback(err); - return; - } - - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); - tokenRequest.getTokenFromCacheWithRefresh(userId, callback); - }); -}; - -/** - * Gets a token for a given resource. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} username The username of the user on behalf this application is authenticating. - * @param {string} password The password of the user named in the username parameter. - * @param {string} clientId The OAuth client id of the calling application. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithUsernamePassword = function(resource, username, password, clientId, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(username, 'username'); - argument.validateStringParameter(password, 'password'); - argument.validateStringParameter(clientId, 'clientId'); - } catch(err) { - callback(err); - return; - } - - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); - tokenRequest.getTokenWithUsernamePassword(username, password, callback); - }); -}; - -/** - * Gets a token for a given resource. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} clientSecret The OAuth client secret of the calling application. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithClientCredentials = function(resource, clientId, clientSecret, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(clientId, 'clientId'); - argument.validateStringParameter(clientSecret, 'clientSecret'); - } catch (err) { - callback(err); - return; - } - - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); - tokenRequest.getTokenWithClientCredentials(clientSecret, callback); - }); -}; - -/** - * Gets a token for a given resource. - * @param {string} authorizationCode An authorization code returned from a client. - * @param {string} redirectUri The redirect uri that was used in the authorize call. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} clientSecret The OAuth client secret of the calling application. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithAuthorizationCode = function(authorizationCode, redirectUri, resource, clientId, clientSecret, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(authorizationCode, 'authorizationCode'); - argument.validateStringParameter(redirectUri, 'redirectUri'); - argument.validateStringParameter(clientId, 'clientId'); - } catch(err) { - callback(err); - return; - } - - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, redirectUri); - tokenRequest.getTokenWithAuthorizationCode(authorizationCode, clientSecret, callback); - }); -}; - -/** - * Gets a new access token via a previously issued refresh token. - * @param {string} refreshToken A refresh token returned in a tokne response from a previous invocation of acquireToken. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} [clientSecret] The OAuth client secret of the calling application. (Note: this parameter is a late addition. - * This parameter may be ommitted entirely so that applications built before this change will continue - * to work unchanged.) - * @param {string} resource The OAuth resource for which a token is being request. This parameter is optional and can be set to null. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithRefreshToken = function(refreshToken, clientId, clientSecret, resource, callback) { - // Fix up the arguments. Older clients may pass fewer arguments as the clientSecret paramter did not always exist. - // The code needs to make adjustments for those clients. - var clientSecretPresent = (5 === arguments.length); - var actualClientSecret = clientSecretPresent ? clientSecret : null; - var actualCallback = clientSecretPresent ? arguments[4] : arguments[3]; - var actualResource = clientSecretPresent ? arguments[3] : arguments[2]; - - argument.validateCallbackType(actualCallback); - try { - argument.validateStringParameter(refreshToken, 'refreshToken'); - argument.validateStringParameter(clientId, 'clientId'); - } catch(err) { - callback(err); - return; - } - - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, actualResource); - tokenRequest.getTokenWithRefreshToken(refreshToken, actualClientSecret, actualCallback); - }); -}; - -/** - * Gets a new access token using via a certificate credential. - * @param {string} resource A URI that identifies the resource for which the token is valid. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint A hex encoded thumbprint of the certificate. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithClientCertificate = function(resource, clientId, certificate, thumbprint, callback) { - argument.validateCallbackType(callback); - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(certificate, 'certificate'); - argument.validateStringParameter(thumbprint, 'thumbprint'); - } catch(err) { - callback(err); - return; - } - - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource); - tokenRequest.getTokenWithCertificate(certificate, thumbprint, callback); - }); -}; - -/** - * Gets the userCodeInfo which contains user_code, device_code for authenticating user on device. - * @param {string} resource A URI that identifies the resource for which the device_code and user_code is valid for. - * @param {string} clientId The OAuth client id of the calling application. - * @param {string} language The language code specifying how the message should be localized to. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireUserCode = function(resource, clientId, language, callback) { - argument.validateCallbackType(callback); - - try { - argument.validateStringParameter(resource, 'resource'); - argument.validateStringParameter(clientId, 'clientId'); - } catch (err) { - callback(err); - return; - } - - this._acquireUserCode(callback, function () { - var codeRequest = new CodeRequest(this._callContext, this, clientId, resource); - codeRequest.getUserCodeInfo(language, callback); - }); -}; - -/** - * Gets a new access token using via a device code. - * @note This method doesn't look up the cache, it only stores the returned token into cache. To look up cache before making a new request, - * please use acquireToken. - * @param {string} clientId The OAuth client id of the calling application. - * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.acquireTokenWithDeviceCode = function(resource, clientId, userCodeInfo, callback){ - argument.validateCallbackType(callback); - - try{ - argument.validateUserCodeInfo(userCodeInfo); - } catch (err) { - callback(err); - return; - } - - var self = this; - this._acquireToken(callback, function() { - var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, null); - self._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]] = tokenRequest; - tokenRequest.getTokenWithDeviceCode(userCodeInfo, callback); - }) -}; - -/** - * Cancels the polling request to get token with device code. - * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. - * @param {AcquireTokenCallback} callback The callback function. - */ -AuthenticationContext.prototype.cancelRequestToGetTokenWithDeviceCode = function (userCodeInfo, callback) { - argument.validateCallbackType(callback); - - try { - argument.validateUserCodeInfo(userCodeInfo); - } catch (err) { - callback(err); - return; - } - - if (!this._tokenRequestWithUserCode || !this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]) { - callback(new Error('No acquireTokenWithDeviceCodeRequest existed to be cancelled')); - return; - } - - var tokenRequestToBeCancelled = this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]; - tokenRequestToBeCancelled.cancelTokenRequestWithDeviceCode(); - - delete this._tokenRequestWithUserCode[constants.UserCodeResponseFields.DEVICE_CODE]; -}; - -var exports = { - AuthenticationContext : AuthenticationContext, - setGlobalADALOptions : function(options) { - globalADALOptions = options; - }, - getGlobalADALOptions : function() { - return globalADALOptions; - } -}; - -util.adalInit(); -module.exports = exports; + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. -/***/ }), + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; -/***/ 74854: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - - -var axios = __nccwpck_require__(96545); -var argument = __nccwpck_require__(62432); -var log = __nccwpck_require__(92288); -var util = __nccwpck_require__(5336); -var HttpErrorCode = __nccwpck_require__(10282).HttpError; - -/* - * Constants - */ -var consts = { - AUTHORIZATION_URI : 'authorization_uri', - RESOURCE : 'resource', - WWW_AUTHENTICATE_HEADER : 'www-authenticate' -}; - -/** - * The AuthenticationParameters class holds the parameters that are parsed from an OAuth challenge - * in the www-authenticate header. - * @constructor - * @param {string} authorizationUri The URI of an authority that can issues tokens for the - * resource that issued the challenge. - * @param {string} resource The resource for a which a token should be requested from the authority. - */ -function AuthenticationParameters(authorizationUri, resource) { - this._authorizationUri = authorizationUri; - this._resource = resource; -} - -/** - * The URI of an authority that can issues tokens for the resource that issued the challenge. - * @instance - * @memberOf AuthenticationParameters - * @type {string} - * @name authorizationUri - */ -Object.defineProperty(AuthenticationParameters.prototype, 'authorizationUri', { - get : function() { - return this._authorizationUri; - } -}); - -/** - * The resource for a which a token should be requested from the authority. - * This property may be undefined if the resource was not returned in the challenge. - * @instance - * @memberOf AuthenticationParameters - * @type {string} - * @name authorizationUri - */ -Object.defineProperty(AuthenticationParameters.prototype, 'resource', { - get : function() { - return this._resource; - } -}); - -var exports = {}; - -// The 401 challenge is a standard defined in RFC6750, which is based in part on RFC2617. -// The challenge has the following form. -// WWW-Authenticate : Bearer authorization_uri="https://login.windows.net/mytenant.com/oauth2/authorize",Resource_id="00000002-0000-0000-c000-000000000000" - -// This regex is used to validate the structure of the challenge header. -// Match whole structure: ^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$ -// ^ Start at the beginning of the string. -// \s*Bearer\s+ Match 'Bearer' surrounded by one or more amount of whitespace. -// ([^,\s="]+?) This cpatures the key which is composed of any characters except comma, whitespace or a quotes. -// = Match the = sign. -// "([^"]*?)" Captures the value can be any number of non quote characters. At this point only the first key value pair as been captured. -// \s* There can be any amount of white space after the first key value pair. -// ( Start a capture group to retrieve the rest of the key value pairs that are separated by commas. -// \s* There can be any amount of whitespace before the comma. -// , There must be a comma. -// \s* There can be any amount of whitespace after the comma. -// (([^,\s="]+?) This will capture the key that comes after the comma. It's made of a series of any character excpet comma, whitespace or quotes. -// = Match the equal sign between the key and value. -// " Match the opening quote of the value. -// ([^"]*?) This will capture the value which can be any number of non quote characters. -// " Match the values closing quote. -// \s* There can be any amount of whitespace before the next comma. -// )* Close the capture group for key value pairs. There can be any number of these. -// $ The rest of the string can be whitespace but nothing else up to the end of the string. -// -// -// In other some other languages the regex above would be all that was needed. However, in JavaScript the RegExp object does not -// return all of the captures in one go. So the regex above needs to be broken up so that captures can be retrieved -// iteratively. -// - -function parseChallenge(challenge) { - // This regex checks the structure of the whole challenge header. The complete - // header needs to be checked for validity before we can be certain that - // we will succeed in pulling out the individual parts. - var bearerChallengeStructureValidation = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$/; - - // This regex pulls out the key and value from the very first pair. - var firstKeyValuePairRegex = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*/; - - // This regex is used to pull out all of the key value pairs after the first one. - // All of these begin with a comma. - var allOtherKeyValuePairRegex = /(?:,\s*([^,\s="]+?)="([^"]*?)"\s*)/g; - - - if (!bearerChallengeStructureValidation.test(challenge)) { - throw new Error('The challenge is not parseable as an RFC6750 OAuth2 challenge'); - } - - var challengeParameters = {}; - for(var match = firstKeyValuePairRegex.exec(challenge); - match; - match = allOtherKeyValuePairRegex.exec(challenge)) { - - challengeParameters[match[1]] = match[2]; - } - - return challengeParameters; -} - -exports.AuthenticationParameters = AuthenticationParameters; - -/** - * Creates an {@link AuthenticationParameters} object from the contents of a - * www-authenticate header received from a HTTP 401 response from a resource server. - * @param {string} challenge The content fo the www-authenticate header. - * @return {AuthenticationParameters} An AuthenticationParameters object containing the parsed values from the header. - */ -exports.createAuthenticationParametersFromHeader = function(challenge) { - argument.validateStringParameter(challenge, 'challenge'); - - var challengeParameters = parseChallenge(challenge); - - var authorizationUri = challengeParameters[consts.AUTHORIZATION_URI]; - if (!authorizationUri) { - throw new Error('Could not find \'authorization_uri\' in challenge header.'); - } - - var resource = challengeParameters[consts.RESOURCE]; - - return new AuthenticationParameters(authorizationUri, resource); -}; - -/** - * Create an {@link AuthenticationParameters} object from a node http.IncomingMessage - * object that was created as a result of a request to a resource server. This function - * expects the response to contain a HTTP 401 error code with a www-authenticate - * header. - * @param {http.IncomingMessage} response A response from a http request to a resource server. - * @return {AuthenticationParameters} - */ -exports.createAuthenticationParametersFromResponse = function(response) { - if (!response) { - throw new Error('Mising required parameter: response'); - } - - if (!response.status) { - throw new Error('The response parameter does not have the expected HTTP status field'); - } - - if (HttpErrorCode.UNAUTHORIZED !== response.status) { - throw new Error('The response status code does not correspond to an OAuth challenge. ' + - 'The status is expected to be 401 but is: ' + response.status); - } - - if (!response.headers) { - throw new Error('There were no headers found in the response.'); - } - - var challenge = response.headers[consts.WWW_AUTHENTICATE_HEADER]; - if (!challenge) { - throw new Error('The response does not contain a WWW-Authenticate header that can be used to determine the authority_uri and resource.'); - } - - return exports.createAuthenticationParametersFromHeader(challenge); -}; - -function validateUrlObject(url) { - if (!url || !url.href) { - throw new Error('Parameter is of wrong type: url'); - } -} - -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback CreateAuthenticationParametersCallback - * @memberOf AuthenticationContext - * @param {Error} [error] If the request fails this parameter will contain an Error object. - * @param {AuthenticationParameters} [parameters] On a succesful request returns a {@link AuthenticationParameters}. - */ - -/** - * Creates an {@link AuthenticationParameters} object by sending a get request - * to the url passed to this function, and parsing the resulting http 401 - * response. - * @param {string|url} url The url of a resource server. - * @param {AuthenticationParameters} callback Called on error or request completion. - * @param {string} [correlationId] An optional correlationId to pass along with the request and to include in any logs. - */ -exports.createAuthenticationParametersFromUrl = function(url, callback, correlationId) { - argument.validateCallbackType(callback); - try { - if (!url) { - callback(new Error('Missing required parameter: url')); - return; - } - var challengeUrl; - if ('string' === typeof(url)) { - challengeUrl = url; - } else { - validateUrlObject(url); - challengeUrl = url.href; - } - - var logContext = log.createLogContext(correlationId); - var logger = new log.Logger('AuthenticationParameters', logContext); - - logger.verbose('Attempting to retrieve authentication parameters'); - logger.verbose('Attempting to retrieve authentication parameters from: ' + challengeUrl, true); - var options = util.createRequestOptions({ _callContext: { _logContext: logContext } }); - - axios.get(challengeUrl, options).then((response) => { - util.logReturnCorrelationId(logger, "Authentication Parameters", response); - var parameters; - try { - parameters = exports.createAuthenticationParametersFromResponse(response); - } catch (creationErr) { - logger.error('Unable to parse response in to authentication parameters.', creationErr, true); - callback(creationErr); - } - callback(null, parameters); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - var parameters; - util.logReturnCorrelationId(logger, "Authentication Parameters", error.response); - try { - parameters = exports.createAuthenticationParametersFromResponse(error.response); - } catch (creationErr) { - logger.error('Unable to parse response in to authentication parameters.', creationErr, true); - callback(creationErr); - return; - } - callback(null, parameters); - } - // if there is no response from the server - else if (error.request) { - logger.error('AuthenticationParameters' + ' request was made but no response was received', error.request, true); - callback(logger.createError('No response from the server')); - } - // request was never made - else { - logger.error('AuthenticationParameters http get failed.' + ' request was never made, please check', error.message, true); - callback(error.message); - } - }) - } catch(err) { - callback(err); - return; - } -}; - -module.exports = exports; + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. -/***/ }), + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } -/***/ 19270: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + src.on('data', ondata); -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var axios = __nccwpck_require__(96545); -var url = __nccwpck_require__(78835); -var _ = __nccwpck_require__(83571); - -var AADConstants = __nccwpck_require__(10282).AADConstants; -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); - -/** -* Constructs an Authority object with a specific authority URL. -* @private -* @constructor -* @param {string} authorityUrl A URL that identifies a token authority. -* @param {bool} validateAuthority Indicates whether the Authority url should be validated as an actual AAD -* authority. The default is true. -*/ -function Authority(authorityUrl, validateAuthority) { - this._log = null; - this._url = url.parse(authorityUrl); - this._validateAuthorityUrl(); - - this._validated = !validateAuthority; - this._host = null; - this._tenant = null; - this._parseAuthority(); - - this._authorizationEndpoint = null; - this._tokenEndpoint = null; - this._deviceCodeEndpoint = null; - this._isAdfsAuthority = (this._tenant.toLowerCase() === "adfs"); -} - -/** - * The URL of the authority - * @instance - * @type {string} - * @memberOf Authority - * @name url - */ -Object.defineProperty(Authority.prototype, 'url', { - get: function() { - return url.format(this._url); - } -}); - -/** - * The token endpoint that the authority uses as discovered by instance discovery. - * @instance - * @type {string} - * @memberOf Authority - * @name tokenEndpoint - */ -Object.defineProperty(Authority.prototype, 'tokenEndpoint', { - get: function() { - return this._tokenEndpoint; - } -}); - -Object.defineProperty(Authority.prototype, 'deviceCodeEndpoint', { - get: function() { - return this._deviceCodeEndpoint; - } -}); - -/** - * Checks the authority url to ensure that it meets basic requirements such as being over SSL. If it does not then - * this method will throw if any of the checks fail. - * @private - * @throws {Error} If the authority url fails to pass any validation checks. - */ -Authority.prototype._validateAuthorityUrl = function() { - if (this._url.protocol !== 'https:') { - throw new Error('The authority url must be an https endpoint.'); - } - - if (this._url.query) { - throw new Error('The authority url must not have a query string.'); - } -}; - -/** - * Parse the authority to get the tenant name. The rest of the - * URL is thrown away in favor of one of the endpoints from the validation doc. - * @private - */ -Authority.prototype._parseAuthority = function() { - this._host = this._url.host; - - var pathParts = this._url.pathname.split('/'); - this._tenant = pathParts[1]; - - if (!this._tenant) { - throw new Error('Could not determine tenant.'); - } -}; - -/** - * Performs instance discovery based on a simple match against well known authorities. - * @private - * @return {bool} Returns true if the authority is recognized. - */ -Authority.prototype._performStaticInstanceDiscovery = function() { - this._log.verbose('Performing static instance discovery'); - - var hostIndex = _.indexOf(AADConstants.WELL_KNOWN_AUTHORITY_HOSTS, this._url.hostname); - var found = hostIndex > -1; - - if (found) { - this._log.verbose('Authority validated via static instance discovery.'); - } - - return found; -}; - -Authority.prototype._createAuthorityUrl = function() { - return 'https://' + this._url.host + '/' + encodeURIComponent(this._tenant) + AADConstants.AUTHORIZE_ENDPOINT_PATH; -}; - -/** - * Creates an instance discovery endpoint url for the specific authority that this object represents. - * @private - * @param {string} authorityHost The host name of a well known authority. - * @return {URL} The constructed endpoint url. - */ -Authority.prototype._createInstanceDiscoveryEndpointFromTemplate = function(authorityHost) { - var discoveryEndpoint = AADConstants.INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE; - discoveryEndpoint = discoveryEndpoint.replace('{authorize_host}', authorityHost); - discoveryEndpoint = discoveryEndpoint.replace('{authorize_endpoint}', encodeURIComponent(this._createAuthorityUrl())); - return url.parse(discoveryEndpoint); -}; - -/** - * Performs instance discovery via a network call to well known authorities. - * @private - * @param {Authority.InstanceDiscoveryCallback} callback The callback function. If succesful, - * this function calls the callback with the - * tenantDiscoveryEndpoint returned by the - * server. - */ -Authority.prototype._performDynamicInstanceDiscovery = function(callback) { - try { - var self = this; - var discoveryEndpoint = this._createInstanceDiscoveryEndpointFromTemplate(AADConstants.WORLD_WIDE_AUTHORITY); - - var getOptions = util.createRequestOptions(self); - - this._log.verbose('Attempting instance discover'); - this._log.verbose('Attempting instance discover at: ' + url.format(discoveryEndpoint), true); - - axios.get(discoveryEndpoint, getOptions).then((response) => { - util.logReturnCorrelationId(this._log, 'Instance Discovery', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'Instance Discovery' + ' request returned http error: ' + response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - var discoveryResponse = response.data; - if (discoveryResponse['tenant_discovery_endpoint']) { - callback(null, discoveryResponse['tenant_discovery_endpoint']); - } else { - callback(self._log.createError('Failed to parse instance discovery response')); - } - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'Instance Discovery', error.response); - this._log.error('Instance Discovery' + ' request failed with', error.response.status, true); - var returnErrorString = 'Instance Discovery' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if(error.request) { - this._log.error('Instance Discovery' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else { - this._log.error('Instance Discovery' + ' request was never made, please check', error.message, true); - callback(error.message); - } - }); - } catch(e) { - callback(e); - } -}; - -/** - * @callback InstanceDiscoveryCallback - * @private - * @memberOf Authority - * @param {Error} err If an error occurs during instance discovery then it will be returned here. - * @param {string} tenantDiscoveryEndpoint If instance discovery is successful then this will contain the - * tenantDiscoveryEndpoint associated with the authority. - */ - -/** - * Determines whether the authority is recognized as a trusted AAD authority. - * @private - * @param {Authority.InstanceDiscoveryCallback} callback The callback function. - */ -Authority.prototype._validateViaInstanceDiscovery = function(callback) { - if (this._performStaticInstanceDiscovery()) { - callback(); - } else { - this._performDynamicInstanceDiscovery(callback); - } -}; - -/** - * @callback GetOauthEndpointsCallback - * @private - * @memberOf Authority - * @param {Error} error An error if one occurred. - */ - -/** - * Given a tenant discovery endpoint this method will attempt to discover the token endpoint. If the - * tenant discovery endpoint is unreachable for some reason then it will fall back to a algorithmic generation of the - * token endpoint url. - * @private - * @param {string} tenantDiscoveryEndpoint The url of the tenant discovery endpoint for this authority. - * @param {Authority.GetOauthEndpointsCallback} callback The callback function. - */ -Authority.prototype._getOAuthEndpoints = function(tenantDiscoveryEndpoint, callback) { - if (this._tokenEndpoint && this._deviceCodeEndpoint) { - callback(); - return; - } else { - // fallback to the well known token endpoint path. - if (!this._tokenEndpoint){ - this._tokenEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.TOKEN_ENDPOINT_PATH; - } - - if (!this._deviceCodeEndpoint){ - this._deviceCodeEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.DEVICE_ENDPOINT_PATH; - } - - callback(); - return; - } -}; - -/** - * @callback ValidateCallback - * @memberOf Authority - */ - -/** - * Perform validation on the authority represented by this object. In addition to simple validation - * the oauth token endpoint will be retrieved. - * @param {Authority.ValidateCallback} callback The callback function. - */ -Authority.prototype.validate = function(callContext, callback) { - this._log = new Logger('Authority', callContext._logContext); - this._callContext = callContext; - var self = this; - - if (!this._validated) { - this._log.verbose('Performing instance discovery'); - this._log.verbose('Performing instance discovery: ' + url.format(this._url), true); - this._validateViaInstanceDiscovery(function(err, tenantDiscoveryEndpoint) { - if (err) - { - callback(err); - } else { - self._validated = true; - self._getOAuthEndpoints(tenantDiscoveryEndpoint, callback); - return; - } - }); - } else { - this._log.verbose('Instance discovery/validation has either already been completed or is turned off'); - this._log.verbose('Instance discovery/validation has either already been completed or is turned off: ' + url.format(this._url), true); - this._getOAuthEndpoints(null, callback); - return; - } -}; - -module.exports.W = Authority; + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } -/***/ }), + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. -/***/ 38289: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - - -var _ = __nccwpck_require__(83571); -var crypto = __nccwpck_require__(76417); -__nccwpck_require__(1693); // Adds a number of convenience methods to the builtin Date object. - -var Logger = __nccwpck_require__(92288).Logger; -var constants = __nccwpck_require__(10282); -var cacheConstants = constants.Cache; -var TokenResponseFields = constants.TokenResponseFields; - -// TODO: remove this. -// There is a PM requirement that developers be able to look in to the cache and manipulate the cache based on -// the parameters (authority, resource, clientId, userId), in any combination. They must be able find, add, and remove -// tokens based on those parameters. Any default cache that the API supplies must allow for this query pattern. -// This has the following implications: -// The developer must not be required to calculate any special fields, such as hashes or unique keys. -// -// The default cache implementation can not include optimizations that break the previous requirement. -// This means that we can only do complete scans of the data and equality can only be calculated based on -// equality of all of the individual fields. -// -// The cache interface can not make any assumption about the query efficency of the cache nor can -// it help in optimizing those queries. -// -// There is no simple sorting optimization, rather a series of indexes, and index intersection would -// be necessary. -// -// If for some reason the developer tries to update the cache with a new entry that may be a refresh -// token, they will not know that they need to update all of the refresh tokens or they may get strange -// behavior. -// -// Related to the above, there is no definition of a coherent cache. And if there was there would be -// no way for our API to enforce it. What about duplicates? -// -// there be a single cache entry per (authority, resource, clientId) -// tuple, with no special tokens (i.e. MRRT tokens) -// Required cache operations -// - -// Constants -var METADATA_CLIENTID = '_clientId'; -var METADATA_AUTHORITY = '_authority'; - -function nop(placeHolder, callback) { - callback(); -} - -/* - * This is a place holder cache that does nothing. - */ -var nopCache = { - add : nop, - addMany : nop, - remove : nop, - removeMany : nop, - find : nop -}; - -function createTokenHash(token) { - var hashAlg = crypto.createHash(cacheConstants.HASH_ALGORITHM); - hashAlg.update(token, 'utf8'); - return hashAlg.digest('base64'); -} - -function createTokenIdMessage(entry) { - var accessTokenHash = createTokenHash(entry[TokenResponseFields.ACCESS_TOKEN]); - var message = 'AccessTokenId: ' + accessTokenHash; - if (entry[TokenResponseFields.REFRESH_TOKEN]) { - var refreshTokenHash = createTokenHash(entry[TokenResponseFields.REFRESH_TOKEN]); - message += ', RefreshTokenId: ' + refreshTokenHash; - } - return message; -} - -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback RefreshEntryFunction - * @memberOf CacheDriver - * @param {object} tokenResponse A token response to refresh. - * @param {string} [resource] The resource for which to obtain the token if it is different from the original token. - * @param {AcquireTokenCallback} callback Called on completion with an error or a new entry to add to the cache. - */ - -/** - * Constructs a new CacheDriver object. - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} authority - * @param {TokenCache} [cache] A token cache to use. If none is passed then the CacheDriver instance - * will not cache. - * @param {RefreshEntryFunction} refreshFunction - */ -function CacheDriver(callContext, authority, resource, clientId, cache, refreshFunction) { - this._callContext = callContext; - this._log = new Logger('CacheDriver', callContext._logContext); - this._authority = authority; - this._resource = resource; - this._clientId = clientId; - this._cache = cache || nopCache; - this._refreshFunction = refreshFunction; -} - -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback QueryCallback - * @memberOf CacheDriver - * @param {Error} [error] If the request fails this parameter will contain an Error object. - * @param {Array} [response] On a succesful request returns an array of matched entries. - */ - -/** - * The cache driver query function. Ensures that all queries are authority specific. - * @param {object} query A query object. Can contain a clientId or userId or both. - * @param {QueryCallback} callback - */ -CacheDriver.prototype._find = function(query, callback) { - this._cache.find(query, callback); -}; - -/** - * Queries for all entries that might satisfy a request for a cached token. - * @param {object} query A query object. Can contain a clientId or userId or both. - * @param {QueryCallback} callback - */ -CacheDriver.prototype._getPotentialEntries = function(query, callback) { - var self = this; - var potentialEntriesQuery = {}; - - if (query.clientId) { - potentialEntriesQuery[METADATA_CLIENTID] = query.clientId; - } - if (query.userId) { - potentialEntriesQuery[TokenResponseFields.USER_ID] = query.userId; - } - - this._log.verbose('Looking for potential cache entries:'); - this._log.verbose(JSON.stringify(potentialEntriesQuery), true); - this._find(potentialEntriesQuery, function(err, entries) { - self._log.verbose('Found ' + entries.length + ' potential entries.'); - callback(err, entries); - return; - }); -}; - -/** - * Finds all multi resource refresh tokens in the cache. - * Refresh token is bound to userId, clientId. - * @param {QueryCallback} callback - */ -CacheDriver.prototype._findMRRTTokensForUser = function(user, callback) { - this._find({ isMRRT : true, userId : user, _clientId : this._clientId}, callback); -}; - -/** - * This is the callback that is passed to all acquireToken variants below. - * @callback SingleEntryCallback - * @memberOf CacheDriver - * @param {Error} [error] If the request fails this parameter will contain an Error object. - * @param {object} [response] On a succesful request returns a single cache entry. - */ - - -/** - * Finds a single entry that matches the query. If multiple entries are found that satisfy the query - * then an error will be returned. - * @param {object} query A query object. - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype._loadSingleEntryFromCache = function(query, callback) { - var self = this; - this._getPotentialEntries(query, function(err, potentialEntries) { - if (err) { - callback(err); - return; - } - - var returnVal; - var isResourceTenantSpecific; - - if (potentialEntries && 0 < potentialEntries.length) { - var resourceTenantSpecificEntries = _.where(potentialEntries, { resource : self._resource, _authority : self._authority }); - - if (!resourceTenantSpecificEntries || 0 === resourceTenantSpecificEntries.length) { - self._log.verbose('No resource specific cache entries found.'); - - // There are no resource specific entries. Find an MRRT token. - var mrrtTokens = _.where(potentialEntries, { isMRRT : true }); - if (mrrtTokens && mrrtTokens.length > 0) { - self._log.verbose('Found an MRRT token.'); - returnVal = mrrtTokens[0]; - } else { - self._log.verbose('No MRRT tokens found.'); - } - - } else if (resourceTenantSpecificEntries.length === 1) { - self._log.verbose('Resource specific token found.'); - returnVal = resourceTenantSpecificEntries[0]; - isResourceTenantSpecific = true; - }else { - callback(self._log.createError('More than one token matches the criteria. The result is ambiguous.')); - return; - } - } - if (returnVal) { - self._log.verbose('Returning token from cache lookup'); - self._log.verbose('Returning token from cache lookup, ' + createTokenIdMessage(returnVal), true); - } - callback(null, returnVal, isResourceTenantSpecific); - }); -}; - -/** - * The response from a token refresh request never contains an id_token and therefore no - * userInfo can be created from the response. This function creates a new cache entry - * combining the id_token based info and cache metadata from the cache entry that was refreshed with the - * new tokens in the refresh response. - * @param {object} entry A cache entry corresponding to the resfreshResponse. - * @param {object} refreshResponse The response from a token refresh request for the entry parameter. - * @return {object} A new cache entry. - */ -CacheDriver.prototype._createEntryFromRefresh = function(entry, refreshResponse) { - var newEntry = _.clone(entry); - newEntry = _.extend(newEntry, refreshResponse); - - if (entry.isMRRT && this._authority !== entry[METADATA_AUTHORITY]) { - newEntry[METADATA_AUTHORITY] = this._authority; - } - - this._log.verbose('Created new cache entry from refresh response.'); - return newEntry; -}; - -CacheDriver.prototype._replaceEntry = function(entryToReplace, newEntry, callback) { - var self = this; - this.remove(entryToReplace, function(err) { - if (err) { - callback(err); - return; - } - self.add(newEntry, callback); - }); -}; - -/** - * Given an expired cache entry refreshes it and updates the cache. - * @param {object} entry A cache entry with an MRRT to refresh for another resource. - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype._refreshExpiredEntry = function(entry, callback) { - var self = this; - this._refreshFunction(entry, null, function(err, tokenResponse) { - if (err) { - callback(err); - return; - } - - var newEntry = self._createEntryFromRefresh(entry, tokenResponse); - self._replaceEntry(entry, newEntry, function(err) { - if (err) { - self._log.error('error refreshing expired token', err, true); - } else { - self._log.info('Returning token refreshed after expiry.'); - } - callback(err, newEntry); - }); - }); -}; - -/** - * Given a cache entry with an MRRT will acquire a new token for a new resource via the MRRT, and cache it. - * @param {object} entry A cache entry with an MRRT to refresh for another resource. - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype._acquireNewTokenFromMrrt = function(entry, callback) { - var self = this; - this._refreshFunction(entry, this._resource, function(err, tokenResponse) { - if (err) { - callback(err); - return; - } - - var newEntry = self._createEntryFromRefresh(entry, tokenResponse); - self.add(newEntry, function(err) { - if (err) { - self._log.error('error refreshing mrrt', err, true); - } else { - self._log.info('Returning token derived from mrrt refresh.'); - } - callback(err, newEntry); - }); - }); -}; - -/** - * Given a token this function will refresh it if it is either expired, or an MRRT. - * @param {object} entry A cache entry to refresh if necessary. - * @param {Boolean} isResourceSpecific Indicates whether this token is appropriate for the resource for which - * it was requested or whether it is possibly an MRRT token for which - * a resource specific access token should be acquired. - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype._refreshEntryIfNecessary = function(entry, isResourceSpecific, callback) { - var expiryDate = entry[TokenResponseFields.EXPIRES_ON]; - - // Add some buffer in to the time comparison to account for clock skew or latency. - var nowPlusBuffer = (new Date()).addMinutes(constants.Misc.CLOCK_BUFFER); - - if (isResourceSpecific && nowPlusBuffer.isAfter(expiryDate)) { - this._log.info('Cached token is expired. Refreshing: ' + expiryDate); - this._refreshExpiredEntry(entry, callback); - return; - } else if (!isResourceSpecific && entry.isMRRT) { - this._log.info('Acquiring new access token from MRRT token.'); - this._acquireNewTokenFromMrrt(entry, callback); - return; - } else { - callback(null, entry); - } -}; - -/** - * Finds a single entry in the cache that matches the query or fails if more than one match is found. - * @param {object} query A query object - * @param {SingleEntryCallback} callback - */ -CacheDriver.prototype.find = function(query, callback) { - var self = this; - query = query || {}; - this._log.verbose('finding using query'); - this._log.verbose('finding with query:' + JSON.stringify(query), true); - this._loadSingleEntryFromCache(query, function(err, entry, isResourceTenantSpecific) { - if (err) { - callback(err); - return; - } - - if (!entry) { - callback(); - return; - } - - self._refreshEntryIfNecessary(entry, isResourceTenantSpecific, function(err, newEntry) { - callback(err, newEntry); - return; - }); - }); -}; - -/** - * Removes a single entry from the cache. - * @param {object} entry The entry to remove. - * @param {Function} callback Called on completion. The first parameter may contain an error. - */ -CacheDriver.prototype.remove = function(entry, callback) { - this._log.verbose('Removing entry.'); - return this._cache.remove([entry], function(err) { - callback(err); - return; - }); -}; - -/** - * Removes a collection of entries from the cache in a single batch operation. - * @param {Array} entries An array of cache entries to remove. - * @param {Function} callback This function is called when the operation is complete. Any error is provided as the - * first parameter. - */ -CacheDriver.prototype._removeMany = function(entries, callback) { - this._log.verbose('Remove many: ' + entries.length); - this._cache.remove(entries, function(err) { - callback(err); - return; - }); -}; - -/** - * Adds a collection of entries to the cache in a single batch operation. - * @param {Array} entries An array of entries to add to the cache. - * @param {Function} callback This function is called when the operation is complete. Any error is provided as the - * first parameter. - */ -CacheDriver.prototype._addMany = function(entries, callback) { - this._log.verbose('Add many: ' + entries.length); - this._cache.add(entries, function(err) { - callback(err); - return; - }); -}; - -/* - * Tests whether the passed entry is a multi resource refresh token. - * Somewhat mysteriously the presense of a resource field in a returned - * token response indicates that the response is an MRRT. - * @param {object} entry - * @return {Boolean} true if the entry is an MRRT. - */ -function isMRRT(entry) { - return entry.resource ? true : false; -} - -/** - * Given an cache entry this function finds all of the MRRT tokens already in the cache - * and updates them with the refresh_token of the passed in entry. - * @param {object} entry The entry from which to get an updated refresh_token - * @param {Function} callback Called back on completion. The first parameter may contain an error. - */ -CacheDriver.prototype._updateRefreshTokens = function(entry, callback) { - var self = this; - if (isMRRT(entry)) { - this._findMRRTTokensForUser(entry.userId, function(err, mrrtTokens) { - if (err) { - callback(err); - return; - } - - if (!mrrtTokens || 0 === mrrtTokens.length) { - callback(); - return; - } - - self._log.verbose('Updating ' + mrrtTokens.length + ' cached refresh tokens.'); - self._removeMany(mrrtTokens, function(err) { - if (err) { - callback(err); - return; - } - - for (var i = 0; i < mrrtTokens.length; i++) { - mrrtTokens[i][TokenResponseFields.REFRESH_TOKEN] = entry[TokenResponseFields.REFRESH_TOKEN]; - } - - self._addMany(mrrtTokens, function(err) { - callback(err); - return; - }); - }); - }); - } else { - callback(); - return; - } -}; - -/** - * Checks to see if the entry has cache metadata already. If it does - * then it probably came from a refresh operation and the metadata - * was copied from the originating entry. - * @param {object} entry The entry to check - * @return {bool} Returns true if the entry has already been augmented - * with cache metadata. - */ -CacheDriver.prototype._entryHasMetadata = function(entry) { - return (_.has(entry, METADATA_CLIENTID) && _.has(entry, METADATA_AUTHORITY)); -}; - -CacheDriver.prototype._augmentEntryWithCacheMetadata = function(entry) { - if (this._entryHasMetadata(entry)) { - return; - } - - if (isMRRT(entry)) { - this._log.verbose('Added entry is MRRT'); - entry.isMRRT = true; - } else { - entry.resource = this._resource; - } - - entry[METADATA_CLIENTID] = this._clientId; - entry[METADATA_AUTHORITY] = this._authority; -}; - -/** - * Adds a single entry to the cache. - * @param {object} entry The entry to add. - * @param {string} clientId The id of this client app. - * @param {string} resource The id of the resource for which the cached token was obtained. - * @param {Function} callback Called back on completion. The first parameter may contain an error. - */ -CacheDriver.prototype.add = function(entry, callback) { - var self = this; - this._log.verbose('Adding entry'); - this._log.verbose('Adding entry, ' + createTokenIdMessage(entry)); - - this._augmentEntryWithCacheMetadata(entry); - - this._updateRefreshTokens(entry, function(err) { - if (err) { - callback(err); - return; - } - - self._cache.add([entry], function(err) { - callback(err); - return; - }); - }); -}; - -module.exports = CacheDriver; + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. -/***/ }), -/***/ 66576: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var constants = __nccwpck_require__(10282); -var Logger = __nccwpck_require__(92288).Logger; -var Mex = __nccwpck_require__(27078); -var OAuth2Client = __nccwpck_require__(41602); - -var OAuth2Parameters = constants.OAuth2.Parameters; -var TokenResponseFields = constants.TokenResponseFields; -var OAuth2GrantType = constants.OAuth2.GrantType; -var OAuth2Scope = constants.OAuth2.Scope; - -/** - * Constructs a new CodeRequest object. - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {AuthenticationContext} authenticationContext - * @param {string} resource - * @param {string} clientId - */ -// TODO: probably need to modify the parameter list. -function CodeRequest(callContext, authenticationContext, clientId, resource) { - this._log = new Logger('DeviceCodeRequest', callContext._logContext); - this._callContext = callContext; - this._authenticationContext = authenticationContext; - this._resource = resource; - this._clientId = clientId; - - // This should be set at the beginning of getToken - // functions that have a userId. - this._userId = null; -}; - -/** - * Get user code info. - * @private - * @param {object} oauthParameters containing all the parameters needed to get the user code info. - * @param {callback} callback - */ -CodeRequest.prototype._getUserCodeInfo = function (oauthParameters, callback) { - var oauth2Client = this._createOAuth2Client(); - oauth2Client.getUserCodeInfo(oauthParameters, callback); -}; - -CodeRequest.prototype._createOAuth2Client = function () { - return new OAuth2Client(this._callContext, this._authenticationContext._authority); -}; - -/** - * Creates a set of basic, common, OAuthParameters based on values that the CodeRequest was created with. - * @private - * @return {object} containing all the basic parameters. - */ -CodeRequest.prototype._createOAuthParameters = function () { - var oauthParameters = {}; - - oauthParameters[OAuth2Parameters.CLIENT_ID] = this._clientId; - oauthParameters[OAuth2Parameters.RESOURCE] = this._resource; - - return oauthParameters; -}; - -/** - * Get the user code information. - * @param {string} language optional parameter used to get the user code info. - * @param {callback} callback - */ -CodeRequest.prototype.getUserCodeInfo = function(language, callback) { - this._log.info('Getting user code info.'); - - var oauthParameters = this._createOAuthParameters(); - if (language){ - oauthParameters[OAuth2Parameters.LANGUAGE] = language; - } - - this._getUserCodeInfo(oauthParameters, callback); -}; -module.exports = CodeRequest; + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } -/***/ }), + dest.once('close', onclose); -/***/ 10282: -/***/ ((module) => { + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var Constants = { - OAuth2 : { - Parameters : { - GRANT_TYPE : 'grant_type', - CLIENT_ASSERTION : 'client_assertion', - CLIENT_ASSERTION_TYPE : 'client_assertion_type', - CLIENT_ID : 'client_id', - CLIENT_SECRET : 'client_secret', - REDIRECT_URI : 'redirect_uri', - RESOURCE : 'resource', - CODE : 'code', - SCOPE : 'scope', - ASSERTION : 'assertion', - AAD_API_VERSION : 'api-version', - USERNAME : 'username', - PASSWORD : 'password', - REFRESH_TOKEN : 'refresh_token', - LANGUAGE : 'mkt', - DEVICE_CODE : 'device_code', - }, - - GrantType : { - AUTHORIZATION_CODE : 'authorization_code', - REFRESH_TOKEN : 'refresh_token', - CLIENT_CREDENTIALS : 'client_credentials', - JWT_BEARER : 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', - PASSWORD : 'password', - SAML1 : 'urn:ietf:params:oauth:grant-type:saml1_1-bearer', - SAML2 : 'urn:ietf:params:oauth:grant-type:saml2-bearer', - DEVICE_CODE: 'device_code' - }, - - ResponseParameters : { - CODE : 'code', - TOKEN_TYPE : 'token_type', - ACCESS_TOKEN : 'access_token', - ID_TOKEN : 'id_token', - REFRESH_TOKEN : 'refresh_token', - CREATED_ON : 'created_on', - EXPIRES_ON : 'expires_on', - EXPIRES_IN : 'expires_in', - RESOURCE : 'resource', - ERROR : 'error', - ERROR_DESCRIPTION : 'error_description' - }, - - DeviceCodeResponseParameters : { - USER_CODE : 'user_code', - DEVICE_CODE : 'device_code', - VERIFICATION_URL : 'verification_url', - EXPIRES_IN : 'expires_in', - INTERVAL: 'interval', - MESSAGE: 'message', - ERROR: 'error', - ERROR_DESCRIPTION: 'error_description' - }, - - Scope : { - OPENID : 'openid' - }, - - IdTokenMap : { - 'tid' : 'tenantId', - 'given_name' : 'givenName', - 'family_name' : 'familyName', - 'idp' : 'identityProvider', - 'oid': 'oid' - } - }, - - TokenResponseFields : { - TOKEN_TYPE : 'tokenType', - ACCESS_TOKEN : 'accessToken', - REFRESH_TOKEN : 'refreshToken', - CREATED_ON : 'createdOn', - EXPIRES_ON : 'expiresOn', - EXPIRES_IN : 'expiresIn', - RESOURCE : 'resource', - USER_ID : 'userId', - ERROR : 'error', - ERROR_DESCRIPTION : 'errorDescription' - }, - - UserCodeResponseFields : { - USER_CODE : 'userCode', - DEVICE_CODE: 'deviceCode', - VERIFICATION_URL: 'verificationUrl', - EXPIRES_IN: 'expiresIn', - INTERVAL: 'interval', - MESSAGE: 'message', - ERROR: 'error', - ERROR_DESCRIPTION: 'errorDescription' - }, - - IdTokenFields : { - USER_ID : 'userId', - IS_USER_ID_DISPLAYABLE : 'isUserIdDisplayable', - TENANT_ID : 'tenantId', - GIVE_NAME : 'givenName', - FAMILY_NAME : 'familyName', - IDENTITY_PROVIDER : 'identityProvider' - }, - - Misc : { - MAX_DATE : 0xffffffff, - CLOCK_BUFFER : 5 // In minutes. - }, - - Jwt : { - SELF_SIGNED_JWT_LIFETIME : 10, // 10 mins in mins - AUDIENCE : 'aud', - ISSUER : 'iss', - SUBJECT : 'sub', - NOT_BEFORE : 'nbf', - EXPIRES_ON : 'exp', - JWT_ID : 'jti' - }, - - AADConstants : { - WORLD_WIDE_AUTHORITY : 'login.windows.net', - WELL_KNOWN_AUTHORITY_HOSTS : ['login.windows.net', 'login.microsoftonline.com', 'login.chinacloudapi.cn', 'login-us.microsoftonline.com', 'login.microsoftonline.de', 'login.microsoftonline.us'], - INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE : 'https://{authorize_host}/common/discovery/instance?authorization_endpoint={authorize_endpoint}&api-version=1.0', - AUTHORIZE_ENDPOINT_PATH : '/oauth2/authorize', - TOKEN_ENDPOINT_PATH : '/oauth2/token', - DEVICE_ENDPOINT_PATH : '/oauth2/devicecode' - }, - - UserRealm : { - FederationProtocolType : { - WSFederation : 'wstrust', - SAML2 : 'saml20', - Unknown : 'unknown' - }, - - AccountType : { - Federated : 'federated', - Managed : 'managed', - Unknown : 'unknown' - } - }, - - Saml : { - TokenTypeV1 : 'urn:oasis:names:tc:SAML:1.0:assertion', - TokenTypeV2 : 'urn:oasis:names:tc:SAML:2.0:assertion' - }, - - XmlNamespaces : { - wsdl : 'http://schemas.xmlsoap.org/wsdl/', - sp : 'http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702', - sp2005 : 'http://schemas.xmlsoap.org/ws/2005/07/securitypolicy', - wsu : 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd', - wsa10 : 'http://www.w3.org/2005/08/addressing', - http : 'http://schemas.microsoft.com/ws/06/2004/policy/http', - soap12 : 'http://schemas.xmlsoap.org/wsdl/soap12/', - wsp : 'http://schemas.xmlsoap.org/ws/2004/09/policy', - s : 'http://www.w3.org/2003/05/soap-envelope', - wsa : 'http://www.w3.org/2005/08/addressing', - wst : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512', - t : 'http://schemas.xmlsoap.org/ws/2005/02/trust' - }, - - Cache : { - HASH_ALGORITHM : 'sha256' - }, - - HttpError : { - UNAUTHORIZED : 401 - }, - - AdalIdParameters : { - SKU : 'x-client-SKU', - VERSION : 'x-client-Ver', - OS : 'x-client-OS', - CPU : 'x-client-CPU', - NODE_SKU : 'Node' - }, - - WSTrustVersion : { - UNDEFINED : 'undefined', - WSTRUST13 : 'wstrust13', - WSTRUST2005 : 'wstrust2005' - } - }; - -module.exports = Constants; + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to -/***/ }), -/***/ 92288: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + dest.emit('pipe', src); // start the flow if it hasn't been started already. -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var _ = __nccwpck_require__(83571); -var uuid = __nccwpck_require__(19744); // want to replace with this in the future: https://gist.github.com/jed/982883 - - - -var LEVEL_STRING_MAP = { - 0 : 'ERROR:', - 1 : 'WARNING:', - 2 : 'INFO:', - 3 : 'VERBOSE:' -}; - -/** - * Methods for controling global logging options for ADAL - * @namespace - */ -var Logging = { - - /** - * @callback LoggingCallback - * @memberOf Logging - * @param {Logging.LOGGING_LEVEL} level The level of this log entry. - * @param {string} message The text content of the log entry. - * @param {Error} [error] An Error object if this is an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry. - */ - - /** - * @typedef LoggingOptions - * @memberOf Logging - * @property {LoggingCallback} [log] The function to call when ADAL generates a log entry. - * @property {Logging.LOGGING_LEVEL} [level] The maximum level of log entries to generate. - */ - - /** - * Describes the available logging levels. - * @enum - * @type {Number} - */ - LOGGING_LEVEL : { - ERROR : 0, - WARN : 1, - INFO : 2, - VERBOSE : 3 - }, - - /** - * Sets global logging options for ADAL. - * @param {LoggingOptions} options - */ - setLoggingOptions : function(options) { - if (!options) { - options = {}; - } - - if (options.log) { - if (!_.isFunction(options.log)) { - throw new Error('setLogOptions expects the log key in the options parameter to be a function'); - } - } else { - // if no log function was passed set it to a default no op function. - options.log = function() {}; - } - - if (options.level) { - var level = options.level; - if (level < 0 || level > 3) { - throw new Error('setLogOptions expects the level key to be in the range 0 to 3 inclusive'); - } - } else { - options.level = this.LOGGING_LEVEL.ERROR; - } - - if (options.loggingWithPII != true) { - options.loggingWithPII = false; - } - - this.LogOptions = options; - }, - - /** - * Get's the current global logging options. - * @return {LoggingOptions} - */ - getLoggingOptions : function() { - return this.LogOptions; - }, - - /** - * Stores the current global logging options. - * @private - * @type {LoggingOptions} - */ - LogOptions : { - log : function() {}, - level : 0, - loggingWithPII: false - } -}; - -/** - * An internal logging object. - * @class - * @private - * @param {string} componentName The name of the component that created this instance. This name will be - * prepended to the beginning of all log entries generated by this instance. - */ -function Logger(componentName, logContext) { - if (!logContext) { - throw new Error('Logger: logContext is a required parameter'); - } - this._componentName = componentName; - this._logContext = logContext; -} - -Object.defineProperty(Logger.prototype, 'context', { - get: function () { - return this._logContext; - } -}); - -/** - * Generates a log entry - * @param {Logging.LOGGING_LEVEL} level The level of this log entry - * @param {string|function} message A message string, or a function that returns a message string, to log. - * @param {Error} [error] If this is a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry then the caller - * should pass an error object in this parameter. - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.log = function (level, message, error, containsPII) { - if (containsPII == true && !Logging.LogOptions.loggingWithPII) { - return; - } - - if (level <= Logging.LogOptions.level) { - if (_.isFunction(message)) { - message = message(); - } - - var correlationId = this._logContext.correlationId || ''; - var timeStamp = new Date().toUTCString(); - - var formattedMessage = timeStamp + ':' + correlationId + ' - ' + this._componentName + ': ' + LEVEL_STRING_MAP[level] + ' ' + message; - if (error) { - formattedMessage += '\nStack:\n' + error.stack; - } - Logging.LogOptions.log(level, formattedMessage, error); - } -}; - -/** - * Generate an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry. - * @param {string} message A message to log - * @param {Error} error The Error object associated with this log entry - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.error = function (message, error, containsPII) { - this.log(Logging.LOGGING_LEVEL.ERROR, message, error, containsPII); -}; - -/** - * Generate an {@link Logging.LOGGING_LEVEL.WARN|WARN} level log entry. - * @param {string} message A message to log - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.warn = function (message, containsPII) { - this.log(Logging.LOGGING_LEVEL.WARN, message, null, containsPII); -}; - -/** - * Generate an {@link Logging.LOGGING_LEVEL.INFO|INFO} level log entry. - * @param {string} message A message to log - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.info = function (message, containsPII) { - this.log(Logging.LOGGING_LEVEL.INFO, message, null, containsPII); -}; - -/** - * Generate an {@link Logging.LOGGING_LEVEL.VERBOSE|VERBOSE} level log entry. - * @param {string} message A message to log - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.verbose = function (message, containsPII) { - this.log(Logging.LOGGING_LEVEL.VERBOSE, message, null, containsPII); -}; - -/** - * Generate a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry, as well as an - * Error object to go with it. This is a convenience method for throwing logged errors. - * @param {string} message A message to log - * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false. - */ -Logger.prototype.createError = function(message, containsPII) { - var err = new Error(message); - this.error(message, err, containsPII); - return err; -}; - -/** - * Creates a new log context based on the correlationId passed in. If no correlationId is passed in - * then one is generated, by the function uuid.v4() - * @private - */ -function createLogContext(correlationId) { - var id = correlationId || uuid.v4(); - return { correlationId : id }; -} - -var exports = { - Logging : Logging, - Logger : Logger, - createLogContext : createLogContext -}; - -module.exports = exports; + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } -/***/ }), + return dest; +}; -/***/ 92474: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - - -var _ = __nccwpck_require__(83571); - -/** - * Constructs a new in memory token cache. - * @constructor - */ -function MemoryCache() { - this._entries = []; -} - -/** - * Removes a collection of entries from the cache in a single batch operation. - * @param {Array} entries An array of cache entries to remove. - * @param {Function} callback This function is called when the operation is complete. Any error is provided as the - * first parameter. - */ -MemoryCache.prototype.remove = function(entries, callback) { - var updatedEntries = _.filter(this._entries, function(element) { - if (_.findWhere(entries, element)) { - return false; - } - return true; - }); - - this._entries = updatedEntries; - callback(); -}; - -/** - * Adds a collection of entries to the cache in a single batch operation. - * @param {Array} entries An array of entries to add to the cache. - * @param {Function} callback This function is called when the operation is complete. Any error is provided as the - * first parameter. - */ -MemoryCache.prototype.add = function(entries, callback) { - // Remove any entries that are duplicates of the existing - // cache elements. - _.each(this._entries, function(element) { - _.each(entries, function(addElement, index) { - if (_.isEqual(element, addElement)) { - entries[index] = null; - } - }); - }); - - // Add the new entries to the end of the cache. - entries = _.compact(entries); - for (var i = 0; i < entries.length; i++) { - this._entries.push(entries[i]); - } - - callback(null, true); -}; - -/** - * Finds all entries in the cache that match all of the passed in values. - * @param {object} query This object will be compared to each entry in the cache. Any entries that - * match all of the values in this object will be returned. All the values - * in the passed in object must match values in a potentialy returned object - * exactly. The returned object may have more values than the passed in query - * object. - * @param {TokenCacheFindCallback} callback - */ -MemoryCache.prototype.find = function(query, callback) { - var results = _.where(this._entries, query); - callback(null, results); -}; - -module.exports = MemoryCache; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; // set up data events if they are asked for +// Ensure readable listeners eventually get something + + +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + + return res; +}; + +Readable.prototype.addListener = Readable.prototype.on; + +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. + + +Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. + + +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __nccwpck_require__(37558); + } + + return createReadableStreamAsyncIterator(this); + }; +} + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); // exposed for testing purposes only. + +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. + +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} + +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __nccwpck_require__(57039); + } + + return from(Readable, iterable, opts); + }; +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; +} /***/ }), -/***/ 27078: +/***/ 26753: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - -var axios = __nccwpck_require__(96545); -var url = __nccwpck_require__(78835); -var DOMParser = __nccwpck_require__(57286).DOMParser; -var _ = __nccwpck_require__(83571); -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); - -var xmlutil = __nccwpck_require__(27387); -var select = xmlutil.xpathSelect; - -var Namespaces = __nccwpck_require__(10282).XmlNamespaces; - -var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; - -/** - * Create a new Mex object. - * @private - * @constructor - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} url The url of the mex endpoint. - */ -function Mex(callContext, url) { - this._log = new Logger('MEX', callContext._logContext); - this._callContext = callContext; - this._url = url; - this._dom = null; - this._mexDoc = null; - this._usernamePasswordPolicy = {}; - this._log.verbose('Mex created'); - this._log.verbose('Mex created with url: ' + url, true); -} - -/** -* Returns the policy containing IDP url and wstrust version from which a username passwowrd can be exchanged for a token. -* @instance -* @memberOf Mex -* @name usernamePasswordPolicy -*/ -Object.defineProperty(Mex.prototype, 'usernamePasswordPolicy', { - get: function() { - return this._usernamePasswordPolicy; - } -}); - -/** -* @callback DiscoverCallback -* @memberOf Mex -* @param {object} error -*/ - -/** -* Performs Mex discovery. This method will retrieve the mex document, parse it, and extract -* the username password ws-trust endpoint. -* @private -* @param {Mex.DiscoverCallback} callback Called when discover is complete. -*/ -Mex.prototype.discover = function (callback) { - this._log.verbose('Retrieving mex'); - this._log.verbose('Retrieving mex at: ' + this._url); - var self = this; - var options = util.createRequestOptions(self, { headers: { 'Content-Type': 'application/soap+xml' } }); - axios.get(this._url, options).then((response) => { - util.logReturnCorrelationId(this._log, 'Mex Get', response); - - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'Mex Get' + ' request returned http error: ' + response.status + ' and server response: ' + response.status;; - callback(this._log.createError(returnErrorString, true), response.data); - } - - // Success case: status >= 200 && < 300 - try { - self._mexDoc = response.data; - var options = { - errorHandler : self._log.error - }; - self._dom = new DOMParser(options).parseFromString(self._mexDoc); - self._parse(callback); - return; - } catch (err) { - self._log.error('Failed to parse mex response in to DOM', err, true); - callback(err); - } - }).catch((error) => { - // status >= 400: error case - if (error.response) { - this._log.error('Mex Get' + ' request failed with', error.response.status, true); - util.logReturnCorrelationId(this._log, 'Mex Get', error.response); - var returnErrorString = 'Mex Get' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data);; - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('Mex Get' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else { - this._log.error('Mex Get' + ' request was never made, please check', error.message, true); - callback(error.message); - } - }); -}; - -var TRANSPORT_BINDING_XPATH = 'wsp:ExactlyOne/wsp:All/sp:TransportBinding'; -var TRANSPORT_BINDING_2005_XPATH = 'wsp:ExactlyOne/wsp:All/sp2005:TransportBinding'; -/** -* Checks a DOM policy node that is a potentialy appplicable username password policy -* to ensure that it has the correct transport. -* @private -* @param {object} policyNode The policy node to check. -* @returns {string} If the policy matches the desired transport then the id of the policy is returned. -* If not then null is returned. -*/ -Mex.prototype._checkPolicy = function(policyNode) { - var policyId = null; - var id = policyNode.getAttributeNS(Namespaces.wsu, 'Id'); - var transportBindingNodes = select(policyNode, TRANSPORT_BINDING_XPATH); - if (0 === transportBindingNodes.length) { - transportBindingNodes = select(policyNode, TRANSPORT_BINDING_2005_XPATH); - } - if (0 !== transportBindingNodes.length) { - if (id) { - policyId = id; - } - } - if (policyId) { - this._log.verbose('found matching policy id'); - this._log.verbose('found matching policy id: ' + policyId, true); - } else { - if (!id) { - id = ''; - } - this._log.verbose('potential policy did not match required transport binding'); - this._log.verbose('potential policy did not match required transport binding: ' + id, true); - } - return policyId; -}; - -/** -* Finds all username password policies within the mex document. -* @private -* @param xpath The xpath expression for selecting username token nodes. -* @returns {object} A map object that contains objects containing the id of username password polices. -*/ -Mex.prototype._selectUsernamePasswordPolicies = function(xpath) { - var policies = {}; - var usernameTokenNodes = select(this._dom, xpath); - if (!usernameTokenNodes.length) { - this._log.warn('no username token policy nodes found'); - return; - } - for (var i=0; i < usernameTokenNodes.length; i++) { - var policyNode = usernameTokenNodes[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode; - var id = this._checkPolicy(policyNode); - if (id) { - var idRef = '#' + id; - policies[idRef] = { id : idRef }; - } - } - return _.isEmpty(policies) ? null : policies; -}; - -var SOAP_ACTION_XPATH = 'wsdl:operation/soap12:operation/@soapAction'; -var RST_SOAP_ACTION_13 = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; -var RST_SOAP_ACTION_2005 = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'; -var SOAP_TRANSPORT_XPATH = 'soap12:binding/@transport'; -var SOAP_HTTP_TRANSPORT_VALUE = 'http://schemas.xmlsoap.org/soap/http'; -/** -* Given a DOM binding node determines whether it matches the correct soap action and transport. -* @private -* @param {object} bindingNode The DOM node to check. -* @returns {bool} -*/ -Mex.prototype._checkSoapActionAndTransport = function(bindingNode) { - var soapTransportAttributes; - var soapAction; - var soapTransport; - var bindingName = bindingNode.getAttribute('name'); - var soapActionAttributes = select(bindingNode, SOAP_ACTION_XPATH); - if (soapActionAttributes.length) { - soapAction = soapActionAttributes[0].value; - soapTransportAttributes = select(bindingNode, SOAP_TRANSPORT_XPATH); - } - if (soapTransportAttributes.length) { - soapTransport = soapTransportAttributes[0].value; - } - - if (soapTransport === SOAP_HTTP_TRANSPORT_VALUE) { - if (soapAction === RST_SOAP_ACTION_13) { - this._log.verbose('foud binding matching Action and Transport: ' + bindingName); - return WSTrustVersion.WSTRUST13; - } - else if (soapAction === RST_SOAP_ACTION_2005) { - this._log.verbose('found binding matching Action and Transport: ' + bindingName); - return WSTrustVersion.WSTRUST2005; - } - } - - this._log.verbose('binding node did not match soap Action or Transport: ' + bindingName); - return WSTrustVersion.UNDEFINED; -}; - -/** -* Given a map with policy id keys, finds the bindings in the mex document that are linked to thos policies. -* @private -* @param {object} policies A map with policy id keys. -* @returns {object} a map of bindings id's to policy id's. -*/ -Mex.prototype._getMatchingBindings = function(policies) { - var bindings = {}; - var bindingPolicyRefNodes = select(this._dom, '//wsdl:definitions/wsdl:binding/wsp:PolicyReference'); - for (var i=0; i < bindingPolicyRefNodes.length; i++) { - var node = bindingPolicyRefNodes[i]; - var uri = node.getAttribute('URI'); - var policy = policies[uri]; - if (policy) { - var bindingNode = node.parentNode; - var bindingName = bindingNode.getAttribute('name'); - var version = this._checkSoapActionAndTransport(bindingNode); - if (version !== WSTrustVersion.UNDEFINED) { - var bindingPolicy = {}; - bindingPolicy.url = uri; - bindingPolicy.version = version; - - bindings[bindingName] = bindingPolicy; - } - } - } - return _.isEmpty(bindings) ? null : bindings; -}; - -/** -* Ensures that a url points to an SSL endpoint. -* @private -* @param {string} endpointUrl The url to check. -* @returns {bool} -*/ -Mex.prototype._urlIsSecure = function(endpointUrl) { - var parsedUrl = url.parse(endpointUrl); - return parsedUrl.protocol === 'https:'; -}; - -var PORT_XPATH = '//wsdl:definitions/wsdl:service/wsdl:port'; -var ADDRESS_XPATH = 'wsa10:EndpointReference/wsa10:Address'; -/** -* Finds all of the wsdl ports in the mex document that are associated with username password policies. Augments -* the passed in bindings with the endpoint url of the correct port. -* @private -* @param {object} bindings A map of binding id's to policy id's. -*/ -Mex.prototype._getPortsForPolicyBindings = function(bindings, policies) { - var portNodes = select(this._dom, PORT_XPATH); - if (0 === portNodes.length) { - this._log.warning('no ports found'); - } - for (var i=0; i < portNodes.length; i++) { - var portNode = portNodes[i]; - var bindingId = portNode.getAttribute('binding'); - - // Clear any prefix - var bindingIdParts = bindingId.split(':'); - bindingId = bindingIdParts[bindingIdParts.length - 1]; - - var trustPolicy = bindings[bindingId]; - if (trustPolicy) { - var bindingPolicy = policies[trustPolicy.url]; - - if (bindingPolicy && !bindingPolicy.url) { - bindingPolicy.version = trustPolicy.version; - var addressNode = select(portNode, ADDRESS_XPATH); - if (0 === addressNode) { - throw this._log.createError('no address nodes on port.'); - } - var address = xmlutil.findElementText(addressNode[0]); - if (this._urlIsSecure(address)) { - bindingPolicy.url = address; - } else { - this._log.warn('skipping insecure endpoint: ' + address); - } - } - } - } -}; - -/** -* Given a list of username password policies chooses one of them at random as the policy chosen by this Mex instance. -* @private -* @param {object} policies A map of policy id's to an object containing username password ws-trust endpoint addresses. -*/ -Mex.prototype._selectSingleMatchingPolicy = function(policies) { - // if both wstrust13 and wstrust2005 policy exists, then choose wstrust13, otherwise choose whatever exists. - var matchingPolicies = _.filter(policies, function(policy) { return policy.url ? true : false; }); - if (!matchingPolicies) { - this._log.warn('no policies found with an url'); - return; - } - - var wstrust13Policy = null, wstrust2005Policy = null; - for(var i = 0; i < matchingPolicies.length; ++i) { - var matchingPolicy = matchingPolicies[i]; - if (WSTrustVersion.WSTRUST13 === matchingPolicy.version) { - wstrust13Policy = matchingPolicy; - } - else if (WSTrustVersion.WSTRUST2005 === matchingPolicy.version) { - wstrust2005Policy = matchingPolicy; - } - } - - if (!wstrust13Policy && !wstrust2005Policy) { - this._log.warn('no policies found with an url'); - this._usernamePasswordPolicy = null; - return; - } - - this._usernamePasswordPolicy = wstrust13Policy ? wstrust13Policy : wstrust2005Policy; -}; - -/** -* Parses the mex document previously retrieved. -* @private -* @param {Mex.DiscoverCallback} callback -*/ -Mex.prototype._parse = function(callback) { - var self = this; - var xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp:SignedEncryptedSupportingTokens/wsp:Policy/sp:UsernameToken/wsp:Policy/sp:WssUsernameToken10'; - var policies = self._selectUsernamePasswordPolicies(xpathExpression); - - xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp2005:SignedSupportingTokens/wsp:Policy/sp2005:UsernameToken/wsp:Policy/sp2005:WssUsernameToken10'; - - if (policies) { - _.extend(policies, self._selectUsernamePasswordPolicies(xpathExpression)); - } - else { - policies = self._selectUsernamePasswordPolicies(xpathExpression); - } - - if (!policies) { - callback(self._log.createError('No matching policies')); - return; - } - var bindings = self._getMatchingBindings(policies); - if (!bindings) { - callback(self._log.createError('No matching bindings')); - return; - } - self._getPortsForPolicyBindings(bindings, policies); - self._selectSingleMatchingPolicy(policies); - var err = this._url ? undefined : this._log.createError('No ws-trust endpoints match requirements.'); - callback(err); -}; - -module.exports = Mex; +// 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. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + + +module.exports = Transform; + +var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + +var Duplex = __nccwpck_require__(13928); + +__nccwpck_require__(44124)(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. + + +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. + + +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} /***/ }), -/***/ 41602: +/***/ 58729: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var _ = __nccwpck_require__(83571); -__nccwpck_require__(1693); // Adds a number of convenience methods to the builtin Date object. -var querystring = __nccwpck_require__(71191); -var uuid = __nccwpck_require__(19744); -var axios = __nccwpck_require__(96545); -var url = __nccwpck_require__(78835); -var async = __nccwpck_require__(57888); - -var constants = __nccwpck_require__(10282); -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); - -var OAuth2Parameters = constants.OAuth2.Parameters; -var OAuth2ResponseParameters = constants.OAuth2.ResponseParameters; -var DeviceCodeResponseParameters = constants.OAuth2.DeviceCodeResponseParameters; -var IdTokenMap = constants.OAuth2.IdTokenMap; -var TokenResponseFields = constants.TokenResponseFields; -var UserCodeResponseFields = constants.UserCodeResponseFields; -var IdTokenFields = constants.IdTokenFields; - -var TOKEN_RESPONSE_MAP = {}; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.TOKEN_TYPE] = TokenResponseFields.TOKEN_TYPE; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ACCESS_TOKEN] = TokenResponseFields.ACCESS_TOKEN; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.REFRESH_TOKEN] = TokenResponseFields.REFRESH_TOKEN; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.CREATED_ON] = TokenResponseFields.CREATED_ON; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_ON] = TokenResponseFields.EXPIRES_ON; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_IN] = TokenResponseFields.EXPIRES_IN; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.RESOURCE] = TokenResponseFields.RESOURCE; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR] = TokenResponseFields.ERROR; -TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR_DESCRIPTION] = TokenResponseFields.ERROR_DESCRIPTION; - - -var DEVICE_CODE_RESPONSE_MAP = {}; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.DEVICE_CODE] = UserCodeResponseFields.DEVICE_CODE; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.USER_CODE] = UserCodeResponseFields.USER_CODE; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.VERIFICATION_URL] = UserCodeResponseFields.VERIFICATION_URL; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.INTERVAL] = UserCodeResponseFields.INTERVAL; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.EXPIRES_IN] = UserCodeResponseFields.EXPIRES_IN; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.MESSAGE] = UserCodeResponseFields.MESSAGE; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR] = UserCodeResponseFields.ERROR; -DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR_DESCRIPTION] = UserCodeResponseFields.ERROR_DESCRIPTION; - -/** - * Constructs an instances of OAuth2Client - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {string|url} authority An url that points to an authority. - */ -function OAuth2Client(callContext, authority) { - this._aadApiVersion = authority.aadApiVersion === undefined? '1.0' : authority.aadApiVersion; - this._tokenEndpoint = authority.tokenEndpoint; - this._deviceCodeEndpoint = authority.deviceCodeEndpoint; - - this._log = new Logger('OAuth2Client', callContext._logContext); - this._callContext = callContext; - this._cancelPollingRequest = false; -} - -/** - * Constructs an OAuth 2.0 token request url. - * @private - * @return {URL} - */ -OAuth2Client.prototype._createTokenUrl = function () { - var tokenUrl = url.parse(this._tokenEndpoint); - - var parameters = {}; - parameters[OAuth2Parameters.AAD_API_VERSION] = this._aadApiVersion; - - tokenUrl.search = querystring.stringify(parameters); - return tokenUrl; -}; - -/** - * Constructs the user code info request url. - * @private - * @return {URL} - */ -OAuth2Client.prototype._createDeviceCodeUrl = function () { - var deviceCodeUrl = url.parse(this._deviceCodeEndpoint); - - var parameters = {}; - parameters[OAuth2Parameters.AAD_API_VERSION] = this._aadApiVersion; - - deviceCodeUrl.search = querystring.stringify(parameters); - - return deviceCodeUrl; -}; - -/** - * @private - * @param {object} obj An object in which integer values may reside. - * @param {array} keys An array of strings that specify keys in which integers may need parsing. - */ -OAuth2Client.prototype._parseOptionalInts = function (obj, keys) { - var self = this; - keys.forEach(function(element) { - if (_.has(obj, element)) { - obj[element] = parseInt(obj[element], 10); - if (isNaN(obj[element])) { - throw self._log.createError(element + ' could not be parsed as an int.'); - } - } - }); -}; - -/** - * Parses a JWS encoded JWT into it's three parts. - * @param {string} jwtToken The token to parse. - * @return {object} The three JWS parts, header, JWSPayload, and JWSSig, or undefined. - */ -OAuth2Client.prototype._crackJwt = function(jwtToken) { - var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; - - var matches = idTokenPartsRegex.exec(jwtToken); - if (!matches || matches.length < 4) { - this._log.warn('The returned id_token is not parseable.'); - return; - } - - var crackedToken = { - header : matches[1], - JWSPayload : matches[2], - JWSSig : matches[3] - }; - - return crackedToken; -}; - -/** - * Finds the value that should be used as the userId value. - * @param {object} idToken The id token that parsed. - * @returns {object} An object with a userId field and maybe a userIdIsDisplayable field. - */ -OAuth2Client.prototype._getUserId = function(idToken) { - var userId; - var isDisplayable; - - if (idToken.upn) { - userId = idToken.upn; - isDisplayable = true; - } else if (idToken.email) { - userId = idToken.email; - isDisplayable = true; - } else if (idToken.sub) { - userId = idToken.sub; - } - - if (!userId) { - // generate a random GUID. - userId = uuid.v4(); - } - - var userIdVals = {}; - userIdVals[IdTokenFields.USER_ID] = userId; - if (isDisplayable) { - userIdVals[IdTokenFields.IS_USER_ID_DISPLAYABLE] = true; - } - - return userIdVals; -}; - -function mapFields(inObj, outObj, map) { - for (var key in inObj) { - if (map[key]) { - var mappedKey = map[key]; - outObj[mappedKey] = inObj[key]; - } - } -} - -/** - * Given a decoded id token off the wire, this function extracts the values that - * ADAL commonly returns to callers and translates the names to more user - * friendly names. - * @param {Object} idToken A decoded id token. - * @return {Object} The set of extracted values with their new names. - */ -OAuth2Client.prototype._extractIdTokenValues = function(idToken) { - var extractedValues = {}; - _.extend(extractedValues, this._getUserId(idToken)); - - mapFields(idToken, extractedValues, IdTokenMap); - - return extractedValues; -}; - -/** - * Parses the value of the id_token OAuth 2 Reponse. - * @param {string} encodedIdToken An unencrypted JWT token. - * @return {object} returns the decoded id_token or undefined. - */ -OAuth2Client.prototype._parseIdToken = function(encodedIdToken) { - var crackedToken = this._crackJwt(encodedIdToken); - if (!crackedToken) { - return; - } - - var idToken; - try { - var base64IdToken = crackedToken.JWSPayload; - var base64Decoded = util.base64DecodeStringUrlSafe(base64IdToken); - if (!base64Decoded) { - this._log.warn('The returned id_token could not be base64 url safe decoded.'); - return; - } - - idToken = JSON.parse(base64Decoded); - } catch (err) { - this._log.warn('the returned id_token could not be decoded'); - this._log.warn('The returned id_token could not be decoded: ' + err.stack, true); - return; - } - - return this._extractIdTokenValues(idToken); -}; - -/** - * Validates the response returned from an OAuth 2.0 token request. - * @private - * @param {string} body The response as a string encoded JSON object. - * @return {object} The parsed response. - */ -OAuth2Client.prototype._validateTokenResponse = function (body) { - var wireResponse; - var tokenResponse = {}; - - try { - wireResponse = body; - } catch(e) { - throw new Error('The token response returned from the server is unparseable as JSON'); - } - - var intKeys = [ - OAuth2ResponseParameters.EXPIRES_ON, - OAuth2ResponseParameters.EXPIRES_IN, - OAuth2ResponseParameters.CREATED_ON - ]; - - this._parseOptionalInts(wireResponse, intKeys); - - if (wireResponse[OAuth2ResponseParameters.EXPIRES_IN]) { - var expiresIn = wireResponse[OAuth2ResponseParameters.EXPIRES_IN]; - var now = new Date(); - wireResponse[OAuth2ResponseParameters.EXPIRES_ON] = now.add( { seconds : expiresIn }); - } - - if (wireResponse[OAuth2ResponseParameters.CREATED_ON]) { - var tempDate = new Date(); - var createdOn = wireResponse[OAuth2ResponseParameters.CREATED_ON]; - tempDate.setTime(createdOn); - wireResponse[OAuth2ResponseParameters.CREATED_ON] = tempDate; - } - - if (!wireResponse[OAuth2ResponseParameters.TOKEN_TYPE]) { - throw this._log.createError('wireResponse is missing token_type'); - } - if (!wireResponse[OAuth2ResponseParameters.ACCESS_TOKEN]) { - throw this._log.createError('wireResponse missing access_token'); - } - - mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); - - if (wireResponse[OAuth2ResponseParameters.ID_TOKEN]) { - var idToken = this._parseIdToken(wireResponse[OAuth2ResponseParameters.ID_TOKEN]); - if (idToken) { - _.extend(tokenResponse, idToken); - } - } - - return tokenResponse; -}; - -/** - * Validates the response returned from an OAuth 2.0 device code request. - * @private - * @param {string} body The response as a string encoded JSON object. - * @return {object} The parsed response. - */ -OAuth2Client.prototype._validateDeviceCodeResponse = function(body) { - var wireResponse; - var deviceCodeResponse = {}; - - try { - wireResponse = body; - } catch(e) { - throw new Error('The device code response returned from the server is unparseable as JSON.'); - } - - var intKeys = [ - DeviceCodeResponseParameters.EXPIRES_IN, - DeviceCodeResponseParameters.INTERVAL - ]; - - this._parseOptionalInts(wireResponse, intKeys); - - if (!wireResponse[DeviceCodeResponseParameters.EXPIRES_IN]){ - throw this._log.createError('wireResponse is missing expires_in'); - } - - if (!wireResponse[DeviceCodeResponseParameters.DEVICE_CODE]) { - throw this._log.createError('wireResponse is missing device code'); - } - - if (!wireResponse[DeviceCodeResponseParameters.USER_CODE]) { - throw this._log.createError('wireResponse is missing user code'); - } - - mapFields(wireResponse, deviceCodeResponse, DEVICE_CODE_RESPONSE_MAP); - - return deviceCodeResponse; -}; - -/** - * @private - * @param {string} body The body of a http token response. - */ -OAuth2Client.prototype._handlePollingResponse = function(body) { - //handle token error response - var tokenResponse = this._handlePollingRequestErrorResponse(body); - if (_.isEmpty(tokenResponse)){ - tokenResponse = this._validateTokenResponse(body); - } - - return tokenResponse; -}; - -/** - * @private - * @param {string} body The body of a http token response. - */ -OAuth2Client.prototype._handlePollingRequestErrorResponse = function(body) { - var wireResponse; - var tokenResponse = {}; - - try { - wireResponse = body; - } catch (e) { - throw new Error ('The token response returned from the server is unparsable as JSON'); - } - - if (wireResponse[OAuth2ResponseParameters.ERROR]) { - mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); - } - - return tokenResponse; -}; - -/** - * @private - * @param {object} response An http response object. - * @param {string} body The body of a http token response. - * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed - * into this function. - */ -OAuth2Client.prototype._handleGetTokenResponse = function(body, callback) { - var tokenResponse; - try { - tokenResponse = this._validateTokenResponse(body); - } catch (e) { - this._log.error('Error validating get token response', e, true); - callback(e); - return; - } - callback(null, tokenResponse); -}; - -OAuth2Client.prototype._handleGetDeviceCodeResponse = function(body, callback) { - var deviceCodeResponse; - try { - deviceCodeResponse = this._validateDeviceCodeResponse(body); - } catch (e) { - this._log.error('Error validating get user code response', e, true); - callback(e); - return; - } - - callback(null, deviceCodeResponse); -}; - -OAuth2Client.prototype._getTokenWithPolling = function (postOptions, callback) { - var self = this; - if (self._cancelPollingRequest === true) { - callback(null, new Error('Polling_Request_Cancelled')); - return; - } - - axios(postOptions).then((response) => { - var tokenResponse; - util.logReturnCorrelationId(this._log, 'GetToken', response); - try { - tokenResponse = self._handlePollingResponse(response.data); - } catch (e) { - self._log.error('Error validating get token response', e, true); - callback(null, e); - return; - } - callback(null, tokenResponse); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'GetToken', error.response); - // error response callback, for error response, it's already parsed as Json. - if (error.response && error.response.data.hasOwnProperty(TokenResponseFields.ERROR) && error.response.data[TokenResponseFields.ERROR] === 'authorization_pending') { - callback(new Error(error.response.data[TokenResponseFields.ERROR]), error.response.data); - } - } - // if there is no response from the server - else if (error.request) { - self._log.error('GetToken' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else if (error.message) { - self._log.error('GetToken http get failed.' + ' request was never made, please check', error.message, true); - callback(error.message); - } - // unknown error - else { - self._log.error('GetToken' + ' failed with unknown error', "unknown error", true); - callback(self._log.createError('failed with an unknown error')); - } - }); -}; - -OAuth2Client.prototype._createPostOption = function (postUrl, urlEncodedRequestForm) { - - var postOptions = util.createRequestOptions( - this, - { - method : 'POST', - url : url.format(postUrl), - data : urlEncodedRequestForm, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - maxRedirects: 0, - encoding: 'utf8', - } - ); - - return postOptions; -}; - -/** - * @callback GetTokenCallback - * @memberOf OAuth2Client - * @param {Error} [error] In case of an error this will hold the associated Error object. - * @param {TokenResponse} tokenResponse Contains the parsed result of a get token request. - */ - -/** -* @param {object} oauthParameters An object whose keys come from -* Constants.OAuth2.Parameters -* @param {OAuth2Client.GetTokenCallback} callback The callback function. -*/ -OAuth2Client.prototype.getToken = function(oauthParameters, callback) { - var self = this; - var tokenUrl = self._createTokenUrl(); - - var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); - var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); - - axios(postOptions).then((response) => { - util.logReturnCorrelationId(this._log, 'Get Token', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'Get Token' + ' request returned http error: ' + response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - self._handleGetTokenResponse(response.data, callback); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'Get Token', error.response); - this._log.error('Get Token' + ' request failed with', error.response.status, true); - var returnErrorString = 'Get Token' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('Get Token' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else if (error.message) { - this._log.error('Get Token' + ' request was never made, please check', error.message, true); - callback(error.message); - } - // unknown error - else { - self._log.error('GetToken' + ' failed with unknown error', "unknown error", true); - callback(self._log.createError('failed with an unknown error')); - } - }); -}; - -/** - * @param {object} oauthParameters An object whose keys come from - * Constants.OAuth2.Parameters - * @param {integer} refresh_interval The interval for polling request. - * @param {integer} exipres_in The timeout for polling request. - * @param {OAuth2Client.GetTokenCallback} callback The callback function. - */ -OAuth2Client.prototype.getTokenWithPolling = function(oauthParameters, refresh_interval, expires_in, callback){ - var self = this; - var maxTimesForRetry = Math.floor(expires_in / refresh_interval); - - var tokenUrl = self._createTokenUrl(); - var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); - var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); - - var optionsForRetry = {times: maxTimesForRetry, interval: refresh_interval * 1000}; - - async.retry(optionsForRetry, function(retryCallback, response) { - self._getTokenWithPolling(postOptions, retryCallback); - }, function(err, response) { - if (response && response instanceof Error) { - callback(response); - return; - } - else if (response && response.hasOwnProperty(DeviceCodeResponseParameters.ERROR)) { - callback(response); - return; - } - callback(err, response); - }); -}; - -OAuth2Client.prototype.getUserCodeInfo = function(oauthParameters, callback) { - // for now make it as a post request - var self = this; - var deviceCodeUrl = self._createDeviceCodeUrl(); - - var urlEncodedDeviceCodeRequestForm = querystring.stringify(oauthParameters); - - var postOptions = self._createPostOption(deviceCodeUrl, urlEncodedDeviceCodeRequestForm); - - axios(postOptions).then((response) => { - util.logReturnCorrelationId(this._log, 'Get Device Code', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'Get Device Code' + ' request returned http error: ' + response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - self._handleGetDeviceCodeResponse(response.data, callback); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'Get Device Code', error.response); - this._log.error('Get Device Code' + ' request failed with', error.response.status, true); - var returnErrorString = 'Get Device Code' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('Get Device Code' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else if (error.message) { - this._log.error('Get Device Code' + ' request was never made, please check', error.message, true); - callback(error.message); - } - // unknown error - else { - self._log.error('Get Device Code' + ' failed with unknown error', "unknown error", true); - callback(self._log.createError('failed with an unknown error')); - } - }); - }; - -/** - * Cancel the polling request made for acquiring token by device code. - */ -OAuth2Client.prototype.cancelPollingRequest = function() { - this._cancelPollingRequest = true; -}; - -module.exports = OAuth2Client; +// 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. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. -/***/ }), +module.exports = Writable; +/* */ -/***/ 60772: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var jwtConstants = __nccwpck_require__(10282).Jwt; -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); - -__nccwpck_require__(1693); -var jws = __nccwpck_require__(4636); -var uuid = __nccwpck_require__(19744); - -/** - * JavaScript dates are in milliseconds, but JWT dates are in seconds. - * This function does the conversion. - * @param {Date} date - * @return {string} - */ -function dateGetTimeInSeconds(date) { - return Math.floor(date.getTime()/1000); -} - -/** - * Constructs a new SelfSignedJwt object. - * @param {object} callContext Context specific to this token request. - * @param {Authority} authority The authority to be used as the JWT audience. - * @param {string} clientId The client id of the calling app. - */ -function SelfSignedJwt(callContext, authority, clientId) { - this._log = new Logger('SelfSignedJwt', callContext._logContext); - this._callContext = callContext; - - this._authority = authority; - this._tokenEndpoint = authority.tokenEndpoint; - this._clientId = clientId; -} - -/** - * This wraps date creation in order to make unit testing easier. - * @return {Date} - */ -SelfSignedJwt.prototype._getDateNow = function() { - return new Date(); -}; - -SelfSignedJwt.prototype._getNewJwtId = function() { - return uuid.v4(); -}; - -/** - * A regular certificate thumbprint is a hex encode string of the binary certificate - * hash. For some reason teh x5t value in a JWT is a url save base64 encoded string - * instead. This function does the conversion. - * @param {string} thumbprint A hex encoded certificate thumbprint. - * @return {string} A url safe base64 encoded certificate thumbprint. - */ -SelfSignedJwt.prototype._createx5tValue = function(thumbprint) { - var hexString = thumbprint.replace(/:/g, '').replace(/ /g, ''); - var base64 = (new Buffer(hexString, 'hex')).toString('base64'); - return util.convertRegularToUrlSafeBase64EncodedString(base64); -}; - -/** - * Creates the JWT header. - * @param {string} thumbprint A hex encoded certificate thumbprint. - * @return {object} - */ -SelfSignedJwt.prototype._createHeader = function(thumbprint) { - var x5t = this._createx5tValue(thumbprint); - var header = { typ: 'JWT', alg: 'RS256', x5t : x5t }; - - this._log.verbose('Creating self signed JWT header'); - this._log.verbose('Creating self signed JWT header. x5t: ' + x5t, true); - - return header; -}; - -/** - * Creates the JWT payload. - * @return {object} - */ -SelfSignedJwt.prototype._createPayload = function() { - var now = this._getDateNow(); - var expires = (new Date(now.getTime())).addMinutes(jwtConstants.SELF_SIGNED_JWT_LIFETIME); - - this._log.verbose('Creating self signed JWT payload. Expires: ' + expires + ' NotBefore: ' + now); - - var jwtPayload = {}; - jwtPayload[jwtConstants.AUDIENCE] = this._tokenEndpoint; - jwtPayload[jwtConstants.ISSUER] = this._clientId; - jwtPayload[jwtConstants.SUBJECT] = this._clientId; - jwtPayload[jwtConstants.NOT_BEFORE] = dateGetTimeInSeconds(now); - jwtPayload[jwtConstants.EXPIRES_ON] = dateGetTimeInSeconds(expires); - jwtPayload[jwtConstants.JWT_ID] = this._getNewJwtId(); - - return jwtPayload; -}; - -SelfSignedJwt.prototype._throwOnInvalidJwtSignature = function(jwt) { - var jwtSegments = jwt.split('.'); - - if (3 > jwtSegments.length || !jwtSegments[2]) { - throw this._log.createError('Failed to sign JWT. This is most likely due to an invalid certificate.'); - } - - return; -}; - -SelfSignedJwt.prototype._signJwt = function(header, payload, certificate) { - var jwt; - try { - jwt = jws.sign({ header : header, payload : payload, secret : certificate }); - } - catch (err) { - this._log.error(err, true); - throw this._log.createError('Failed to sign JWT.This is most likely due to an invalid certificate.'); - } - - this._throwOnInvalidJwtSignature(jwt); - return jwt; -}; - -SelfSignedJwt.prototype._reduceThumbprint = function(thumbprint) { - var canonical = thumbprint.toLowerCase().replace(/ /g, '').replace(/:/g, ''); - this._throwOnInvalidThumbprint(canonical); - return canonical; -}; - -var numCharIn128BitHexString = 128/8*2; -var numCharIn160BitHexString = 160/8*2; -var thumbprintSizes = {}; -thumbprintSizes[numCharIn128BitHexString] = true; -thumbprintSizes[numCharIn160BitHexString] = true; -var thumbprintRegExp = /^[a-f\d]*$/; - -SelfSignedJwt.prototype._throwOnInvalidThumbprint = function(thumbprint) { - if (!thumbprintSizes[thumbprint.length] || !thumbprintRegExp.test(thumbprint)) { - throw this._log.createError('The thumbprint does not match a known format'); - } -}; - -/** - * Creates a self signed JWT that can be used as a client_assertion. - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint A hex encoded thumbprint of the certificate. - * @return {string} A self signed JWT token. - */ -SelfSignedJwt.prototype.create = function(certificate, thumbprint) { - thumbprint = this._reduceThumbprint(thumbprint); - var header = this._createHeader(thumbprint); - - var payload = this._createPayload(); - - var jwt = this._signJwt(header, payload, certificate); - return jwt; -}; - -module.exports = SelfSignedJwt; -/***/ }), +function CorkedRequest(state) { + var _this = this; -/***/ 21178: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.next = null; + this.entry = null; -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var constants = __nccwpck_require__(10282); -var CacheDriver = __nccwpck_require__(38289); -var Logger = __nccwpck_require__(92288).Logger; -var Mex = __nccwpck_require__(27078); -var OAuth2Client = __nccwpck_require__(41602); -var SelfSignedJwt = __nccwpck_require__(60772); -var UserRealm = __nccwpck_require__(58663); -var WSTrustRequest = __nccwpck_require__(39035); - -var OAuth2Parameters = constants.OAuth2.Parameters; -var TokenResponseFields = constants.TokenResponseFields; -var OAuth2GrantType = constants.OAuth2.GrantType; -var OAuth2Scope = constants.OAuth2.Scope; -var Saml = constants.Saml; -var AccountType = constants.UserRealm.AccountType; -var WSTrustVersion = constants.WSTrustVersion; -var DeviceCodeResponseParameters = constants.UserCodeResponseFields; - -/** - * Constructs a new TokenRequest object. - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {AuthenticationContext} authenticationContext - * @param {string} resource - * @param {string} clientId - * @param {string} redirectUri - */ -function TokenRequest(callContext, authenticationContext, clientId, resource, redirectUri) { - this._log = new Logger('TokenRequest', callContext._logContext); - this._callContext = callContext; - this._authenticationContext = authenticationContext; - this._resource = resource; - this._clientId = clientId; - this._redirectUri = redirectUri; - - // This should be set at the beginning of getToken - // functions that have a userId. - this._userId = null; - - this._userRealm = null; - this._pollingClient = {}; -} - -TokenRequest.prototype._createUserRealmRequest = function(username) { - return new UserRealm(this._callContext, username, this._authenticationContext.authority); -}; - -TokenRequest.prototype._createMex = function(mexEndpoint) { - return new Mex(this._callContext, mexEndpoint); -}; - -TokenRequest.prototype._createWSTrustRequest = function(wstrustEndpoint, appliesTo, wstrustEndpointVersion) { - return new WSTrustRequest(this._callContext, wstrustEndpoint, appliesTo, wstrustEndpointVersion); -}; - -TokenRequest.prototype._createOAuth2Client = function() { - return new OAuth2Client(this._callContext, this._authenticationContext._authority); -}; - -TokenRequest.prototype._createSelfSignedJwt = function() { - return new SelfSignedJwt(this._callContext, this._authenticationContext._authority, this._clientId); -}; - -TokenRequest.prototype._oauthGetToken = function(oauthParameters, callback) { - var client = this._createOAuth2Client(); - client.getToken(oauthParameters, callback); -}; - -TokenRequest.prototype._oauthGetTokenByPolling = function(oauthParameters, refresh_interval, expires_in, callback){ - var client = this._createOAuth2Client(); - client.getTokenWithPolling(oauthParameters, refresh_interval, expires_in, callback); - this._pollingClient = client; -} - -TokenRequest.prototype._createCacheDriver = function() { - return new CacheDriver( - this._callContext, - this._authenticationContext.authority, - this._resource, - this._clientId, - this._authenticationContext.cache, - this._getTokenWithTokenResponse.bind(this) - ); -}; - -/** - * Used by the cache driver to refresh tokens. - * @param {TokenResponse} entry A token response to refresh. - * @param {string} resource The resource for which to get the token. - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype._getTokenWithTokenResponse = function(entry, resource, callback) { - this._log.verbose('Called to refresh a token from the cache.'); - var refreshToken = entry[TokenResponseFields.REFRESH_TOKEN]; - this._getTokenWithRefreshToken(refreshToken, resource, null, callback); -}; - -TokenRequest.prototype._createCacheQuery = function() { - var query = { - clientId : this._clientId - }; - - if (this._userId) { - query.userId = this._userId; - } else { - this._log.verbose('No userId passed for cache query.'); - } - - return query; -}; - - -TokenRequest.prototype._getTokenWithCacheWrapper = function(callback, getTokenFunc) { - var self = this; - this._cacheDriver = this._createCacheDriver(); - var cacheQuery = this._createCacheQuery(); - this._cacheDriver.find(cacheQuery, function(err, token) { - if (err) { - self._log.warn('Attempt to look for token in cahce resulted in Error'); - self._log.warn('Attempt to look for token in cache resulted in Error: ' + err.stack, true); - } - - if (!token) { - self._log.verbose('No appropriate cached token found.'); - getTokenFunc.call(self, function(err, tokenResponse) { - if (err) { - self._log.verbose('getTokenFunc returned with err'); - callback(err, tokenResponse); - return; - } - - self._log.verbose('Successfully retrieved token from authority'); - self._cacheDriver.add(tokenResponse, function() { - callback(null, tokenResponse); - }); - }); - } else { - self._log.info('Returning cached token.'); - callback(err, token); - } - }); -}; - -/** - * Store token into cache. - * @param {object} tokenResponse Token response to be added into the cache. - */ -TokenRequest.prototype._addTokenIntoCache = function(tokenResponse, callback) { - this._cacheDriver = this._createCacheDriver(); - this._log.verbose('Storing retrieved token into cache'); - this._cacheDriver.add(tokenResponse, function(err) { - callback(err, tokenResponse); - }); -}; - -/** - * Adds an OAuth parameter to the paramters object if the parameter is - * not null or undefined. - * @private - * @param {object} parameters OAuth parameters object. - * @param {string} key A member of the OAuth2Parameters constants. - * @param {object} value - */ -function _addParameterIfAvailable(parameters, key, value) { - if (value) { - parameters[key] = value; - } -} - -/** - * Creates a set of basic, common, OAuthParameters based on values that the TokenRequest - * was created with. - * @private - * @param {string} grantType A member of the OAuth2GrantType constants. - * @return {object} - */ -TokenRequest.prototype._createOAuthParameters = function(grantType) { - var oauthParameters = {}; - oauthParameters[OAuth2Parameters.GRANT_TYPE] = grantType; - - if (OAuth2GrantType.AUTHORIZATION_CODE !== grantType && - OAuth2GrantType.CLIENT_CREDENTIALS !== grantType && - OAuth2GrantType.DEVICE_CODE != grantType) { - oauthParameters[OAuth2Parameters.SCOPE] = OAuth2Scope.OPENID; - } - - _addParameterIfAvailable(oauthParameters, OAuth2Parameters.CLIENT_ID, this._clientId); - _addParameterIfAvailable(oauthParameters, OAuth2Parameters.RESOURCE, this._resource); - _addParameterIfAvailable(oauthParameters, OAuth2Parameters.REDIRECT_URI, this._redirectUri); - - return oauthParameters; -}; - -/** - * Get's a token from AAD using a username and password - * @private - * @param {string} username - * @param {string} password - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype._getTokenUsernamePasswordManaged = function(username, password, callback) { - this._log.verbose('Acquiring token with username password for managed user'); - - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.PASSWORD); - - oauthParameters[OAuth2Parameters.PASSWORD] = password; - oauthParameters[OAuth2Parameters.USERNAME] = username; - - this._oauthGetToken(oauthParameters, callback); -}; - -/** - * Determines the OAuth SAML grant type to use based on the passed in TokenType - * that was returned from a RSTR. - * @param {string} wstrustResponse RSTR token type. - * @return {string} An OAuth grant type. - */ -TokenRequest.prototype._getSamlGrantType = function(wstrustResponse) { - var tokenType = wstrustResponse.tokenType; - switch (tokenType) { - case Saml.TokenTypeV1: - return OAuth2GrantType.SAML1; - case Saml.TokenTypeV2: - return OAuth2GrantType.SAML2; - default: - throw this._log.createError('RSTR returned unknown token type: ' + tokenType); - } -}; - -/** - * Performs an OAuth SAML Assertion grant type exchange. Uses a SAML token as the credential for getting - * an OAuth access token. - * @param {WSTrustResponse} wstrustResponse A response from a WSTrustRequest - * @param {AcquireTokenCallback} callback callback - */ -TokenRequest.prototype._performWSTrustAssertionOAuthExchange = function(wstrustResponse, callback) { - this._log.verbose('Performing OAuth assertion grant type exchange.'); - - var oauthParameters; - try { - var grantType = this._getSamlGrantType(wstrustResponse); - var assertion = new Buffer(wstrustResponse.token).toString('base64'); - oauthParameters = this._createOAuthParameters(grantType); - oauthParameters[OAuth2Parameters.ASSERTION] = assertion; - } catch (err) { - callback(err); - return; - } - - this._oauthGetToken(oauthParameters, callback); -}; - -/** - * Exchange a username and password for a SAML token from an ADFS instance via WSTrust. - * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint. - * @param {string} wstrustEndpointVersion The version of the wstrust endpoint. - * @param {string} username username - * @param {string} password password - * @param {AcquireTokenCallback} callback callback - */ -TokenRequest.prototype._performWSTrustExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) { - var self = this; - var wstrust = this._createWSTrustRequest(wstrustEndpoint, 'urn:federation:MicrosoftOnline', wstrustEndpointVersion); - wstrust.acquireToken(username, password, function(rstErr, response) { - if (rstErr) { - callback(rstErr); - return; - } - - if (!response.token) { - var rstrErr = self._log.createError('Unsucessful RSTR.\n\terror code: ' + response.errorCode + '\n\tfaultMessage: ' + response.faultMessage, true); - callback(rstrErr); - return; - } - - callback(null, response); - }); -}; - -/** - * Given a username and password this method invokes a WSTrust and OAuth exchange to get an access token. - * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint. - * @param {string} username username - * @param {string} password password - * @param {AcquireTokenCallback} callback callback - */ -TokenRequest.prototype._performUsernamePasswordForAccessTokenExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) { - var self = this; - this._performWSTrustExchange(wstrustEndpoint, wstrustEndpointVersion, username, password, function(err, wstrustResponse) { - if (err) { - callback(err); - return; - } - - self._performWSTrustAssertionOAuthExchange(wstrustResponse, callback); - }); -}; - -/** - * Returns an Error object indicating that AAD did not return a WSTrust endpoint. - * @return {Error} - */ -TokenRequest.prototype._createADWSTrustEndpointError = function() { - return this._log.createError('AAD did not return a WSTrust endpoint. Unable to proceed.'); -}; - -/** - * Gets an OAuth access token using a username and password via a federated ADFS instance. - * @param {string} username username - * @param {string} password password - * @param {AcquireTokenCallback} callback callback - */ -TokenRequest.prototype._getTokenUsernamePasswordFederated = function(username, password, callback) { - this._log.verbose('Acquiring token with username password for federated user'); - - var self = this; - if (!this._userRealm.federationMetadataUrl) { - this._log.warn('Unable to retrieve federationMetadataUrl from AAD. Attempting fallback to AAD supplied endpoint.'); - - if (!this._userRealm.federationActiveAuthUrl) { - callback(this._createADWSTrustEndpointError()); - return; - } - - var wstrustVersion = this._parseWStrustVersionFromFederationActiveAuthUrl(this._userRealm.federationActiveAuthUrl); - this._log.verbose('Wstrust endpoint version is: ' + wstrustVersion); - this._performUsernamePasswordForAccessTokenExchange(this._userRealm.federationActiveAuthUrl, wstrustVersion, username, password, callback); - return; - } else { - var mexEndpoint = this._userRealm.federationMetadataUrl; - this._log.verbose('Attempting mex'); - this._log.verbose('Attempting mex at: ' + mexEndpoint, true); - var mex = this._createMex(mexEndpoint); - mex.discover(function(mexErr) { - var wstrustEndpoint; - wstrustVersion = WSTrustVersion.UNDEFINED; - if (mexErr) { - self._log.warn('MEX exchange failed. Attempting fallback to AAD supplied endpoint.'); - - wstrustEndpoint = self._userRealm.federationActiveAuthUrl; - wstrustVersion = self._parseWStrustVersionFromFederationActiveAuthUrl(self._userRealm.federationActiveAuthUrl); - if (!wstrustEndpoint) { - callback(self._createADWSTrustEndpointError()); - return; - } - } else { - wstrustEndpoint = mex.usernamePasswordPolicy.url; - wstrustVersion = mex.usernamePasswordPolicy.version; - } - - self._performUsernamePasswordForAccessTokenExchange(wstrustEndpoint, wstrustVersion, username, password, callback); - return; - }); - } -}; - -/** - * Gets wstrust endpoint version from the federation active auth url. - * @private - * @param {string} federationActiveAuthUrl federationActiveAuthUrl - * @return {object} The wstrust endpoint version. - */ -TokenRequest.prototype._parseWStrustVersionFromFederationActiveAuthUrl = function(federationActiveAuthUrl) { - var wstrust2005Regex = /[/trust]?[2005][/usernamemixed]?/; - var wstrust13Regex = /[/trust]?[13][/usernamemixed]?/; - - if (wstrust2005Regex.exec(federationActiveAuthUrl)) { - return WSTrustVersion.WSTRUST2005; - } - else if (wstrust13Regex.exec(federationActiveAuthUrl)) { - return WSTrustVersion.WSTRUST13; - } - - return WSTrustVersion.UNDEFINED; -}; - -/** - * Decides whether the username represents a managed or a federated user and then - * obtains a token using the appropriate protocol flow. - * @private - * @param {string} username - * @param {string} password - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithUsernamePassword = function(username, password, callback) { - this._log.info('Acquiring token with username password'); - this._userId = username; - - this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { - var self = this; - - if(this._authenticationContext._authority._isAdfsAuthority) { - this._log.info('Skipping user realm discovery for ADFS authority'); - - self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback); - return; - } - - this._userRealm = this._createUserRealmRequest(username); - this._userRealm.discover(function(err) { - if (err) { - getTokenCompleteCallback(err); - return; - } - - switch(self._userRealm.accountType) { - case AccountType.Managed: - self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback); - return; - case AccountType.Federated: - self._getTokenUsernamePasswordFederated(username, password, getTokenCompleteCallback); - return; - default: - getTokenCompleteCallback(self._log.createError('Server returned an unknown AccountType: ' + self._userRealm.AccountType)); - } - }); - }); -}; - -/** - * Obtains a token using client credentials - * @private - * @param {string} clientSecret - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithClientCredentials = function(clientSecret, callback) { - this._log.info('Getting token with client credentials.'); - - this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS); - - oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; - - this._oauthGetToken(oauthParameters, getTokenCompleteCallback); - }); -}; - -/** - * Obtains a token using an authorization code. - * @private - * @param {string} authorizationCode - * @param {string} clientSecret - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithAuthorizationCode = function(authorizationCode, clientSecret, callback) { - this._log.info('Getting token with auth code.'); - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.AUTHORIZATION_CODE); - - oauthParameters[OAuth2Parameters.CODE] = authorizationCode; - oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; - - this._oauthGetToken(oauthParameters, callback); -}; - -/** - * Obtains a token using a refresh token. - * @param {string} refreshToken - * @param {string} resource - * @param {string} [clientSecret] - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype._getTokenWithRefreshToken = function(refreshToken, resource, clientSecret, callback) { - this._log.info('Getting a new token from a refresh token.'); - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.REFRESH_TOKEN); - - if (resource) { - oauthParameters[OAuth2Parameters.RESOURCE] = resource; - } - - if (clientSecret) { - oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret; - } - - oauthParameters[OAuth2Parameters.REFRESH_TOKEN] = refreshToken; - - this._oauthGetToken(oauthParameters, callback); -}; - -/** - * Obtains a token using a refresh token. - * @param {string} refreshToken - * @param {string} [clientSecret] - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithRefreshToken = function(refreshToken, clientSecret, callback) { - this._getTokenWithRefreshToken(refreshToken, null, clientSecret, callback); -}; - -/** - * Obtains a token from the cache, refreshing it or using a MRRT if necessary. - * @param {string} [userId] The user associated with the cached token. - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenFromCacheWithRefresh = function(userId, callback) { - var self = this; - this._log.info('Getting token from cache with refresh if necessary.'); - - this._userId = userId; - this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { - // If this method was called then no cached entry was found. Since - // this particular version of acquireToken can only retrieve tokens - // from the cache, return an error. - getTokenCompleteCallback(self._log.createError('Entry not found in cache.')); - }); -}; - -/** - * Creates a self signed jwt. - * @param {string} authorityUrl - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint - * @return {string} A self signed JWT - */ -TokenRequest.prototype._createJwt = function(authorityUrl, certificate, thumbprint) { - var jwt; - var ssj = this._createSelfSignedJwt(); - jwt = ssj.create(certificate, thumbprint); - if (!jwt) { - throw this._log.createError('Failed to create JWT'); - } - - return jwt; -}; - -/** - * Obtains a token via a certificate. The certificate is used to generate a self signed - * JWT token that is passed as a client_assertion. - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint A hex encoded thumbprint of the certificate. - * @param {AcquireTokenCallback} callback - */ -TokenRequest.prototype.getTokenWithCertificate = function(certificate, thumbprint, callback) { - - this._log.info('Getting a token via certificate.'); - - var authorityUrl = this._authenticationContext._authority; - - var jwt; - try { - jwt = this._createJwt(authorityUrl, certificate, thumbprint); - } catch (err) { - callback(err); - return; - } - - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS); - oauthParameters[OAuth2Parameters.CLIENT_ASSERTION_TYPE] = OAuth2GrantType.JWT_BEARER; - oauthParameters[OAuth2Parameters.CLIENT_ASSERTION] = jwt; - - this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) { - this._oauthGetToken(oauthParameters, getTokenCompleteCallback); - }); -}; - -TokenRequest.prototype.getTokenWithDeviceCode = function(userCodeInfo, callback) { - this._log.info('Getting a token via device code'); - var self = this; - - var oauthParameters = this._createOAuthParameters(OAuth2GrantType.DEVICE_CODE); - oauthParameters[OAuth2Parameters.CODE] = userCodeInfo[DeviceCodeResponseParameters.DEVICE_CODE]; - - var interval = userCodeInfo[DeviceCodeResponseParameters.INTERVAL]; - var expires_in = userCodeInfo[DeviceCodeResponseParameters.EXPIRES_IN]; - - if (interval <= 0) { - callback(new Error('invalid refresh interval')); - return; - } - - this._oauthGetTokenByPolling(oauthParameters, interval, expires_in, function(err, tokenResponse) { - if (err) { - self._log.verbose('Token polling request returend with err.'); - callback(err, tokenResponse); - } - else { - self._addTokenIntoCache(tokenResponse, callback); - } - }); -}; - -TokenRequest.prototype.cancelTokenRequestWithDeviceCode = function() { - this._pollingClient.cancelPollingRequest(); -}; - -module.exports = TokenRequest; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ +/**/ -/***/ }), -/***/ 58663: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var Duplex; +/**/ -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var querystring = __nccwpck_require__(71191); -var axios = __nccwpck_require__(96545); -var _ = __nccwpck_require__(83571); -var url = __nccwpck_require__(78835); - -var constants = __nccwpck_require__(10282); -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); - -var AccountType = constants.UserRealm.AccountType; -var FederationProtocolType = constants.UserRealm.FederationProtocolType; - -var USER_REALM_PATH_TEMPLATE = 'common/UserRealm/'; - -/** - * Create a new UserRealm object - * @private - * @constructor - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} userPrinciple The username for which a realm needs to be discovered. - * @param {string} authority The string url of the authority that owns the userPrinciple. - */ -function UserRealm(callContext, userPrinciple, authority) { - this._log = new Logger('UserRealm', callContext._logContext); - this._callContext = callContext; - this._apiVersion = '1.0'; - this._federationProtocol = null; - this._accountType = null; - this._federationMetadataUrl = null; - this._federationActiveAuthUrl = null; - this._userPrinciple = userPrinciple; - this._authority = authority; -} - -/** -* The API version requested by UserRealm. -* @type {string} -* @instance -* @memberOf UserRealm -* @name apiVersion -*/ -Object.defineProperty(UserRealm.prototype, 'apiVersion', { - get : function() { - return this._apiVersion; - } -}); - -/** -* The federation protocol used by the users realm. -* @type {string} -* @instance -* @memberOf UserRealm -* @name federationProtocol -*/ -Object.defineProperty(UserRealm.prototype, 'federationProtocol', { - get : function() { - return this._federationProtocol; - } -}); - -/** -* The Type of account. Either managed or federated. -* @type {string} -* @instance -* @memberOf UserRealm -* @name accountType -*/ -Object.defineProperty(UserRealm.prototype, 'accountType', { - get : function() { - return this._accountType; - } -}); - -/** -* If this is a federated account then this property will contain the mex url. -* @type {string} -* @instance -* @memberOf UserRealm -* @name federationsMetadataUrl -*/ -Object.defineProperty(UserRealm.prototype, 'federationMetadataUrl', { - get : function() { - return this._federationMetadataUrl; - } -}); - -/** -* If the account is federated this will contain the authentication endpoint. -* @type {string} -* @instance -* @memberOf UserRealm -* @name federationActiveAuthUrl -*/ -Object.defineProperty(UserRealm.prototype, 'federationActiveAuthUrl', { - get : function() { - return this._federationActiveAuthUrl; - } -}); - -/** -* Given the authority url this method constructs a full user realm discovery url. -* @private -* @returns A full user realm discovery url including path and query string. -*/ -UserRealm.prototype._getUserRealmUrl = function() { - var userRealmUrl = util.copyUrl(this._authority); - var urlEncodedUser = encodeURIComponent(this._userPrinciple); - userRealmUrl.pathname = USER_REALM_PATH_TEMPLATE.replace('', urlEncodedUser); - - var userRealmQuery = { - 'api-version' : this._apiVersion - }; - - userRealmUrl.search = querystring.stringify(userRealmQuery); - - userRealmUrl = util.copyUrl(userRealmUrl); - - return userRealmUrl; -}; - -/** -* Given a constants object and a value, validates that the value is a key in the constants object. -* @private -* @param {object} constants An object containing constant key value pairs. -* @param {string} value A value to check against the constants -* @param {bool} caseSensitive set to true if comparisons should be made as case sensitive. Defaults to false. -* @returns {bool|string} If value passed in matches one of the constants then the return value is the matched constant. -* If a non case sensitive match was done, then the value returned may be different than the value -* passed in. If there is no match then the method returns false. -*/ -UserRealm.prototype._validateConstantValue = function(constants, value, caseSensitive) { - if (!value) { - return false; - } - if (!caseSensitive) { - value = value.toLowerCase(); - } - return _.contains(_.values(constants), value) ? value : false; -}; - -/** -* Checks whether an account type string is valid. -* @private -* @param {string} type An account type string. -* @returns {bool} -*/ -UserRealm.prototype._validateAccountType = function(type) { - return this._validateConstantValue(AccountType, type); -}; - -/** -* Checks whether a federation protocol string is valid. -* @private -* @param {string} protocol A federation protocol string. -* @returns {bool} -*/ -UserRealm.prototype._validateFederationProtocol = function(protocol) { - return this._validateConstantValue(FederationProtocolType, protocol); -}; - -/** -* Logs the values parsed as part of user realm discovery. -* @private -*/ -UserRealm.prototype._logParsedResponse = function() { - this._log.verbose('UserRealm response:'); - this._log.verbose(' AccountType: ' + this.accountType); - this._log.verbose(' FederationProtocol: ' + this.federationProtocol); - this._log.verbose(' FederationMetatdataUrl: ' + this.federationMetadataUrl, true); - this._log.verbose(' FederationActiveAuthUrl: ' + this.federationActiveAuthUrl, true); -}; - -/** -* Parses the response from a user realm discovery request. -* @private -* @param {string} body The body returned as part of the http user realm discovery request. -* @param {UserRealm.DiscoverCallback} callback Called when parsing is complete. -*/ -UserRealm.prototype._parseDiscoveryResponse = function(body, callback) { - this._log.verbose('Discovery response:\n' + body, true); - - var response; - try { - response = body; - } catch (err) { - callback(this._log.createError('Parsing realm discovery respone JSON failed: ' + body, true)); - return; - } - - var accountType = this._validateAccountType(response['account_type']); - if (!accountType) { - callback(this._log.createError('Cannot parse account_type: ' + accountType)); - return; - } - - this._accountType = accountType; - - if (this._accountType === AccountType.Federated) { - var protocol = this._validateFederationProtocol(response['federation_protocol']); - - if (!protocol) { - callback(this._log.createError('Cannot parse federation protocol: ' + protocol)); - return; - } - - this._federationProtocol = protocol; - this._federationMetadataUrl = response['federation_metadata_url']; - this._federationActiveAuthUrl = response['federation_active_auth_url']; - } - - this._logParsedResponse(); - callback(); -}; - -/** -* @callback DiscoverCallback -* @memberOf UserRealm -* @param {Error} error If an error occurs during discovery then this parameter will be used to return the error. -*/ - -/** -* Performs user realm discovery and fills in the properties on this object. -* @private -* @param {UserRealm.DiscoverCallback} callback Called when discovery is complete. -*/ -UserRealm.prototype.discover = function(callback) { - var self = this; - var options = util.createRequestOptions( - this, - { - headers : { - Accept : 'application/json' - } - } - ); - - var userRealmUrl = this._getUserRealmUrl(); - this._log.verbose('Performing user realm discovery at: ' + url.format(userRealmUrl), true); - - axios.get(userRealmUrl, options).then((response) => { - util.logReturnCorrelationId(this._log, 'User Realm Discovery', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'User Realm Discovery' + ' request returned http error: ' + response.status + ' and server response: ' + response.status; - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - self._parseDiscoveryResponse(response.data, callback); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'User Realm Discovery', error.response); - this._log.error('User Realm Discovery' + ' request failed with', error.response.status, true); - var returnErrorString = 'User Realm Discovery' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('User Realm Discovery' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else { - this._log.error('User Realm Discovery' + ' request was never made, please check', error.message, true); - callback(error.message); - } - }); -}; - -module.exports = UserRealm; +Writable.WritableState = WritableState; +/**/ -/***/ }), +var internalUtil = { + deprecate: __nccwpck_require__(65278) +}; +/**/ -/***/ 5336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/**/ -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var _ = __nccwpck_require__(83571); -var adalIdConstants = __nccwpck_require__(10282).AdalIdParameters; -var os = __nccwpck_require__(12087); -var url = __nccwpck_require__(78835); - -var ADAL_VERSION; - -/** - * @namespace Util - * @private - */ - -function loadAdalVersion() { - ADAL_VERSION = __nccwpck_require__(93700)/* .version */ .i8; -} - -function adalInit() { - loadAdalVersion(); -} - -/** - * @static - * @memberOf Util - * @param {string|int} statusCode An HTTP status code. - */ -function isHttpSuccess(statusCode) { - return statusCode >= 200 && statusCode < 300; -} - -function addDefaultRequestHeaders (self, options) { - if (!options.headers) { - options.headers = {}; - } - var headers = options.headers; - if (!headers['Accept-Charset']) { - headers['Accept-Charset'] = 'utf-8'; - } - headers['client-request-id'] = self._callContext._logContext.correlationId; - headers['return-client-request-id'] = 'true'; - - // ADAL Id headers - headers[adalIdConstants.SKU] = adalIdConstants.NODE_SKU; - headers[adalIdConstants.VERSION] = ADAL_VERSION; - headers[adalIdConstants.OS] = os.platform(); - headers[adalIdConstants.CPU] = os.arch(); -} - -/** -* Central place for housing default request options. This is a place holder -* for when SSL validation is implemented an all requests are subject to that -* policy. -* @static -* @memberOf Util -* @param {object} options A set of options that will be merged with teh default options -* These will override any default options. -* @returns {object} Returns the merged options. -*/ -function createRequestOptions(self, options) { - var defaultOptions = {}; //{ strictSSL : true }; - var mergedOptions = defaultOptions; - if (options) { - _.extend(mergedOptions, options); - } - if (self._callContext.options && self._callContext.options.http) { - _.extend(mergedOptions, self._callContext.options.http); - } - - addDefaultRequestHeaders(self, mergedOptions); - return mergedOptions; -} - -function logReturnCorrelationId(log, operationMessage, response) { - if (response && response.headers && response.headers['client-request-id']) { - log.info(operationMessage + 'Server returned this correlationId: ' + response.headers['client-request-id'], true); - } -} - -/** -* Creates a function that can be used as the callback for http request operations. This is meant -* to centralize error handling in one place. -* @static -* @memberOf Util -* @param {string} operationMessage A message to be prepended to logged error strings. This should be something like 'Mex Request' -* and summarize the purpose of the http request. -* @param {object} log A Logger object being used by the calling component. -* @param {Util.CreateRequestHandlerErrorCallback} errorCallback Called in the event of an error. -* @param {Util.CreateRequestHandlerSuccessCallabck} successCallback Called on successfull completion of the request. -*/ -function createRequestHandler(operationMessage, log, errorCallback, successCallback) { - return function(err, response, body) { - logReturnCorrelationId(log, operationMessage, response); - if (err) { - log.error(operationMessage + ' request failed with', err, true); - errorCallback(err); - return; - } - if (!isHttpSuccess(response.statusCode)) { - var returnErrorString = operationMessage + ' request returned http error: ' + response.statusCode; - var errorResponse; - if (body) { - returnErrorString += ' and server response: ' + body; - try { - errorResponse = JSON.parse(body); - } catch (e) { - // No problem if it doesn't parse. - } - } - errorCallback(log.createError(returnErrorString, true), errorResponse); - return; - } - - successCallback(response, body); - }; -} - -/** -* @callback CreateRequestHandlerErrorCallback -* @memberOf Util -* @param {Error} error An error object. -*/ - -/** -* @callback CreateRequestHandlerSuccessCallabck -* @memberOf Util -* @param {object} response The response object returned from request. -* @param {string} body The body of the http response. -*/ - -/** -* Deep copies a url object. -* @static -* @memberOf Util -* @param {URL} urlSource The source url object to copy. -* @returns {URL} A deep copy of sourceUrl. -*/ -function copyUrl(urlSource) { - return url.parse(url.format(urlSource)); -} - -function convertUrlSafeToRegularBase64EncodedString(str) { - return str.replace(/-/g, '+').replace(/_/g, '/'); -} - -function convertRegularToUrlSafeBase64EncodedString(str) { - return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); -} - -function base64DecodeStringUrlSafe(str) { - var base64 = convertUrlSafeToRegularBase64EncodedString(str); - return (new Buffer(base64, 'base64')).toString('utf8'); -} - -function base64EncodeStringUrlSafe(str) { - var base64 = (new Buffer(str, 'utf8').toString('base64')); - var converted = convertRegularToUrlSafeBase64EncodedString(base64); - return converted; -} - -module.exports.adalInit = adalInit; -module.exports.isHttpSuccess = isHttpSuccess; -module.exports.logReturnCorrelationId = logReturnCorrelationId; -module.exports.createRequestHandler = createRequestHandler; -module.exports.createRequestOptions = createRequestOptions; -module.exports.copyUrl = copyUrl; -module.exports.base64DecodeStringUrlSafe = base64DecodeStringUrlSafe; -module.exports.base64EncodeStringUrlSafe = base64EncodeStringUrlSafe; -module.exports.convertRegularToUrlSafeBase64EncodedString = convertRegularToUrlSafeBase64EncodedString; +var Stream = __nccwpck_require__(36238); +/**/ -/***/ }), -/***/ 39035: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var axios = __nccwpck_require__(96545); -var uuid = __nccwpck_require__(19744); - -var Logger = __nccwpck_require__(92288).Logger; -var util = __nccwpck_require__(5336); -var WSTrustResponse = __nccwpck_require__(55927); -var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; - -var USERNAME_PLACEHOLDER = '{UsernamePlaceHolder}'; -var PASSWORD_PLACEHOLDER = '{PasswordPlaceHolder}'; - -/** - * Creates a new instance of WSTrustRequest - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} wstrustEndpointUrl An STS WS-Trust soap endpoint. - * @param {string} appliesTo A URI that identifies a service for which the a token is to be obtained. - */ -function WSTrustRequest(callContext, wstrustEndpointUrl, appliesTo, wstrustEndpointVersion) { - this._log = new Logger('WSTrustRequest', callContext._logContext); - this._callContext = callContext; - this._wstrustEndpointUrl = wstrustEndpointUrl; - this._appliesTo = appliesTo; - this._wstrustEndpointVersion = wstrustEndpointVersion; -} - -/** -* Given a Date object adds the minutes parameter and returns a new Date object. -* @private -* @static -* @memberOf WSTrustRequest -* @param {Date} date A Date object. -* @param {Number} minutes The number of minutes to add to the date parameter. -* @returns {Date} Returns a Date object. -*/ -function _datePlusMinutes(date, minutes) { - var minutesInMilliSeconds = minutes * 60 * 1000; - var epochTime = date.getTime() + minutesInMilliSeconds; - return new Date(epochTime); -} - -/** - * Builds the soap security header for the RST message. - * @private - * @param {string} username A username - * @param {string} password The passowrd that corresponds to the username parameter. - * @returns {string} A string that contains the soap security header. - */ -WSTrustRequest.prototype._buildSecurityHeader = function() { - var timeNow = new Date(); - var expireTime = _datePlusMinutes(timeNow, 10); - var timeNowString = timeNow.toISOString(); - var expireTimeString = expireTime.toISOString(); - - var securityHeaderXml = - '\ - \ - ' + timeNowString + '\ - ' + expireTimeString + '\ - \ - \ - ' + USERNAME_PLACEHOLDER + '\ - ' + PASSWORD_PLACEHOLDER + '\ - \ - '; - - return securityHeaderXml; -}; - -/** - * Replaces the placeholders in the RST template with the actual username and password values. - * @private - * @param {string} RSTTemplate An RST with placeholders for username and password. - * @param {string} username A username - * @param {string} password The passowrd that corresponds to the username parameter. - * @returns {string} A string containing a complete RST soap message. - */ - -WSTrustRequest.prototype._populateRSTUsernamePassword = function(RSTTemplate, username, password) { - var RST = RSTTemplate.replace(USERNAME_PLACEHOLDER, username).replace(PASSWORD_PLACEHOLDER, this._populatedEscapedPassword(password)); - return RST; -}; - -/** - * Escape xml characters in password. - * @private - * @param {string} password The password to be excaped with xml charaters. - */ -WSTrustRequest.prototype._populatedEscapedPassword = function (password) { - var escapedPassword = password; - return escapedPassword.replace(/&/g, '&') - .replace(/"/g, '"') - .replace(/'/g, ''') - .replace(//g, '>'); -} - -/** - * Builds a WS-Trust RequestSecurityToken (RST) message using username password authentication. - * @private - * @param {string} username A username - * @param {string} password The passowrd that corresponds to the username parameter. - * @returns {string} A string containing a complete RST soap message. - */ -WSTrustRequest.prototype._buildRST = function(username, password) { - var messageID = uuid.v4(); - - // Create a template RST with placeholders for the username and password so the - // the RST can be logged without the sensitive information. - var schemaLocation = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'; - var soapAction = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; - var rstTrustNamespace = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512'; - var keyType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer'; - var requestType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue'; - - if (this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005) { - soapAction = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'; - rstTrustNamespace = 'http://schemas.xmlsoap.org/ws/2005/02/trust'; - keyType = 'http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey'; - requestType = 'http://schemas.xmlsoap.org/ws/2005/02/trust/Issue'; - } - - var RSTTemplate = - '\ - \ - ' + soapAction + '\ - urn:uuid:' + messageID + '\ - \ - http://www.w3.org/2005/08/addressing/anonymous\ - \ - ' + this._wstrustEndpointUrl + '\ - ' + this._buildSecurityHeader() + '\ - \ - \ - \ - \ - \ - ' + this._appliesTo + '\ - \ - \ - ' + keyType + '\ - ' + requestType + '\ - \ - \ - '; - - this._log.verbose('Created RST: \n' + RSTTemplate, true); - - var RST = this._populateRSTUsernamePassword(RSTTemplate, username, password); - return RST; -}; - -/** - * Handles the processing of a RSTR - * @private - * @param {string} body - * @param {WSTrustRequest.AcquireTokenCallback} callback - */ -WSTrustRequest.prototype._handleRSTR = function(body, callback) { - var err; - - var wstrustResponse = new WSTrustResponse(this._callContext, body, this._wstrustEndpointVersion); - try { - wstrustResponse.parse(); - } catch (error) { - err = error; - } - - callback(err, wstrustResponse); -}; - -/** - * Performs a WS-Trust RequestSecurityToken request to obtain a federated token in exchange for a username password. - * @param {string} username A username - * @param {string} password The passowrd that corresponds to the username parameter. - * @param {WSTrustRequest.AcquireTokenCallback} callback Called once the federated token has been retrieved or on error. -*/ -WSTrustRequest.prototype.acquireToken = function(username, password, callback) { - if (this._wstrustEndpointVersion === WSTrustVersion.UNDEFINED) { - var err = this._log.createError('Unsupported wstrust endpoint version. Current support version is wstrust2005 or wstrust13.'); - callback(err); - return; - } - - var self = this; - var RST = this._buildRST(username, password); - - var soapAction = this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005 ? 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'; - - var options = util.createRequestOptions( - this, - { - method: 'POST', - url: this._wstrustEndpointUrl, - headers : { - 'Content-Type' : 'application/soap+xml; charset=utf-8', - 'SOAPAction' : soapAction - }, - data: RST, - maxRedirects: 0, - encoding: 'utf8', - } - ); - - this._log.verbose('Sending RST to: ' + this._wstrustEndpointUrl, true); - - axios(options).then((response) => { - util.logReturnCorrelationId(this._log, 'WS-Trust RST', response); - // status >= 300 && < 400 - if (!util.isHttpSuccess(response.status)) { - var returnErrorString = 'WS-Trust RST' + ' request returned http error: ' + response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(this._log.createError(returnErrorString, true), response.data); - } - // Success case: status >= 200 && < 300 - self._handleRSTR(response.data, callback); - }).catch((error) => { - // status >= 400: error case - if (error.response) { - util.logReturnCorrelationId(this._log, 'WS-Trust RST', error.response); - this._log.error('WS-Trust RST' + ' request failed with', error.response.status, true); - var returnErrorString = 'WS-Trust RST' + ' request returned http error: ' + error.response.status + ' and server response: ' + JSON.stringify(error.response.data); - callback(self._log.createError(returnErrorString, true), error.response.data); - } - // if there is no response from the server - else if (error.request) { - this._log.error('WS-Trust RST' + ' request was made but no response was received', error.request, true); - callback(self._log.createError('No response from the server')); - } - // request was never made - else if (error.message) { - this._log.error('WS-Trust RST' + ' request was never made, please check', error.message, true); - callback(error.message); - } - // unknown error - else { - self._log.error('WS-Trust RST' + ' failed with unknown error', "unknown error", true); - callback(self._log.createError('failed with an unknown error')); - } - }); -}; - -/** -* @callback AcquireTokenCallback -* @memberOf WSTrustRequest -* @param {Error} err Contains an error object if acquireToken fails. -* @param {WSTrustResponse} A successful response to the RST. -*/ - -module.exports = WSTrustRequest; +var Buffer = __nccwpck_require__(64293).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; -/***/ }), +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} -/***/ 55927: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var xmldom = __nccwpck_require__(57286); - -var xmlutil = __nccwpck_require__(27387); - -var Logger = __nccwpck_require__(92288).Logger; - -var WSTrustVersion = __nccwpck_require__(10282).WSTrustVersion; - -var select = xmlutil.xpathSelect; -var DOMParser = xmldom.DOMParser; - -// A regular expression for finding the SAML Assertion in an RSTR. Used to remove the SAML -// assertion when logging the RSTR. -var assertionRegEx = /RequestedSecurityToken.*?((<.*?:Assertion.*?>).*<\/.*?Assertion>).*?/; - -/** - * Creates a log message that contains the RSTR scrubbed of the actual SAML assertion. - * @private - * @return {string} A log message. - */ -function scrubRSTRLogMessage(RSTR) { - var scrubbedRSTR = null; - - var singleLineRSTR = RSTR.replace(/(\r\n|\n|\r)/gm,''); - - var matchResult = assertionRegEx.exec(singleLineRSTR); - if (null === matchResult) { - // No Assertion was matched so just return the RSTR as is. - scrubbedRSTR = singleLineRSTR; - } else { - var samlAssertion = matchResult[1]; - var samlAssertionStartTag = matchResult[2]; - - scrubbedRSTR = singleLineRSTR.replace(samlAssertion, samlAssertionStartTag + 'ASSERTION CONTENTS REDACTED'); - } - - return 'RSTR Response: ' + scrubbedRSTR; -} - -/** - * Creates a new WSTrustResponse instance. - * @constructor - * @private - * @param {object} callContext Contains any context information that applies to the request. - * @param {string} response A soap response from a WS-Trust request. - * @param {sting} wstrustVersion The version for the WS-Trust request. - */ -function WSTrustResponse(callContext, response, wstrustVersion) { - this._log = new Logger('WSTrustResponse', callContext._logContext); - this._callContext = callContext; - this._response = response; - this._dom = null; - this._errorCode = null; - this._faultMessage = null; - this._tokenType = null; - this._token = null; - this._wstrustVersion = wstrustVersion; - - this._log.verbose(function(){return scrubRSTRLogMessage(response);}); -} - -/** - * If the soap response contained a soap fault then this property will contain the fault - * error code. Otherwise it will return null - * @instance - * @type {string} - * @memberOf WSTrustResponse - * @name errorCode - */ -Object.defineProperty(WSTrustResponse.prototype, 'errorCode', { - get: function() { - return this._errorCode; - } -}); - -/** - * @property {string} FaultMessage If the soap resopnse contained a soap fault with a fault message then it will - * be returned by this property. - * @instance - * @type {string} - * @memberOf WSTrustResponse - * @name faultMessage - */ -Object.defineProperty(WSTrustResponse.prototype, 'faultMessage', { - get: function() { - return this._faultMessage; - } -}); - -/** - * @property {string} TokenType If the soap resonse contained a token then this property will contain - * the token type uri - * @instance - * @type {string} - * @memberOf WSTrustResponse - * @name tokenType - */ -Object.defineProperty(WSTrustResponse.prototype, 'tokenType', { - get: function() { - return this._tokenType; - } -}); - -/** - * @property {string} Token If the soap response contained a token then this property will hold that token. - * @instance - * @type {string} - * @memberOf WSTrustResponse - * @name token - */ -Object.defineProperty(WSTrustResponse.prototype, 'token', { - get: function() { - return this._token; - } -}); - - // Sample error message - // - // - // http://www.w3.org/2005/08/addressing/soap/fault - // - - // - // 2013-07-30T00:32:21.989Z - // 2013-07-30T00:37:21.989Z - // - // - // - // - // - // - // s:Sender - // - // a:RequestFailed - // - // - // - // MSIS3127: The specified request failed. - // - // - // - // - -/** - * Attempts to parse an error from the soap response. If there is one then it - * will fill in the error related properties. Otherwsie it will do nothing. - * @private - * @returns {bool} true if an error was found and parsed in the response. - */ -WSTrustResponse.prototype._parseError = function() { - var errorFound = false; - - var faultNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Reason'); - if (faultNode.length) { - this._faultMessage = xmlutil.serializeNodeChildren(faultNode[0]); - - if (this._faultMessage) { - errorFound = true; - } - } - - // Subcode has minoccurs=0 and maxoccurs=1(default) according to the http://www.w3.org/2003/05/soap-envelope - // Subcode may have another subcode as well. This is only targetting at top level subcode. - // Subcode value may have different messages not always uses http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd. - // text inside the value is not possible to select without prefix, so substring is necessary - var subcodeNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Code/s:Subcode/s:Value'); - if (1 < subcodeNode.length) { - throw this._log.createError('Found too many fault code values:' + subcodeNode.length); - } - - if (subcodeNode.length) { - var errorCode = subcodeNode[0].firstChild.data; - this._errorCode = (errorCode.split(':'))[1]; - errorFound = true; - } - - return errorFound; -}; - -/** - * Attempts to parse a token from the soap response. If there is one then it will fill in the - * token related properties. Otherwise it does nothing. - * @private - * @throws {Error} If the response is not parseable, or too many tokens are found. - */ -WSTrustResponse.prototype._parseToken = function() { - var xPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? '//s:Envelope/s:Body/t:RequestSecurityTokenResponse/t:TokenType' : '//s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/wst:RequestSecurityTokenResponse/wst:TokenType'; - - var tokenTypeNodes = select(this._dom, xPath); - if (!tokenTypeNodes.length) { - this._log.warn('No TokenType elements found in RSTR'); - } - - for (var i = 0, length = tokenTypeNodes.length; i < length; i++) { - if (this._token) { - this._log.warn('Found more than one returned token. Using the first.'); - break; - } - - var tokenTypeNode = tokenTypeNodes[i]; - var tokenType = xmlutil.findElementText(tokenTypeNode); - if (!tokenType) { - this._log.warn('Could not find token type in RSTR token'); - } - - var securityTokenPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? 't:RequestedSecurityToken' : 'wst:RequestedSecurityToken'; - var requestedTokenNode = select(tokenTypeNode.parentNode, securityTokenPath); - if (1 < requestedTokenNode) { - throw this._log.createError('Found too many RequestedSecurityToken nodes for token type: ' + tokenType); - } - if (!requestedTokenNode.length) { - this._log.warn('Unable to find RequestsSecurityToken element associated with TokenType element: ' + tokenType); - continue; - } - - var token = xmlutil.serializeNodeChildren(requestedTokenNode[0]); - if (!token) { - this._log.warn('Unable to find token associated with TokenType element: ' + tokenType); - continue; - } - - this._token = token; - this._tokenType = tokenType; - - this._log.info('Found token of type: ' + this._tokenType); - } - - if (!this._token) { - throw this._log.createError('Unable to find any tokens in RSTR.'); - } -}; - -/** - * This method parses the soap response that was passed in at construction. - * @throws {Error} If the server returned an error, or there was any failure to parse the response. - */ -WSTrustResponse.prototype.parse = function() { - if (!this._response) { - throw this._log.createError('Received empty RSTR response body.'); - } - - try { - try { - var options = { - errorHandler : this._log.error - }; - this._dom = new DOMParser(options).parseFromString(this._response); - } catch (err) { - throw this._log.createError('Failed to parse RSTR in to DOM', err, true); - } - - var errorFound = this._parseError(); - - if (errorFound) { - var stringErrorCode = this.ErrorCode || 'NONE'; - var stringFaultMessage = this.FaultMessage || 'NONE'; - throw this._log.createError('Server returned error in RSTR - ErrorCode: ' + stringErrorCode + ' : FaultMessage: ' + stringFaultMessage, true); - } - - this._parseToken(); - } catch (err) { - delete this._dom; - throw err; - } -}; - -module.exports = WSTrustResponse; +var destroyImpl = __nccwpck_require__(36994); -/***/ }), +var _require = __nccwpck_require__(3533), + getHighWaterMark = _require.getHighWaterMark; -/***/ 27387: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; -"use strict"; -/* - * @copyright - * Copyright © Microsoft Open Technologies, Inc. - * - * All Rights Reserved - * - * 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 - * - * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION - * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A - * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. - * - * See the Apache License, Version 2.0 for the specific language - * governing permissions and limitations under the License. - */ - - -var _ = __nccwpck_require__(83571); -var select = __nccwpck_require__(74277); -var XMLSerializer = __nccwpck_require__(57286).XMLSerializer; - -var constants = __nccwpck_require__(10282); - -/** - * @namespace XmlUtil - * @private - */ - -var XPATH_PATH_TEMPLATE = '*[local-name() = \'LOCAL_NAME\' and namespace-uri() = \'NAMESPACE\']'; -/** -* The xpath implementation being used does not have a way of matching expanded namespace. -* This method takes an xpath query and expands all of the namespaces involved. It then -* re-writes the query in to a longer form that directory matches the correct namespaces. -* @private -* @static -* @memberOf XmlUtil -* @param {string} xpath The expath query string to expand. -* @returns {string} An expanded xpath query. -*/ -function expandQNames(xpath) { - var namespaces = constants.XmlNamespaces; - var pathParts = xpath.split('/'); - for (var i=0; i < pathParts.length; i++) { - if (pathParts[i].indexOf(':') !== -1) { - var QNameParts = pathParts[i].split(':'); - if (QNameParts.length !== 2) { - throw new Error('Unable to parse XPath string : ' + xpath + ' : with QName : ' + pathParts[i]); - } - var expandedPath = XPATH_PATH_TEMPLATE.replace('LOCAL_NAME', QNameParts[1]); - expandedPath = expandedPath.replace('NAMESPACE', namespaces[QNameParts[0]]); - pathParts[i] = expandedPath; - } - } - return pathParts.join('/'); -} - -var exports = { - - /** - * Performs an xpath select that does appropriate namespace matching since the imported - * xpath module does not properly handle namespaces. - * @static - * @memberOf XmlUtil - * @param {object} dom A dom object created by the xmldom module - * @param {string} xpath An xpath expression - * @return {array} An array of matching dom nodes. - */ - xpathSelect : function (dom, xpath) { - return select(dom, expandQNames(xpath)); - }, - - /** - * Given a dom node serializes all immediate children that are xml elements. - * @static - * @memberOf XmlUtil - * @param {object} node An xml dom node. - * @return {string} Serialized xml. - */ - serializeNodeChildren : function(node) { - var doc = ''; - var sibling = node.firstChild; - var serializer = new XMLSerializer(); - - while (sibling) { - if (this.isElementNode(sibling)) { - doc += serializer.serializeToString(sibling); - } - sibling = sibling.nextSibling; - } - - return doc !== '' ? doc : null; - }, - - /** - * Detects whether the passed in dom node represents an xml element. - * @static - * @memberOf XmlUtil - * @param {object} node An xml dom node. - * @return {Boolean} true if the node represents an element. - */ - isElementNode : function(node) { - return _.has(node, 'tagName'); - }, - - /** - * Given an xmldom node this function returns any text data contained within. - * @static - * @memberOf XmlUtil - * @param {object} node An xmldom node from which the data should be extracted. - * @return {string} Any data found within the element or null if none is found. - */ - findElementText : function(node) { - var sibling = node.firstChild; - while (sibling && !sibling.data) { - sibling = sibling.nextSibling; - } - - return sibling.data ? sibling.data : null; - } -}; - -module.exports = exports; +var errorOrDestroy = destroyImpl.errorOrDestroy; -/***/ }), +__nccwpck_require__(44124)(Writable, Stream); -/***/ 19744: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function nop() {} -var v1 = __nccwpck_require__(64425); -var v4 = __nccwpck_require__(85258); +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(13928); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. -module.exports = uuid; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called -/***/ }), + this.finalCalled = false; // drain event flag. -/***/ 54121: -/***/ ((module) => { + this.needDrain = false; // at the start of calling end() -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); -} + this.ending = false; // when end() has been called, and returned -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - return ([ - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]] - ]).join(''); -} + this.ended = false; // when 'finish' is emitted -module.exports = bytesToUuid; + this.finished = false; // has it been destroyed + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. -/***/ }), + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. -/***/ 57455: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. -// Unique ID creation requires a high quality random # generator. In node.js -// this is pretty straight-forward - we use the crypto API. + this.length = 0; // a flag to see when we're in the middle of a write. -var crypto = __nccwpck_require__(76417); + this.writing = false; // when true all writes will be buffered until .uncork() call -module.exports = function nodeRNG() { - return crypto.randomBytes(16); -}; + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. -/***/ }), + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) -/***/ 64425: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) -var rng = __nccwpck_require__(57455); -var bytesToUuid = __nccwpck_require__(54121); -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html + this.writecb = null; // the amount that is being written when _write is called. -var _nodeId; -var _clockseq; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted -// Previous uuid creation time -var _lastMSecs = 0; -var _lastNSecs = 0; + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams -// See https://github.com/uuidjs/uuid for API details -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; + this.prefinished = false; // True if the error was already emitted and should not be thrown again - options = options || {}; - var node = options.node || _nodeId; - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - if (node == null || clockseq == null) { - var seedBytes = rng(); - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [ - seedBytes[0] | 0x01, - seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] - ]; - } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + this.autoDestroy = !!options.autoDestroy; // count buffered requests - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two - // Time since last uuid creation (in msecs) - var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + this.corkedRequestsFree = new CorkedRequest(this); +} - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; + while (current) { + out.push(current); + current = current.next; } - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); - } + return out; +}; - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - // `time_low` - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; +var realHasInstance; - // `time_mid` - var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; +function Writable(options) { + Duplex = Duplex || __nccwpck_require__(13928); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. - // `clock_seq_low` - b[i++] = clockseq & 0xff; + this.writable = true; - // `node` - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; } - return buf ? buf : bytesToUuid(b); -} + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. -module.exports = v1; +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; -/***/ }), +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb -/***/ 85258: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. -var rng = __nccwpck_require__(57455); -var bytesToUuid = __nccwpck_require__(54121); -function v4(options, buf, offset) { - var i = buf && offset || 0; +function validChunk(stream, state, chunk, cb) { + var er; - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } - options = options || {}; - var rnds = options.random || (options.rng || rng)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; } - return buf || bytesToUuid(rnds); + return true; } -module.exports = v4; - - -/***/ }), - -/***/ 52068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; -"use strict"; -/* module decorator */ module = __nccwpck_require__.nmd(module); + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; }; -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +Writable.prototype.cork = function () { + this._writableState.corked++; }; -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); +Writable.prototype.uncork = function () { + var state = this._writableState; - return value; - }, - enumerable: true, - configurable: true - }); + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } }; -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = __nccwpck_require__(86931); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; }; -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; + return chunk; +} - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); - group[styleName] = styles[styleName]; + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } - codes.set(style[0], style[1]); - } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } + if (!ret) state.needDrain = true; - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - return styles; + return ret; } -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} -/***/ }), +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; -/***/ 64808: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error -"use strict"; + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} -var lib = __nccwpck_require__(98035); -module.exports = lib(__dirname); +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -/***/ }), - -/***/ 98035: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -module.exports = function(dirname) { - var path = __nccwpck_require__(85622); - var resolve = __nccwpck_require__(15619); - var appRootPath = resolve(dirname); - - var publicInterface = { - resolve: function(pathToModule) { - return path.join(appRootPath, pathToModule); - }, - - require: function(pathToModule) { - return require(publicInterface.resolve(pathToModule)); - }, - - toString: function() { - return appRootPath; - }, - - setPath: function(explicitlySetPath) { - appRootPath = path.resolve(explicitlySetPath); - publicInterface.path = appRootPath; - }, +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; - path: appRootPath - }; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } - return publicInterface; -}; + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} -/***/ }), +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. -/***/ 15619: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it -// Dependencies -var path = __nccwpck_require__(85622); +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; -// Load global paths -var globalPaths = __nccwpck_require__(32282).globalPaths; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; -// Guess at NPM's global install dir -var npmGlobalPrefix; -if ('win32' === process.platform) { - npmGlobalPrefix = path.dirname(process.execPath); -} else { - npmGlobalPrefix = path.dirname(path.dirname(process.execPath)); -} -var npmGlobalModuleDir = path.resolve(npmGlobalPrefix, 'lib', 'node_modules'); + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } -// Save OS-specific path separator -var sep = path.sep; + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite -// If we're in webpack, force it to use the original require() method -var requireFunction = ( true) - ? eval("require") - : 0; + state.pendingcb++; + state.lastBufferedRequest = null; -const isInstalledWithPNPM = function(resolved) { - const pnpmDir = sep + '.pnpm'; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } - for (const globalPath of globalPaths) { - if (-1 !== globalPath.indexOf(pnpmDir) && -1 !== resolved.indexOf(pnpmDir)) { - return true; - } - } - return false; -} + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. -const getFirstPartFromNodeModules = function(resolved) { - const nodeModulesDir = sep + 'node_modules'; + if (state.writing) { + break; + } + } - if (-1 !== resolved.indexOf(nodeModulesDir)) { - const parts = resolved.split(nodeModulesDir); - if (parts.length) { - return parts[0]; - } - } + if (entry === null) state.lastBufferedRequest = null; + } - return null; + state.bufferedRequest = entry; + state.bufferProcessing = false; } -// Resolver -module.exports = function resolve(dirname) { - // Check for environmental variable - if (process.env.APP_ROOT_PATH) { - return path.resolve(process.env.APP_ROOT_PATH); - } - - // Defer to Yarn Plug'n'Play if enabled - if (process.versions.pnp) { - try { - var pnp = requireFunction('pnpapi'); - return pnp.getPackageInformation(pnp.topLevel).packageLocation; - } catch (e) {} - } - - // Defer to main process in electron renderer - if ('undefined' !== typeof window && window.process && 'renderer' === window.process.type) { - try { - var remote = requireFunction('electron').remote; - return remote.require('app-root-path').path; - } catch (e) {} - } - - // Defer to AWS Lambda when executing there - if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) { - return process.env.LAMBDA_TASK_ROOT; - } - - var resolved = path.resolve(dirname); - var alternateMethod = false; - var appRootPath = null; +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; - // Check if the globalPaths contain some folders with '.pnpm' in the path - // If yes this means it is most likely installed with pnpm - if (isInstalledWithPNPM(resolved)) { - appRootPath = getFirstPartFromNodeModules(resolved); +Writable.prototype._writev = null; - if (appRootPath) { - return appRootPath; - } - } +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - // Make sure that we're not loaded from a global include path - // Eg. $HOME/.node_modules - // $HOME/.node_libraries - // $PREFIX/lib/node - globalPaths.forEach(function(globalPath) { - if (!alternateMethod && 0 === resolved.indexOf(globalPath)) { - alternateMethod = true; - } - }); + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - // If the app-root-path library isn't loaded globally, - // and node_modules exists in the path, just split __dirname - if (!alternateMethod) { - appRootPath = getFirstPartFromNodeModules(resolved); - } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - // If the above didn't work, or this module is loaded globally, then - // resort to require.main.filename (See http://nodejs.org/api/modules.html) - if (alternateMethod || null == appRootPath) { - appRootPath = path.dirname(requireFunction.main.filename); - } + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. - // Handle global bin/ directory edge-case - if (alternateMethod && -1 !== appRootPath.indexOf(npmGlobalModuleDir) && (appRootPath.length - 4) === appRootPath.indexOf(sep + 'bin')) { - appRootPath = appRootPath.slice(0, -4); - } - // Return - return appRootPath; + if (!state.ending) endWritable(this, state, cb); + return this; }; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); -/***/ }), - -/***/ 83278: -/***/ ((module) => { +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} -"use strict"; +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } -function isArguments (thingy) { - return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); } -var types = { - '*': {label: 'any', check: function () { return true }}, - A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }}, - S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }}, - N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }}, - F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }}, - O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }}, - B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }}, - E: {label: 'error', check: function (thingy) { return thingy instanceof Error }}, - Z: {label: 'null', check: function (thingy) { return thingy == null }} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } } -function addSchema (schema, arity) { - var group = arity[schema.length] = arity[schema.length] || [] - if (group.indexOf(schema) === -1) group.push(schema) -} +function finishMaybe(stream, state) { + var need = needFinish(state); -var validate = module.exports = function (rawSchemas, args) { - if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) - if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') - if (!args) throw missingRequiredArg(1, 'args') - if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) - if (!types.A.check(args)) throw invalidType(1, ['array'], args) - var schemas = rawSchemas.split('|') - var arity = {} + if (need) { + prefinish(stream, state); - schemas.forEach(function (schema) { - for (var ii = 0; ii < schema.length; ++ii) { - var type = schema[ii] - if (!types[type]) throw unknownType(ii, type) - } - if (/E.*E/.test(schema)) throw moreThanOneError(schema) - addSchema(schema, arity) - if (/E/.test(schema)) { - addSchema(schema.replace(/E.*$/, 'E'), arity) - addSchema(schema.replace(/E/, 'Z'), arity) - if (schema.length === 1) addSchema('', arity) - } - }) - var matching = arity[args.length] - if (!matching) { - throw wrongNumberOfArgs(Object.keys(arity), args.length) - } - for (var ii = 0; ii < args.length; ++ii) { - var newMatching = matching.filter(function (schema) { - var type = schema[ii] - var typeCheck = types[type].check - return typeCheck(args[ii]) - }) - if (!newMatching.length) { - var labels = matching.map(function (schema) { - return types[schema[ii]].label - }).filter(function (schema) { return schema != null }) - throw invalidType(ii, labels, args[ii]) + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } } - matching = newMatching } -} -function missingRequiredArg (num) { - return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) + return need; } -function unknownType (num, type) { - return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) -} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); -function invalidType (num, expectedTypes, value) { - var valueType - Object.keys(types).forEach(function (typeCode) { - if (types[typeCode].check(value)) valueType = types[typeCode].label - }) - return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + - englishList(expectedTypes) + ' but got ' + valueType) -} + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } -function englishList (list) { - return list.join(', ').replace(/, ([^,]+)$/, ' or $1') + state.ended = true; + stream.writable = false; } -function wrongNumberOfArgs (expected, got) { - var english = englishList(expected) - var args = expected.every(function (ex) { return ex.length === 1 }) - ? 'argument' - : 'arguments' - return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) -} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; -function moreThanOneError (schema) { - return newException('ETOOMANYERRORTYPES', - 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') -} + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. -function newException (code, msg) { - var e = new Error(msg) - e.code = code - if (Error.captureStackTrace) Error.captureStackTrace(e, validate) - return e -} + state.corkedRequestsFree.next = corkReq; +} -/***/ }), +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } -/***/ 11083: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed -"use strict"; -exports.TrackerGroup = __nccwpck_require__(60660) -exports.Tracker = __nccwpck_require__(8074) -exports.TrackerStream = __nccwpck_require__(31375) + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; /***/ }), -/***/ 10165: +/***/ 37558: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var EventEmitter = __nccwpck_require__(28614).EventEmitter -var util = __nccwpck_require__(31669) -var trackerId = 0 -var TrackerBase = module.exports = function (name) { - EventEmitter.call(this) - this.id = ++trackerId - this.name = name -} -util.inherits(TrackerBase, EventEmitter) +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -/***/ }), +var finished = __nccwpck_require__(40036); -/***/ 60660: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); -"use strict"; +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} -var util = __nccwpck_require__(31669) -var TrackerBase = __nccwpck_require__(10165) -var Tracker = __nccwpck_require__(8074) -var TrackerStream = __nccwpck_require__(31375) +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; -var TrackerGroup = module.exports = function (name) { - TrackerBase.call(this, name) - this.parentGroup = null - this.trackers = [] - this.completion = {} - this.weight = {} - this.totalWeight = 0 - this.finished = false - this.bubbleChange = bubbleChange(this) -} -util.inherits(TrackerGroup, TrackerBase) + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' -function bubbleChange (trackerGroup) { - return function (name, completed, tracker) { - trackerGroup.completion[tracker.id] = completed - if (trackerGroup.finished) return - trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup) + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } } } -TrackerGroup.prototype.nameInTree = function () { - var names = [] - var from = this - while (from) { - names.unshift(from.name) - from = from.parentGroup - } - return names.join('/') +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); } -TrackerGroup.prototype.addUnit = function (unit, weight) { - if (unit.addUnit) { - var toTest = this - while (toTest) { - if (unit === toTest) { - throw new Error( - 'Attempted to add tracker group ' + - unit.name + ' to tree that already includes it ' + - this.nameInTree(this)) +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; } - toTest = toTest.parentGroup - } - unit.parentGroup = this - } - this.weight[unit.id] = weight || 1 - this.totalWeight += this.weight[unit.id] - this.trackers.push(unit) - this.completion[unit.id] = unit.completed() - unit.on('change', this.bubbleChange) - if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit) - return unit -} -TrackerGroup.prototype.completed = function () { - if (this.trackers.length === 0) return 0 - var valPerWeight = 1 / this.totalWeight - var completed = 0 - for (var ii = 0; ii < this.trackers.length; ii++) { - var trackerId = this.trackers[ii].id - completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId] - } - return completed + iter[kHandlePromise](resolve, reject); + }, reject); + }; } -TrackerGroup.prototype.newGroup = function (name, weight) { - return this.addUnit(new TrackerGroup(name), weight) -} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, -TrackerGroup.prototype.newItem = function (name, todo, weight) { - return this.addUnit(new Tracker(name, todo), weight) -} + next: function next() { + var _this = this; -TrackerGroup.prototype.newStream = function (name, todo, weight) { - return this.addUnit(new TrackerStream(name, todo), weight) -} + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; -TrackerGroup.prototype.finish = function () { - this.finished = true - if (!this.trackers.length) this.addUnit(new Tracker(), 1, true) - for (var ii = 0; ii < this.trackers.length; ii++) { - var tracker = this.trackers[ii] - tracker.finish() - tracker.removeListener('change', this.bubbleChange) - } - this.emit('change', this.name, 1, this) -} + if (error !== null) { + return Promise.reject(error); + } -var buffer = ' ' -TrackerGroup.prototype.debug = function (depth) { - depth = depth || 0 - var indent = depth ? buffer.substr(0, depth) : '' - var output = indent + (this.name || 'top') + ': ' + this.completed() + '\n' - this.trackers.forEach(function (tracker) { - if (tracker instanceof TrackerGroup) { - output += tracker.debug(depth + 1) - } else { - output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n' + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); } - }) - return output -} + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time -/***/ }), -/***/ 31375: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var lastPromise = this[kLastPromise]; + var promise; -"use strict"; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); -var util = __nccwpck_require__(31669) -var stream = __nccwpck_require__(51642) -var delegate = __nccwpck_require__(61318) -var Tracker = __nccwpck_require__(8074) + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } -var TrackerStream = module.exports = function (name, size, options) { - stream.Transform.call(this, options) - this.tracker = new Tracker(name, size) - this.name = name - this.id = this.tracker.id - this.tracker.on('change', delegateChange(this)) -} -util.inherits(TrackerStream, stream.Transform) + promise = new Promise(this[kHandlePromise]); + } -function delegateChange (trackerStream) { - return function (name, completion, tracker) { - trackerStream.emit('change', name, completion, trackerStream) + this[kLastPromise] = promise; + return promise; } -} - -TrackerStream.prototype._transform = function (data, encoding, cb) { - this.tracker.completeWork(data.length ? data.length : 1) - this.push(data) - cb() -} - -TrackerStream.prototype._flush = function (cb) { - this.tracker.finish() - cb() -} - -delegate(TrackerStream.prototype, 'tracker') - .method('completed') - .method('addWork') - .method('finish') +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } -/***/ }), + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); -/***/ 8074: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; -"use strict"; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); -var util = __nccwpck_require__(31669) -var TrackerBase = __nccwpck_require__(10165) + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error -var Tracker = module.exports = function (name, todo) { - TrackerBase.call(this, name) - this.workDone = 0 - this.workTodo = todo || 0 -} -util.inherits(Tracker, TrackerBase) + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } -Tracker.prototype.completed = function () { - return this.workTodo === 0 ? 0 : this.workDone / this.workTodo -} + iterator[kError] = err; + return; + } -Tracker.prototype.addWork = function (work) { - this.workTodo += work - this.emit('change', this.name, this.completed(), this) -} + var resolve = iterator[kLastResolve]; -Tracker.prototype.completeWork = function (work) { - this.workDone += work - if (this.workDone > this.workTodo) this.workDone = this.workTodo - this.emit('change', this.name, this.completed(), this) -} + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } -Tracker.prototype.finish = function () { - this.workTodo = this.workDone = 1 - this.emit('change', this.name, 1, this) -} + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; /***/ }), -/***/ 57888: -/***/ (function(module, exports, __nccwpck_require__) { +/***/ 70662: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; +"use strict"; -function slice(arrayLike, start) { - start = start|0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for(var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} -/** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ -var apply = function(fn/*, ...args*/) { - var args = slice(arguments, 1); - return function(/*callArgs*/) { - var callArgs = slice(arguments); - return fn.apply(null, args.concat(callArgs)); - }; -}; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } -var initialParams = function (fn) { - return function (/*...args, callback*/) { - var args = slice(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function fallback(fn) { - setTimeout(fn, 0); -} +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -function wrap(defer) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -var _defer; +var _require = __nccwpck_require__(64293), + Buffer = _require.Buffer; -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} +var _require2 = __nccwpck_require__(31669), + inspect = _require2.inspect; -var setImmediate$1 = wrap(_defer); +var custom = inspect && inspect.custom || 'inspect'; -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (isObject(result) && typeof result.then === 'function') { - result.then(function(value) { - invokeCallback(callback, null, value); - }, function(err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); } -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - setImmediate$1(rethrow, e); - } -} +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); -function rethrow(error) { - throw error; -} + this.head = null; + this.tail = null; + this.length = 0; + } -var supportsSymbol = typeof Symbol === 'function'; + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} + while (p = p.next) { + ret += s + p.data; + } -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; -} + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; -function applyEach$1(eachfn) { - return function(fns/*, ...args*/) { - var args = slice(arguments, 1); - var go = initialParams(function(args, callback) { - var that = this; - return eachfn(fns, function (fn, cb) { - wrapAsync(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } - else { - return go; - } - }; -} + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } -/** Built-in value references. */ -var Symbol$1 = root.Symbol; + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. -/** Used for built-in method references. */ -var objectProto = Object.prototype; + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } -/** Built-in value references. */ -var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; + break; + } -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; + ++c; + } - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - return result; -} + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} + break; + } -/** `Object#toString` result references. */ -var nullTag = '[object Null]'; -var undefinedTag = '[object Undefined]'; + ++c; + } -/** Built-in value references. */ -var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); -} + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]'; -var funcTag = '[object Function]'; -var genTag = '[object GeneratorFunction]'; -var proxyTag = '[object Proxy]'; + return BufferList; +}(); -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} +/***/ }), -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; +/***/ 36994: +/***/ ((module) => { -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} +"use strict"; + // undocumented cb() API, needed for core, not for public API -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} +function destroy(err, cb) { + var _this = this; -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -var breakLoop = {}; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. -} + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; -var getIterator = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - while (++index < n) { - result[index] = iteratee(index); + if (this._writableState) { + this._writableState.destroyed = true; } - return result; -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; + return this; } -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ -function stubFalse() { - return false; +function emitErrorNT(self, err) { + self.emit('error', err); } -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} -/** Detect free variable `module`. */ -var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; +/***/ }), -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined; +/***/ 40036: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). -/** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ -var isBuffer = nativeIsBuffer || stubFalse; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; +var ERR_STREAM_PREMATURE_CLOSE = __nccwpck_require__(97713)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE; -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$1 : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]'; -var arrayTag = '[object Array]'; -var boolTag = '[object Boolean]'; -var dateTag = '[object Date]'; -var errorTag = '[object Error]'; -var funcTag$1 = '[object Function]'; -var mapTag = '[object Map]'; -var numberTag = '[object Number]'; -var objectTag = '[object Object]'; -var regexpTag = '[object RegExp]'; -var setTag = '[object Set]'; -var stringTag = '[object String]'; -var weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]'; -var dataViewTag = '[object DataView]'; -var float32Tag = '[object Float32Array]'; -var float64Tag = '[object Float64Array]'; -var int8Tag = '[object Int8Array]'; -var int16Tag = '[object Int16Array]'; -var int32Tag = '[object Int32Array]'; -var uint8Tag = '[object Uint8Array]'; -var uint8ClampedTag = '[object Uint8ClampedArray]'; -var uint16Tag = '[object Uint16Array]'; -var uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; - -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; -} + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); + callback.apply(this, args); }; } -/** Detect free variable `exports`. */ -var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule$1 = freeExports$1 && "object" == 'object' && module && !module.nodeType && module; +function noop() {} -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports$1 && freeGlobal.process; +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - if (types) { - return types; - } + var writableEnded = stream._writableState && stream._writableState.finished; - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + var readableEnded = stream._readableState && stream._readableState.endEmitted; -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; + var onerror = function onerror(err) { + callback.call(stream, err); + }; -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + var onclose = function onclose() { + var err; -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$1.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); } - } - return result; -} -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; - return value === proto; -} + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); }; } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object); +module.exports = eos; -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; +/***/ }), -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$4.hasOwnProperty; +/***/ 57039: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$3.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} +"use strict"; -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); -} -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; - } -} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) - return null; - i++; - return {value: item.value, key: i}; - } -} +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function createObjectIterator(obj) { - var okeys = keys(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? {value: obj[key], key: key} : null; - }; -} +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } -function iterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); - } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function onlyOnce(fn) { - return function() { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} +var ERR_INVALID_ARG_TYPE = __nccwpck_require__(97713)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE; -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = once(callback || noop); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = iterator(obj); - var done = false; - var running = 0; - var looping = false; +function from(Readable, iterable, opts) { + var iterator; - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } - else if (value === breakLoop || (done && running <= 0)) { - done = true; - return callback(null); - } - else if (!looping) { - replenish(); - } - } + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); - function replenish () { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); - } - looping = false; - } + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. - replenish(); - }; -} + var reading = false; -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); -} - -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = once(callback || noop); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if ((++completed === length) || value === breakLoop) { - callback(null); - } + readable._read = function () { + if (!reading) { + reading = true; + next(); } + }; - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); - } -} + function next() { + return _next2.apply(this, arguments); + } -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = doLimit(eachOfLimit, Infinity); + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -var eachOf = function(coll, iteratee, callback) { - var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, wrapAsync(iteratee), callback); -}; + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(eachOf, obj, wrapAsync(iteratee), callback); - }; + return readable; } -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || noop; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); +module.exports = from; - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} +/***/ }), -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -var map = doParallel(_asyncMap); +/***/ 20740: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument, `fns`, is provided, it will - * return a function which lets you pass in the arguments as if it were a single - * function call. The signature is `(..args, callback)`. If invoked with any - * arguments, `callback` is required. - * @example - * - * async.applyEach([enableSearch, updateSchema], 'bucket', callback); - * - * // partial application example: - * async.each( - * buckets, - * async.applyEach([enableSearch, updateSchema]), - * callback - * ); - */ -var applyEach = applyEach$1(map); +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); - }; -} -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapLimit = doParallelLimit(_asyncMap); - -/** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapSeries = doLimit(mapLimit, 1); - -/** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument is provided, it will return - * a function which lets you pass in the arguments as if it were a single - * function call. - */ -var applyEachSeries = applyEach$1(mapSeries); - -/** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ -function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; +var eos; - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; } -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; +var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; } -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = createBaseFor(); - -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; } -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __nccwpck_require__(40036); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; } -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; +function call(fn) { + fn(); } -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; +function pipe(from, to) { + return from.pipe(to); } -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); } -/** - * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on - * their requirements. Each function can optionally depend on other functions - * being completed first, and each function is run as soon as its requirements - * are satisfied. - * - * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} itself the last item - * in the array. The object's key of a property serves as the name of the task - * defined by that property, i.e. can be used when specifying requirements for - * other tasks. The function receives one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback. Results are always returned; however, if an - * error occurs, no further `tasks` will be performed, and the results object - * will only contain partial results. Invoked with (err, results). - * @returns undefined - * @example - * - * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... - * }] - * }, callback); - * - * async.auto({ - * get_data: function(callback) { - * console.log('in get_data'); - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * console.log('in make_folder'); - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * console.log('in write_file', JSON.stringify(results)); - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * console.log('in email_link', JSON.stringify(results)); - * // once the file is written let's email a link to it... - * // results.write_file contains the filename returned by write_file. - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }, function(err, results) { - * console.log('err = ', err); - * console.log('results = ', results); - * }); - */ -var auto = function (tasks, concurrency, callback) { - if (typeof concurrency === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = once(callback || noop); - var keys$$1 = keys(tasks); - var numTasks = keys$$1.length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } - - var results = {}; - var runningTasks = 0; - var hasError = false; +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } - var listeners = Object.create(null); + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; - var readyTasks = []; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} - baseForOwn(tasks, function (task, key) { - if (!isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } +module.exports = pipeline; - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; +/***/ }), - arrayEach(dependencies, function (dependencyName) { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + - '` has a non-existent dependency `' + - dependencyName + '` in ' + - dependencies.join(', ')); - } - addListener(dependencyName, function () { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); +/***/ 3533: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - checkForDeadlocks(); - processQueue(); +"use strict"; - function enqueueTask(key, task) { - readyTasks.push(function () { - runTask(key, task); - }); - } - function processQueue() { - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while(readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } +var ERR_INVALID_OPT_VALUE = __nccwpck_require__(97713)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE; - } +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - taskListeners.push(fn); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); } - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - arrayEach(taskListeners, function (fn) { - fn(); - }); - processQueue(); - } + return Math.floor(hwm); + } // Default value - function runTask(key, task) { - if (hasError) return; + return state.objectMode ? 16 : 16 * 1024; +} - var taskCallback = onlyOnce(function(err, result) { - runningTasks--; - if (arguments.length > 2) { - result = slice(arguments, 1); - } - if (err) { - var safeResults = {}; - baseForOwn(results, function(val, rkey) { - safeResults[rkey] = val; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); +module.exports = { + getHighWaterMark: getHighWaterMark +}; - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); +/***/ }), - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } +/***/ 36238: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - arrayEach(getDependents(currentTask), function (dependent) { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } +module.exports = __nccwpck_require__(92413); - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } - } - function getDependents(taskName) { - var result = []; - baseForOwn(tasks, function (task, key) { - if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { - result.push(key); - } - }); - return result; - } -}; +/***/ }), -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); +/***/ 85519: +/***/ ((module, exports, __nccwpck_require__) => { - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; +var Stream = __nccwpck_require__(92413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = __nccwpck_require__(85209); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(58729); + exports.Duplex = __nccwpck_require__(13928); + exports.Transform = __nccwpck_require__(26753); + exports.PassThrough = __nccwpck_require__(4991); + exports.finished = __nccwpck_require__(40036); + exports.pipeline = __nccwpck_require__(20740); } -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} +/***/ }), -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; +/***/ 33717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; -var symbolToString = symbolProto ? symbolProto.toString : undefined; +var concatMap = __nccwpck_require__(86891); +var balanced = __nccwpck_require__(9417); -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} +module.exports = expandTop; -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); } -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); } -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ -function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; -/** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ -function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; + var parts = []; + var m = balanced('{', '}', str); - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} + if (!m) + return str.split(','); -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff'; -var rsComboMarksRange = '\\u0300-\\u036f'; -var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange = '\\u20d0-\\u20ff'; -var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; -var rsVarRange = '\\ufe0e\\ufe0f'; + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\u200d'; + parts.push.apply(parts, p); -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + return parts; +} -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff'; -var rsComboMarksRange$1 = '\\u0300-\\u036f'; -var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; -var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; -var rsVarRange$1 = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']'; -var rsCombo = '[' + rsComboRange$1 + ']'; -var rsFitz = '\\ud83c[\\udffb-\\udfff]'; -var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; -var rsNonAstral = '[^' + rsAstralRange$1 + ']'; -var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; -var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; -var rsZWJ$1 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?'; -var rsOptVar = '[' + rsVarRange$1 + ']?'; -var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; -var rsSeq = rsOptVar + reOptMod + rsOptJoin; -var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); } -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); +function identity(e) { + return e; } -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); } -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} -/** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ -function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; +function expand(str, isTop) { + var expansions = []; - return castSlice(strSymbols, start, end).join(''); -} + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; -var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /(=.+)?(\s*)$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } -function parseParams(func) { - func = func.toString().replace(STRIP_COMMENTS, ''); - func = func.match(FN_ARGS)[2].replace(' ', ''); - func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg){ - return trim(arg.replace(FN_ARG, '')); - }); - return func; -} + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } -/** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). The object's key of a property - * serves as the name of the task defined by that property, i.e. can be used - * when specifying requirements for other tasks. - * * The `callback` parameter is a `callback(err, result)` which must be called - * when finished, passing an `error` (which can be `null`) and the result of - * the function's execution. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback, and a `results` object with any completed - * task results, similar to `auto`. - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ -function autoInject(tasks, callback) { - var newTasks = {}; + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - baseForOwn(tasks, function (taskFn, key) { - var params; - var fnIsAsync = isAsync(taskFn); - var hasNoDeps = - (!fnIsAsync && taskFn.length === 1) || - (fnIsAsync && taskFn.length === 0); + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; - if (isArray(taskFn)) { - params = taskFn.slice(0, -1); - taskFn = taskFn[taskFn.length - 1]; + var N; - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - // remove callback param - if (!fnIsAsync) params.pop(); + N = []; - newTasks[key] = params.concat(newTask); + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } - function newTask(results, taskCb) { - var newArgs = arrayMap(params, function (name) { - return results[name]; - }); - newArgs.push(taskCb); - wrapAsync(taskFn).apply(null, newArgs); - } - }); + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } - auto(newTasks, callback); + return expansions; } -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} -DLL.prototype.removeLink = function(node) { - if (node.prev) node.prev.next = node.next; - else this.head = node.next; - if (node.next) node.next.prev = node.prev; - else this.tail = node.prev; +/***/ }), - node.prev = node.next = null; - this.length -= 1; - return node; -}; +/***/ 9239: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -DLL.prototype.empty = function () { - while(this.head) this.shift(); - return this; -}; +"use strict"; +/*jshint node:true */ -DLL.prototype.insertAfter = function(node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode; - else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; +var Buffer = __nccwpck_require__(64293).Buffer; // browserify +var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; -DLL.prototype.insertBefore = function(node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode; - else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; +module.exports = bufferEq; -DLL.prototype.unshift = function(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); -}; +function bufferEq(a, b) { -DLL.prototype.push = function(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); -}; + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } -DLL.prototype.shift = function() { - return this.head && this.removeLink(this.head); -}; + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } -DLL.prototype.pop = function() { - return this.tail && this.removeLink(this.tail); -}; + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for(var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; }; -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while(!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; }; -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; - - var processingScheduled = false; - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || noop - }; +/***/ }), - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } +/***/ 35684: +/***/ ((module) => { - if (!processingScheduled) { - processingScheduled = true; - setImmediate$1(function() { - processingScheduled = false; - q.process(); - }); - } +function Caseless (dict) { + this.dict = dict || {} +} +Caseless.prototype.set = function (name, value, clobber) { + if (typeof name === 'object') { + for (var i in name) { + this.set(i, name[i], value) } + } else { + if (typeof clobber === 'undefined') clobber = true + var has = this.has(name) - function _next(tasks) { - return function(err){ - numRunning -= 1; + if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value + else this.dict[has || name] = value + return has + } +} +Caseless.prototype.has = function (name) { + var keys = Object.keys(this.dict) + , name = name.toLowerCase() + ; + for (var i=0;i 0) { - workersList.splice(index, 1); - } - - task.callback.apply(task, arguments); - - if (err != null) { - q.error(err, task.data); - } - } +module.exports = function (dict) {return new Caseless(dict)} +module.exports.httpify = function (resp, headers) { + var c = new Caseless(headers) + resp.setHeader = function (key, value, clobber) { + if (typeof value === 'undefined') return + return c.set(key, value, clobber) + } + resp.hasHeader = function (key) { + return c.has(key) + } + resp.getHeader = function (key) { + return c.get(key) + } + resp.removeHeader = function (key) { + return c.del(key) + } + resp.headers = c.dict + return c +} - if (numRunning <= (q.concurrency - q.buffer) ) { - q.unsaturated(); - } - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } +/***/ }), - var isProcessing = false; - var q = { - _tasks: new DLL(), - concurrency: concurrency, - payload: payload, - saturated: noop, - unsaturated:noop, - buffer: concurrency / 4, - empty: noop, - drain: noop, - error: noop, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = noop; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while(!q.paused && numRunning < q.concurrency && q._tasks.length){ - var tasks = [], data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } +/***/ 78818: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - numRunning += 1; +"use strict"; - if (q._tasks.length === 0) { - q.empty(); - } +const ansiStyles = __nccwpck_require__(52068); +const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(59318); +const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +} = __nccwpck_require__(82415); - if (numRunning === q.concurrency) { - q.saturated(); - } +const {isArray} = Array; - var cb = onlyOnce(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function() { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { return; } - q.paused = false; - setImmediate$1(q.process); - } - }; - return q; -} - -/** - * A cargo of tasks for the worker function to complete. Cargo inherits all of - * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. - * @typedef {Object} CargoObject - * @memberOf module:ControlFlow - * @property {Function} length - A function returning the number of items - * waiting to be processed. Invoke like `cargo.length()`. - * @property {number} payload - An `integer` for determining how many tasks - * should be process per round. This property can be changed after a `cargo` is - * created to alter the payload on-the-fly. - * @property {Function} push - Adds `task` to the `queue`. The callback is - * called once the `worker` has finished processing the task. Instead of a - * single task, an array of `tasks` can be submitted. The respective callback is - * used for every task in the list. Invoke like `cargo.push(task, [callback])`. - * @property {Function} saturated - A callback that is called when the - * `queue.length()` hits the concurrency and further tasks will be queued. - * @property {Function} empty - A callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - A callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke like `cargo.idle()`. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke like `cargo.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke like `cargo.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. - */ - -/** - * Creates a `cargo` object with the specified payload. Tasks added to the - * cargo will be processed altogether (up to the `payload` limit). If the - * `worker` is in progress, the task is queued until it becomes available. Once - * the `worker` has completed some tasks, each callback of those tasks is - * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) - * for how `cargo` and `queue` work. - * - * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers - * at a time, cargo passes an array of tasks to a single worker, repeating - * when the worker is finished. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } - var cb = args[args.length - 1]; - if (typeof cb == 'function') { - args.pop(); - } else { - cb = noop; - } + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; - reduce(_functions, args, function(newargs, fn, cb) { - fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) { - var nextargs = slice(arguments, 1); - cb(err, nextargs); - })); - }, - function(err, results) { - cb.apply(that, [err].concat(results)); - }); - }; +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } } -/** - * Creates a function which is a composition of the passed asynchronous - * functions. Each function consumes the return value of the function that - * follows. Composing functions `f()`, `g()`, and `h()` would produce the result - * of `f(g(h()))`, only this version uses callbacks to obtain the return values. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name compose - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} an asynchronous function that is the composed - * asynchronous `functions` - * @example - * - * function add1(n, callback) { - * setTimeout(function () { - * callback(null, n + 1); - * }, 10); - * } - * - * function mul3(n, callback) { - * setTimeout(function () { - * callback(null, n * 3); - * }, 10); - * } - * - * var add1mul3 = async.compose(mul3, add1); - * add1mul3(4, function (err, result) { - * // result now equals 15 - * }); - */ -var compose = function(/*...args*/) { - return seq.apply(null, slice(arguments).reverse()); -}; +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); -var _concat = Array.prototype.concat; + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); -/** - * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. - * - * @name concatLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -var concatLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err /*, ...args*/) { - if (err) return callback(err); - return callback(null, slice(arguments, 1)); - }); - }, function(err, mapResults) { - var result = []; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - result = _concat.apply(result, mapResults[i]); - } - } + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); - return callback(err, result); - }); -}; + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; -/** - * Applies `iteratee` to each item in `coll`, concatenating the results. Returns - * the concatenated list. The `iteratee`s are called in parallel, and the - * results are concatenated as they return. There is no guarantee that the - * results array will be returned in the original order of `coll` passed to the - * `iteratee` function. - * - * @name concat - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @example - * - * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { - * // files is now a list of filenames that exist in the 3 directories - * }); - */ -var concat = doLimit(concatLimit, Infinity); + chalk.template.Instance = ChalkClass; -/** - * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. - * - * @name concatSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. - * The iteratee should complete with an array an array of results. - * Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -var concatSeries = doLimit(concatLimit, 1); - -/** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example - * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); - * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); - * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ -var constant = function(/*...values*/) { - var values = slice(arguments); - var args = [null].concat(values); - return function (/*...ignoredArgs, callback*/) { - var callback = arguments[arguments.length - 1]; - return callback.apply(this, args); - }; + return chalk.template; }; -/** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ -function identity(value) { - return value; +function Chalk(options) { + return chalkFactory(options); } -function _createTester(check, getResult) { - return function(eachfn, arr, iteratee, cb) { - cb = cb || noop; - var testPassed = false; - var testResult; - eachfn(arr, function(value, _, callback) { - iteratee(value, function(err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, breakLoop); - } else { - callback(); - } - }); - }, function(err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; +for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + } + }; } -function _findGetResult(v, x) { - return x; -} +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } +}; -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -var detect = doParallel(_createTester(identity, _findGetResult)); +for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectSeries = doLimit(detectLimit, 1); - -function consoleFunc(name) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - args.push(function (err/*, ...args*/) { - var args = slice(arguments, 1); - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } else if (console[name]) { - arrayEach(args, function (x) { - console[name](x); - }); - } - } - }); - wrapAsync(fn).apply(null, args); - }; +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; } -/** - * Logs the result of an [`async` function]{@link AsyncFunction} to the - * `console` using `console.dir` to display the properties of the resulting object. - * Only works in Node.js or in browsers that support `console.dir` and - * `console.error` (such as FF and Chrome). - * If multiple arguments are returned from the async function, - * `console.dir` is called on each argument in order. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ -var dir = consoleFunc('dir'); +const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } +}); -/** - * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in - * the order of operations, the arguments `test` and `fn` are switched. - * - * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. - * @name doDuring - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.during]{@link module:ControlFlow.during} - * @category Control Flow - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `fn`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error if one occurred, otherwise `null`. - */ -function doDuring(fn, test, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - args.push(check); - _test.apply(this, args); - } +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } + return { + open, + close, + openAll, + closeAll, + parent + }; +}; - check(null, true); +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } -} + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + }; -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto); -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - doWhilst(iteratee, function() { - return !test.apply(this, arguments); - }, callback); -} - -/** - * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that - * is passed a callback in the form of `function (err, truth)`. If error is - * passed to `test` or `fn`, the main callback is immediately called with the - * value of the error. - * - * @name during - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (callback). - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error, if one occurred, otherwise `null`. - * @example - * - * var count = 0; - * - * async.during( - * function (callback) { - * return callback(null, count < 5); - * }, - * function (callback) { - * count++; - * setTimeout(callback, 1000); - * }, - * function (err) { - * // 5 seconds have passed - * } - * ); - */ -function during(test, fn, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err) { - if (err) return callback(err); - _test(check); - } + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } + return builder; +}; - _test(check); -} +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} + let styler = self._styler; -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} + if (styler === undefined) { + return string; + } -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit$1(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -var eachSeries = doLimit(eachLimit$1, 1); - -/** - * Wrap an async function and ensure it calls its callback on a later tick of - * the event loop. If the function already calls its callback on a next tick, - * no extra deferral is added. This is useful for preventing stack overflows - * (`RangeError: Maximum call stack size exceeded`) and generally keeping - * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) - * contained. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * function sometimesAsync(arg, callback) { - * if (cache[arg]) { - * return callback(null, cache[arg]); // this would be synchronous!! - * } else { - * doSomeIO(arg, callback); // this IO would be asynchronous - * } - * } - * - * // this has a risk of stack overflows if many results are cached in a row - * async.mapSeries(args, sometimesAsync, done); - * - * // this will defer sometimesAsync's callback if necessary, - * // preventing stack overflows - * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); - */ -function ensureAsync(fn) { - if (isAsync(fn)) return fn; - return initialParams(function (args, callback) { - var sync = true; - args.push(function () { - var innerArgs = arguments; - if (sync) { - setImmediate$1(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }); -} + const {openAll, closeAll} = styler; + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); -function notId(v) { - return !v; -} + styler = styler.parent; + } + } -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -var every = doParallel(_createTester(notId, notId)); + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everyLimit = doParallelLimit(_createTester(notId, notId)); - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everySeries = doLimit(everyLimit, 1); - -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} + return openAll + string + closeAll; +}; -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} +let template; +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({index: index, value: x}); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, arrayMap(results.sort(function (a, b) { - return a.index - b.index; - }), baseProperty('value'))); - } - }); -} + if (!isArray(firstString) || !isArray(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } -function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, wrapAsync(iteratee), callback || noop); -} + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -var filter = doParallel(_filter); + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var filterLimit = doParallelLimit(_filter); - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -var filterSeries = doLimit(filterLimit, 1); - -/** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. - - * If an error is passed to the callback then `errback` is called with the - * error, and execution stops, otherwise it will never be called. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @example - * - * async.forever( - * function(next) { - * // next is suitable for passing to things that need a callback(err [, whatever]); - * // it will result in this function being called again. - * }, - * function(err) { - * // if next is called with a value in its first parameter, it will appear - * // in here as 'err', and execution will stop. - * } - * ); - */ -function forever(fn, errback) { - var done = onlyOnce(errback || noop); - var task = wrapAsync(ensureAsync(fn)); + if (template === undefined) { + template = __nccwpck_require__(20500); + } - function next(err) { - if (err) return done(err); - task(next); - } - next(); -} + return template(chalk, parts.join('')); +}; -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupByLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err, key) { - if (err) return callback(err); - return callback(null, {key: key, val: val}); - }); - }, function(err, mapResults) { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var hasOwnProperty = Object.prototype.hasOwnProperty; +Object.defineProperties(Chalk.prototype, styles); - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var key = mapResults[i].key; - var val = mapResults[i].val; +const chalk = Chalk(); // eslint-disable-line new-cap +chalk.supportsColor = stdoutColor; +chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap +chalk.stderr.supportsColor = stderrColor; - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } +module.exports = chalk; - return callback(err, result); - }); -}; -/** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @example - * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); - * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; - * }); - */ -var groupBy = doLimit(groupByLimit, Infinity); +/***/ }), -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupBySeries = doLimit(groupByLimit, 1); - -/** - * Logs the result of an `async` function to the `console`. Only works in - * Node.js or in browsers that support `console.log` and `console.error` (such - * as FF and Chrome). If multiple arguments are returned from the async - * function, `console.log` is called on each argument in order. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ -var log = consoleFunc('log'); +/***/ 20500: +/***/ ((module) => { -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -function mapValuesLimit(obj, limit, iteratee, callback) { - callback = once(callback || noop); - var newObj = {}; - var _iteratee = wrapAsync(iteratee); - eachOfLimit(obj, limit, function(val, key, next) { - _iteratee(val, key, function (err, result) { - if (err) return next(err); - newObj[key] = result; - next(); - }); - }, function (err) { - callback(err, newObj); - }); -} +"use strict"; -/** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @example - * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. - * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] - * // } - * }); - */ +const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; -var mapValues = doLimit(mapValuesLimit, Infinity); +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -var mapValuesSeries = doLimit(mapValuesLimit, 1); - -function has(obj, key) { - return key in obj; -} - -/** - * Caches the results of an async function. When creating a hash to store - * function results against, the callback is omitted from the hash and an - * optional hash function can be used. - * - * If no hash function is specified, the first argument is used as a hash key, - * which may work reasonably if it is a string or a data type that converts to a - * distinct string. Note that objects and arrays will not behave reasonably. - * Neither will cases where the other arguments are significant. In such cases, - * specify your own hash function. - * - * The cache of results is exposed as the `memo` property of the function - * returned by `memoize`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} hasher - An optional function for generating a custom hash - * for storing results. It has all the arguments applied to it apart from the - * callback, and must be synchronous. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * var slow_fn = function(name, callback) { - * // do something - * callback(null, result); - * }; - * var fn = async.memoize(slow_fn); - * - * // fn can now be used as if it were slow_fn - * fn('some name', function() { - * // callback - * }); - */ -function memoize(fn, hasher) { - var memo = Object.create(null); - var queues = Object.create(null); - hasher = hasher || identity; - var _fn = wrapAsync(fn); - var memoized = initialParams(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - setImmediate$1(function() { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn.apply(null, args.concat(function(/*args*/) { - var args = slice(arguments); - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; -} +function unescape(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTick`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -var _defer$1; + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } -if (hasNextTick) { - _defer$1 = process.nextTick; -} else if (hasSetImmediate) { - _defer$1 = setImmediate; -} else { - _defer$1 = fallback; -} + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } -var nextTick = wrap(_defer$1); + return ESCAPES.get(c) || c; +} -function _parallel(eachfn, tasks, callback) { - callback = callback || noop; - var results = isArrayLike(tasks) ? [] : {}; +function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; - eachfn(tasks, function (task, key, callback) { - wrapAsync(task)(function (err, result) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } -/** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} - * }); - */ -function parallelLimit(tasks, callback) { - _parallel(eachOf, tasks, callback); + return results; } -/** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - */ -function parallelLimit$1(tasks, limit, callback) { - _parallel(_eachOfLimit(limit), tasks, callback); -} - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {Function} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ - -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain = function() { - * console.log('all items have been processed'); - * }; - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * q.push({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ -var queue$1 = function (worker, concurrency) { - var _worker = wrapAsync(worker); - return queue(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; - -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * The `unshift` method was removed. - */ -var priorityQueue = function(worker, concurrency) { - // Start with a normal queue - var q = queue$1(worker, concurrency); - - // Override push to accept second parameter representing priority - q.push = function(data, priority, callback) { - if (callback == null) callback = noop; - if (typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } - - priority = priority || 0; - var nextNode = q._tasks.head; - while (nextNode && priority >= nextNode.priority) { - nextNode = nextNode.next; - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority: priority, - callback: callback - }; +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; - if (nextNode) { - q._tasks.insertBefore(nextNode, item); - } else { - q._tasks.push(item); - } - } - setImmediate$1(q.process); - }; + const results = []; + let matches; - // Remove unshift function - delete q.unshift; + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; - return q; -}; + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } -/** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns undefined - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ -function race(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync(tasks[i])(callback); - } + return results; } -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight (array, memo, iteratee, callback) { - var reversed = slice(array).reverse(); - reduce(reversed, memo, iteratee, callback); -} - -/** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ -function reflect(fn) { - var _fn = wrapAsync(fn); - return initialParams(function reflectOn(args, reflectCallback) { - args.push(function callback(error, cbArg) { - if (error) { - reflectCallback(null, { error: error }); - } else { - var value; - if (arguments.length <= 2) { - value = cbArg; - } else { - value = slice(arguments, 1); - } - reflectCallback(null, { value: value }); - } - }); +function buildStyle(chalk, styles) { + const enabled = {}; - return _fn.apply(this, args); - }); -} + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } -/** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ -function reflectAll(tasks) { - var results; - if (isArray(tasks)) { - results = arrayMap(tasks, reflect); - } else { - results = {}; - baseForOwn(tasks, function(task, key) { - results[key] = reflect.call(this, task); - }); - } - return results; -} + let current = chalk; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } -function reject$1(eachfn, arr, iteratee, callback) { - _filter(eachfn, arr, function(value, cb) { - iteratee(value, function(err, v) { - cb(err, !v); - }); - }, callback); -} + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -var reject = doParallel(reject$1); + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } -/** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectLimit = doParallelLimit(reject$1); - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectSeries = doLimit(rejectLimit, 1); - -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ -function constant$1(value) { - return function() { - return value; - }; + return current; } -/** - * Attempts to get a successful response from `task` no more than `times` times - * before returning an error. If the task is successful, the `callback` will be - * passed the result of the successful task. If all attempts fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - An optional callback which is called when the - * task has succeeded, or after the final failed attempt. It receives the `err` - * and `result` arguments of the last attempt at completing the `task`. Invoked - * with (err, results). - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ -function retry(opts, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; +module.exports = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) - }; + // eslint-disable-next-line max-params + temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); + chunks.push(chunk.join('')); - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || noop; - task = opts; - } else { - parseTimes(options, opts); - callback = callback || noop; - } + return chunks.join(''); +}; - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } - var _task = wrapAsync(task); +/***/ }), - var attempt = 1; - function retryAttempt() { - _task(function(err) { - if (err && attempt++ < options.times && - (typeof options.errorFilter != 'function' || - options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt)); - } else { - callback.apply(null, arguments); - } - }); - } +/***/ 82415: +/***/ ((module) => { - retryAttempt(); -} +"use strict"; -/** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ -var retryable = function (opts, task) { - if (!task) { - task = opts; - opts = null; - } - var _task = wrapAsync(task); - return initialParams(function (args, callback) { - function taskFn(cb) { - _task.apply(null, args.concat(cb)); - } - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); +const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } - }); + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; }; -/** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @example - * async.series([ - * function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }, - * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] - * }); - * - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback){ - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} - * }); - */ -function series(tasks, callback) { - _parallel(eachOfSeries, tasks, callback); -} +const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -var some = doParallel(_createTester(Boolean, identity)); + returnValue += string.substr(endIndex); + return returnValue; +}; -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someLimit = doParallelLimit(_createTester(Boolean, identity)); - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someSeries = doLimit(someLimit, 1); - -/** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @example - * - * async.sortBy(['file1','file2','file3'], function(file, callback) { - * fs.stat(file, function(err, stats) { - * callback(err, stats.mtime); - * }); - * }, function(err, results) { - * // results is now the original array of files sorted by - * // modified date - * }); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // ascending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x); - * }, function(err,result) { - * // result callback - * }); - * - * // descending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x*-1); //<- x*-1 instead of x, turns the order around - * }, function(err,result) { - * // result callback - * }); - */ -function sortBy (coll, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - map(coll, function (x, callback) { - _iteratee(x, function (err, criteria) { - if (err) return callback(err); - callback(null, {value: x, criteria: criteria}); - }); - }, function (err, results) { - if (err) return callback(err); - callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); - }); +module.exports = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +}; - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } -} -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = wrapAsync(asyncFn); +/***/ }), + +/***/ 97074: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return initialParams(function (args, callback) { - var timedOut = false; - var timer; +"use strict"; - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.supportsLanguage = exports.listLanguages = exports.highlight = void 0; +var hljs = __importStar(__nccwpck_require__(60082)); +var parse5 = __importStar(__nccwpck_require__(88933)); +var parse5_htmlparser2_tree_adapter_1 = __importDefault(__nccwpck_require__(9759)); +var theme_1 = __nccwpck_require__(81442); +function colorizeNode(node, theme, context) { + if (theme === void 0) { theme = {}; } + switch (node.type) { + case 'text': { + var text = node.data; + if (context === undefined) { + return (theme.default || theme_1.DEFAULT_THEME.default || theme_1.plain)(text); } - timedOut = true; - callback(error); + return text; } - - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); + case 'tag': { + var hljsClass = /hljs-(\w+)/.exec(node.attribs.class); + if (hljsClass) { + var token_1 = hljsClass[1]; + var nodeData = node.childNodes + .map(function (node) { return colorizeNode(node, theme, token_1); }) + .join(''); + return (theme[token_1] || theme_1.DEFAULT_THEME[token_1] || theme_1.plain)(nodeData); } - }); - - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeCeil = Math.ceil; -var nativeMax = Math.max; - -/** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ -function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; + // Return the data itself when the class name isn't prefixed with a highlight.js token prefix. + // This is common in instances of sublanguages (JSX, Markdown Code Blocks, etc.) + return node.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); + } + } + throw new Error('Invalid node type ' + node.type); } - -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); -} - -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); - */ -var times = doLimit(timeLimit, Infinity); - -/** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - */ -var timesSeries = doLimit(timeLimit, 1); - -/** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in series, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @example - * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc.push(item * 2) - * callback(null) - * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] - * }); - * - * @example - * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) - */ -function transform (coll, accumulator, iteratee, callback) { - if (arguments.length <= 3) { - callback = iteratee; - iteratee = accumulator; - accumulator = isArray(coll) ? [] : {}; - } - callback = once(callback || noop); - var _iteratee = wrapAsync(iteratee); - - eachOf(coll, function(v, k, cb) { - _iteratee(accumulator, v, k, cb); - }, function(err) { - callback(err, accumulator); +function colorize(code, theme) { + if (theme === void 0) { theme = {}; } + var fragment = parse5.parseFragment(code, { + treeAdapter: parse5_htmlparser2_tree_adapter_1.default, }); + return fragment.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); } - /** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. + * Apply syntax highlighting to `code` with ASCII color codes. The language is automatically + * detected if not set. * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing functions to - * run, each function is passed a `callback(err, result)` it must call on - * completion with an error `err` (which can be `null`) and an optional `result` - * value. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. + * ```ts + * import {highlight} from 'cli-highlight'; + * import * as fs from 'fs'; + * + * fs.readFile('package.json', 'utf8', (err: any, json: string) => { + * console.log('package.json:'); + * console.log(highlight(json)); * }); + * ``` * + * @param code The code to highlight + * @param options Optional options */ -function tryEach(tasks, callback) { - var error = null; - var result; - callback = callback || noop; - eachSeries(tasks, function(task, callback) { - wrapAsync(task)(function (err, res/*, ...args*/) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } else { - result = res; - } - error = err; - callback(!err); - }); - }, function () { - callback(error, result); - }); +function highlight(code, options) { + if (options === void 0) { options = {}; } + var html; + if (options.language) { + html = hljs.highlight(options.language, code, options.ignoreIllegals, options.continuation).value; + } + else { + html = hljs.highlightAuto(code, options.languageSubset).value; + } + return colorize(html, options.theme); } - +exports.highlight = highlight; /** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function + * Returns all supported languages */ -function unmemoize(fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; +function listLanguages() { + return hljs.listLanguages(); } - +exports.listLanguages = listLanguages; /** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - if (!test()) return callback(null); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = slice(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); + * Returns true if the language is supported + * @param name A language name, alias or file extension + */ +function supportsLanguage(name) { + return !!hljs.getLanguage(name); } +exports.supportsLanguage = supportsLanguage; +exports.default = highlight; +__exportStar(__nccwpck_require__(81442), exports); +//# sourceMappingURL=index.js.map -/** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function until(test, iteratee, callback) { - whilst(function() { - return !test.apply(this, arguments); - }, iteratee, callback); -} - -/** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ -var waterfall = function(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; +/***/ }), - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - args.push(onlyOnce(next)); - task.apply(null, args); - } +/***/ 81442: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - function next(err/*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask(slice(arguments, 1)); - } +"use strict"; - nextTask([]); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; - -/** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parse = exports.stringify = exports.toJson = exports.fromJson = exports.DEFAULT_THEME = exports.plain = void 0; +var chalk_1 = __importDefault(__nccwpck_require__(78818)); +/** + * Identity function for tokens that should not be styled (returns the input string as-is). + * See [[Theme]] for an example. + */ +var plain = function (codePart) { return codePart; }; +exports.plain = plain; +/** + * The default theme. It is possible to override just individual keys. + */ +exports.DEFAULT_THEME = { + /** + * keyword in a regular Algol-style language + */ + keyword: chalk_1.default.blue, + /** + * built-in or library object (constant, class, function) + */ + built_in: chalk_1.default.cyan, + /** + * user-defined type in a language with first-class syntactically significant types, like + * Haskell + */ + type: chalk_1.default.cyan.dim, + /** + * special identifier for a built-in value ("true", "false", "null") + */ + literal: chalk_1.default.blue, + /** + * number, including units and modifiers, if any. + */ + number: chalk_1.default.green, + /** + * literal regular expression + */ + regexp: chalk_1.default.red, + /** + * literal string, character + */ + string: chalk_1.default.red, + /** + * parsed section inside a literal string + */ + subst: exports.plain, + /** + * symbolic constant, interned string, goto label + */ + symbol: exports.plain, + /** + * class or class-level declaration (interfaces, traits, modules, etc) + */ + class: chalk_1.default.blue, + /** + * function or method declaration + */ + function: chalk_1.default.yellow, + /** + * name of a class or a function at the place of declaration + */ + title: exports.plain, + /** + * block of function arguments (parameters) at the place of declaration + */ + params: exports.plain, + /** + * comment + */ + comment: chalk_1.default.green, + /** + * documentation markup within comments + */ + doctag: chalk_1.default.green, + /** + * flags, modifiers, annotations, processing instructions, preprocessor directive, etc + */ + meta: chalk_1.default.grey, + /** + * keyword or built-in within meta construct + */ + 'meta-keyword': exports.plain, + /** + * string within meta construct + */ + 'meta-string': exports.plain, + /** + * heading of a section in a config file, heading in text markup + */ + section: exports.plain, + /** + * XML/HTML tag + */ + tag: chalk_1.default.grey, + /** + * name of an XML tag, the first word in an s-expression + */ + name: chalk_1.default.blue, + /** + * s-expression name from the language standard library + */ + 'builtin-name': exports.plain, + /** + * name of an attribute with no language defined semantics (keys in JSON, setting names in + * .ini), also sub-attribute within another highlighted object, like XML tag + */ + attr: chalk_1.default.cyan, + /** + * name of an attribute followed by a structured value part, like CSS properties + */ + attribute: exports.plain, + /** + * variable in a config or a template file, environment var expansion in a script + */ + variable: exports.plain, + /** + * list item bullet in text markup + */ + bullet: exports.plain, + /** + * code block in text markup + */ + code: exports.plain, + /** + * emphasis in text markup + */ + emphasis: chalk_1.default.italic, + /** + * strong emphasis in text markup + */ + strong: chalk_1.default.bold, + /** + * mathematical formula in text markup + */ + formula: exports.plain, + /** + * hyperlink in text markup + */ + link: chalk_1.default.underline, + /** + * quotation in text markup + */ + quote: exports.plain, + /** + * tag selector in CSS + */ + 'selector-tag': exports.plain, + /** + * #id selector in CSS + */ + 'selector-id': exports.plain, + /** + * .class selector in CSS + */ + 'selector-class': exports.plain, + /** + * [attr] selector in CSS + */ + 'selector-attr': exports.plain, + /** + * :pseudo selector in CSS + */ + 'selector-pseudo': exports.plain, + /** + * tag of a template language + */ + 'template-tag': exports.plain, + /** + * variable in a template language + */ + 'template-variable': exports.plain, + /** + * added or changed line in a diff + */ + addition: chalk_1.default.green, + /** + * deleted line in a diff + */ + deletion: chalk_1.default.red, + /** + * things not matched by any token + */ + default: exports.plain, +}; +/** + * Converts a [[JsonTheme]] with string values to a [[Theme]] with formatter functions. Used by [[parse]]. + */ +function fromJson(json) { + var theme = {}; + for (var _i = 0, _a = Object.keys(json); _i < _a.length; _i++) { + var key = _a[_i]; + var style = json[key]; + if (Array.isArray(style)) { + ; + theme[key] = style.reduce(function (previous, current) { return (current === 'plain' ? exports.plain : previous[current]); }, chalk_1.default); + } + else { + ; + theme[key] = chalk_1.default[style]; + } + } + return theme; +} +exports.fromJson = fromJson; +/** + * Converts a [[Theme]] with formatter functions to a [[JsonTheme]] with string values. Used by [[stringify]]. + */ +function toJson(theme) { + var jsonTheme = {}; + for (var _i = 0, _a = Object.keys(jsonTheme); _i < _a.length; _i++) { + var key = _a[_i]; + var style = jsonTheme[key]; + jsonTheme[key] = style._styles; + } + return jsonTheme; +} +exports.toJson = toJson; +/** + * Stringifies a [[Theme]] with formatter functions to a JSON string. * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) + * ```ts + * import chalk = require('chalk'); + * import {stringify} from 'cli-highlight'; + * import * as fs from 'fs'; * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. + * const myTheme: Theme = { + * keyword: chalk.red.bold, + * addition: chalk.green, + * deletion: chalk.red.strikethrough, + * number: plain + * } + * const json = stringify(myTheme); + * fs.writeFile('mytheme.json', json, (err: any) => { + * if (err) throw err; + * console.log('Theme saved'); + * }); + * ``` + */ +function stringify(theme) { + return JSON.stringify(toJson(theme)); +} +exports.stringify = stringify; +/** + * Parses a JSON string into a [[Theme]] with formatter functions. * - * @typedef {Function} AsyncFunction - * @static - */ - -/** - * Async is a utility module which provides straight-forward, powerful functions - * for working with asynchronous JavaScript. Although originally designed for - * use with [Node.js](http://nodejs.org) and installable via - * `npm install --save async`, it can also be used directly in the browser. - * @module async - * @see AsyncFunction - */ - - -/** - * A collection of `async` functions for manipulating collections, such as - * arrays and objects. - * @module Collections - */ - -/** - * A collection of `async` functions for controlling the flow through a script. - * @module ControlFlow - */ - -/** - * A collection of `async` utility functions. - * @module Utils - */ - -var index = { - apply: apply, - applyEach: applyEach, - applyEachSeries: applyEachSeries, - asyncify: asyncify, - auto: auto, - autoInject: autoInject, - cargo: cargo, - compose: compose, - concat: concat, - concatLimit: concatLimit, - concatSeries: concatSeries, - constant: constant, - detect: detect, - detectLimit: detectLimit, - detectSeries: detectSeries, - dir: dir, - doDuring: doDuring, - doUntil: doUntil, - doWhilst: doWhilst, - during: during, - each: eachLimit, - eachLimit: eachLimit$1, - eachOf: eachOf, - eachOfLimit: eachOfLimit, - eachOfSeries: eachOfSeries, - eachSeries: eachSeries, - ensureAsync: ensureAsync, - every: every, - everyLimit: everyLimit, - everySeries: everySeries, - filter: filter, - filterLimit: filterLimit, - filterSeries: filterSeries, - forever: forever, - groupBy: groupBy, - groupByLimit: groupByLimit, - groupBySeries: groupBySeries, - log: log, - map: map, - mapLimit: mapLimit, - mapSeries: mapSeries, - mapValues: mapValues, - mapValuesLimit: mapValuesLimit, - mapValuesSeries: mapValuesSeries, - memoize: memoize, - nextTick: nextTick, - parallel: parallelLimit, - parallelLimit: parallelLimit$1, - priorityQueue: priorityQueue, - queue: queue$1, - race: race, - reduce: reduce, - reduceRight: reduceRight, - reflect: reflect, - reflectAll: reflectAll, - reject: reject, - rejectLimit: rejectLimit, - rejectSeries: rejectSeries, - retry: retry, - retryable: retryable, - seq: seq, - series: series, - setImmediate: setImmediate$1, - some: some, - someLimit: someLimit, - someSeries: someSeries, - sortBy: sortBy, - timeout: timeout, - times: times, - timesLimit: timeLimit, - timesSeries: timesSeries, - transform: transform, - tryEach: tryEach, - unmemoize: unmemoize, - until: until, - waterfall: waterfall, - whilst: whilst, - - // aliases - all: every, - allLimit: everyLimit, - allSeries: everySeries, - any: some, - anyLimit: someLimit, - anySeries: someSeries, - find: detect, - findLimit: detectLimit, - findSeries: detectSeries, - forEach: eachLimit, - forEachSeries: eachSeries, - forEachLimit: eachLimit$1, - forEachOf: eachOf, - forEachOfSeries: eachOfSeries, - forEachOfLimit: eachOfLimit, - inject: reduce, - foldl: reduce, - foldr: reduceRight, - select: filter, - selectLimit: filterLimit, - selectSeries: filterSeries, - wrapSync: asyncify -}; - -exports['default'] = index; -exports.apply = apply; -exports.applyEach = applyEach; -exports.applyEachSeries = applyEachSeries; -exports.asyncify = asyncify; -exports.auto = auto; -exports.autoInject = autoInject; -exports.cargo = cargo; -exports.compose = compose; -exports.concat = concat; -exports.concatLimit = concatLimit; -exports.concatSeries = concatSeries; -exports.constant = constant; -exports.detect = detect; -exports.detectLimit = detectLimit; -exports.detectSeries = detectSeries; -exports.dir = dir; -exports.doDuring = doDuring; -exports.doUntil = doUntil; -exports.doWhilst = doWhilst; -exports.during = during; -exports.each = eachLimit; -exports.eachLimit = eachLimit$1; -exports.eachOf = eachOf; -exports.eachOfLimit = eachOfLimit; -exports.eachOfSeries = eachOfSeries; -exports.eachSeries = eachSeries; -exports.ensureAsync = ensureAsync; -exports.every = every; -exports.everyLimit = everyLimit; -exports.everySeries = everySeries; -exports.filter = filter; -exports.filterLimit = filterLimit; -exports.filterSeries = filterSeries; -exports.forever = forever; -exports.groupBy = groupBy; -exports.groupByLimit = groupByLimit; -exports.groupBySeries = groupBySeries; -exports.log = log; -exports.map = map; -exports.mapLimit = mapLimit; -exports.mapSeries = mapSeries; -exports.mapValues = mapValues; -exports.mapValuesLimit = mapValuesLimit; -exports.mapValuesSeries = mapValuesSeries; -exports.memoize = memoize; -exports.nextTick = nextTick; -exports.parallel = parallelLimit; -exports.parallelLimit = parallelLimit$1; -exports.priorityQueue = priorityQueue; -exports.queue = queue$1; -exports.race = race; -exports.reduce = reduce; -exports.reduceRight = reduceRight; -exports.reflect = reflect; -exports.reflectAll = reflectAll; -exports.reject = reject; -exports.rejectLimit = rejectLimit; -exports.rejectSeries = rejectSeries; -exports.retry = retry; -exports.retryable = retryable; -exports.seq = seq; -exports.series = series; -exports.setImmediate = setImmediate$1; -exports.some = some; -exports.someLimit = someLimit; -exports.someSeries = someSeries; -exports.sortBy = sortBy; -exports.timeout = timeout; -exports.times = times; -exports.timesLimit = timeLimit; -exports.timesSeries = timesSeries; -exports.transform = transform; -exports.tryEach = tryEach; -exports.unmemoize = unmemoize; -exports.until = until; -exports.waterfall = waterfall; -exports.whilst = whilst; -exports.all = every; -exports.allLimit = everyLimit; -exports.allSeries = everySeries; -exports.any = some; -exports.anyLimit = someLimit; -exports.anySeries = someSeries; -exports.find = detect; -exports.findLimit = detectLimit; -exports.findSeries = detectSeries; -exports.forEach = eachLimit; -exports.forEachSeries = eachSeries; -exports.forEachLimit = eachLimit$1; -exports.forEachOf = eachOf; -exports.forEachOfSeries = eachOfSeries; -exports.forEachOfLimit = eachOfLimit; -exports.inject = reduce; -exports.foldl = reduce; -exports.foldr = reduceRight; -exports.select = filter; -exports.selectLimit = filterLimit; -exports.selectSeries = filterSeries; -exports.wrapSync = asyncify; - -Object.defineProperty(exports, '__esModule', { value: true }); + * ```ts + * import * as fs from 'fs'; + * import {parse, highlight} from 'cli-highlight'; + * + * fs.readFile('mytheme.json', 'utf8', (err: any, json: string) => { + * if (err) throw err; + * const code = highlight('SELECT * FROM table', {theme: parse(json)}); + * console.log(code); + * }); + * ``` + */ +function parse(json) { + return fromJson(JSON.parse(json)); +} +exports.parse = parse; +//# sourceMappingURL=theme.js.map -}))); +/***/ }), +/***/ 88933: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/***/ }), +"use strict"; -/***/ 14812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = -{ - parallel : __nccwpck_require__(8210), - serial : __nccwpck_require__(50445), - serialOrdered : __nccwpck_require__(3578) -}; +const Parser = __nccwpck_require__(78180); +const Serializer = __nccwpck_require__(12450); +// Shorthands +exports.parse = function parse(html, options) { + const parser = new Parser(options); -/***/ }), + return parser.parse(html); +}; -/***/ 1700: -/***/ ((module) => { +exports.parseFragment = function parseFragment(fragmentContext, html, options) { + if (typeof fragmentContext === 'string') { + options = html; + html = fragmentContext; + fragmentContext = null; + } -// API -module.exports = abort; + const parser = new Parser(options); -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); + return parser.parseFragment(html, fragmentContext); +}; - // reset leftover jobs - state.jobs = {}; -} +exports.serialize = function(node, options) { + const serializer = new Serializer(node, options); -/** - * Cleans up leftover job by invoking abort function for the provided job id - * - * @this state - * @param {string|number} key - job id to abort - */ -function clean(key) -{ - if (typeof this.jobs[key] == 'function') - { - this.jobs[key](); - } -} + return serializer.serialize(); +}; /***/ }), -/***/ 72794: +/***/ 97391: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var defer = __nccwpck_require__(15295); - -// API -module.exports = async; - -/** - * Runs provided callback asynchronously - * even if callback itself is not - * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback - */ -function async(callback) -{ - var isAsync = false; +/* MIT license */ +/* eslint-disable no-mixed-operators */ +const cssKeywords = __nccwpck_require__(78510); - // check if async happened - defer(function() { isAsync = true; }); +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; +const reverseKeywords = {}; +for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; } +const convert = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; -/***/ }), +module.exports = convert; -/***/ 15295: -/***/ ((module) => { +// Hide .channels and .labels properties +for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } -module.exports = defer; + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } -/** - * Runs provided function on next iteration of the event loop - * - * @param {function} fn - function to run - */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } + const {channels, labels} = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); } +convert.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; -/***/ }), + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } -/***/ 9023: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + h = Math.min(h * 60, 360); -var async = __nccwpck_require__(72794) - , abort = __nccwpck_require__(1700) - ; + if (h < 0) { + h += 360; + } -// API -module.exports = iterate; + const l = (min + max) / 2; -/** - * Iterates over each job object - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {object} state - current job status - * @param {function} callback - invoked when all elements processed - */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; - } + return [h, s * 100, l * 100]; +}; - // clean up jobs - delete state.jobs[key]; +convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; - if (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); - } - else - { - state.results[key] = output; - } + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; - // return salvaged results - callback(error, state.results); - }); -} + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); -/** - * Runs iterator over provided job element - * - * @param {function} iterator - iterator to invoke - * @param {string|number} key - key/index of the element in the list of jobs - * @param {mixed} item - job description - * @param {function} callback - invoked after iterator is done with the job - * @returns {function|mixed} - job abort function or something else - */ -function runJob(iterator, key, item, callback) -{ - var aborter; + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } - // allow shortcut if iterator expects only two arguments - if (iterator.length == 2) - { - aborter = iterator(item, async(callback)); - } - // otherwise go with full three arguments - else - { - aborter = iterator(item, key, async(callback)); - } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } - return aborter; -} + return [ + h * 360, + s * 100, + v * 100 + ]; +}; +convert.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); -/***/ }), + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); -/***/ 42474: -/***/ ((module) => { + return [h, w * 100, b * 100]; +}; -// API -module.exports = state; +convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; -/** - * Creates initial state object - * for iteration over list - * - * @param {array|object} list - list to iterate over - * @param {function|null} sortMethod - function to use for keys sort, - * or `null` to keep them as is - * @returns {object} - initial state object - */ -function state(list, sortMethod) -{ - var isNamedList = !Array.isArray(list) - , initState = - { - index : 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs : {}, - results : isNamedList ? {} : [], - size : isNamedList ? Object.keys(list).length : list.length - } - ; + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; - if (sortMethod) - { - // sort array keys based on it's values - // sort object's keys just on own merit - initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) - { - return sortMethod(list[a], list[b]); - }); - } + return [c * 100, m * 100, y * 100, k * 100]; +}; - return initState; +function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); } +convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } -/***/ }), - -/***/ 37942: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let currentClosestDistance = Infinity; + let currentClosestKeyword; -var abort = __nccwpck_require__(1700) - , async = __nccwpck_require__(72794) - ; + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; -// API -module.exports = terminator; + // Compute comparative distance + const distance = comparativeDistance(rgb, value); -/** - * Terminates jobs in the attached state context - * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination - */ -function terminator(callback) -{ - if (!Object.keys(this.jobs).length) - { - return; - } + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } - // fast forward iteration index - this.index = this.size; + return currentClosestKeyword; +}; - // abort jobs - abort(this); +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; - // send back results we have so far - async(callback)(null, this.results); -} +convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); -/***/ }), + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); -/***/ 8210: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return [x * 100, y * 100, z * 100]; +}; -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; +convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; -// Public API -module.exports = parallel; + x /= 95.047; + y /= 100; + z /= 108.883; -/** - * Runs iterator over provided array elements in parallel - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function parallel(list, iterator, callback) -{ - var state = initState(list); + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); + return [l, a, b]; +}; - state.index++; - } +convert.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; - return terminator.bind(state, callback); -} + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } -/***/ }), + const t1 = 2 * l - t2; -/***/ 50445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } -var serialOrdered = __nccwpck_require__(3578); + if (t3 > 1) { + t3--; + } -// Public API -module.exports = serial; + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } -/** - * Runs iterator over provided array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); -} + rgb[i] = val * 255; + } + return rgb; +}; -/***/ }), +convert.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); -/***/ 3578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; + return [h, sv * 100, v * 100]; +}; -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; +convert.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; -/** - * Runs iterator over provided sorted array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} sortMethod - custom sort function - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serialOrdered(list, iterator, sortMethod, callback) -{ - var state = initState(list, sortMethod); + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; - } + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; - state.index++; +convert.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; - } + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; - // done here - callback(null, state.results); - }); + return [h, sl * 100, l * 100]; +}; - return terminator.bind(state, callback); -} +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; -/* - * -- Sort methods - */ + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } -/** - * sort helper to sort array elements in ascending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function ascending(a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; -} + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; -/** - * sort helper to sort array elements in descending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function descending(a, b) -{ - return -1 * ascending(a, b); -} + if ((i & 0x01) !== 0) { + f = 1 - f; + } + const n = wh + f * (v - wh); // Linear interpolation -/***/ }), + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ -/***/ 96545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return [r * 255, g * 255, b * 255]; +}; -module.exports = __nccwpck_require__(52618); +convert.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; -/***/ }), + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); -/***/ 68104: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return [r * 255, g * 255, b * 255]; +}; -"use strict"; +convert.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); -var utils = __nccwpck_require__(20328); -var settle = __nccwpck_require__(13211); -var buildFullPath = __nccwpck_require__(41934); -var buildURL = __nccwpck_require__(30646); -var http = __nccwpck_require__(98605); -var https = __nccwpck_require__(57211); -var httpFollow = __nccwpck_require__(67707).http; -var httpsFollow = __nccwpck_require__(67707).https; -var url = __nccwpck_require__(78835); -var zlib = __nccwpck_require__(78761); -var pkg = __nccwpck_require__(20696); -var createError = __nccwpck_require__(15226); -var enhanceError = __nccwpck_require__(21516); + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; -var isHttps = /https:?/; + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; -/** - * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} proxy - * @param {string} location - */ -function setProxy(options, proxy, location) { - options.hostname = proxy.host; - options.host = proxy.host; - options.port = proxy.port; - options.path = location; + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; - // Basic proxy authorization - if (proxy.auth) { - var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); - // If a proxy is used, any redirects must also pass through the proxy - options.beforeRedirect = function beforeRedirect(redirection) { - redirection.headers.host = redirection.host; - setProxy(redirection, proxy, redirection.href); - }; -} + return [r * 255, g * 255, b * 255]; +}; -/*eslint consistent-return:0*/ -module.exports = function httpAdapter(config) { - return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { - var resolve = function resolve(value) { - resolvePromise(value); - }; - var reject = function reject(value) { - rejectPromise(value); - }; - var data = config.data; - var headers = config.headers; +convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; - // Set User-Agent (required by some servers) - // Only set header if it hasn't been set in config - // See https://github.com/axios/axios/issues/69 - if (!headers['User-Agent'] && !headers['user-agent']) { - headers['User-Agent'] = 'axios/' + pkg.version; - } + x /= 95.047; + y /= 100; + z /= 108.883; - if (data && !utils.isStream(data)) { - if (Buffer.isBuffer(data)) { - // Nothing to do... - } else if (utils.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(createError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - config - )); - } + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - // Add Content-Length header if data exists - headers['Content-Length'] = data.length; - } + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); - // HTTP basic authentication - var auth = undefined; - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - auth = username + ':' + password; - } + return [l, a, b]; +}; - // Parse url - var fullPath = buildFullPath(config.baseURL, config.url); - var parsed = url.parse(fullPath); - var protocol = parsed.protocol || 'http:'; +convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; - if (!auth && parsed.auth) { - var urlAuth = parsed.auth.split(':'); - var urlUsername = urlAuth[0] || ''; - var urlPassword = urlAuth[1] || ''; - auth = urlUsername + ':' + urlPassword; - } + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; - if (auth) { - delete headers.Authorization; - } + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - var isHttpsRequest = isHttps.test(protocol); - var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + x *= 95.047; + y *= 100; + z *= 108.883; - var options = { - path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), - method: config.method.toUpperCase(), - headers: headers, - agent: agent, - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth: auth - }; + return [x, y, z]; +}; - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname; - options.port = parsed.port; - } +convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; - var proxy = config.proxy; - if (!proxy && proxy !== false) { - var proxyEnv = protocol.slice(0, -1) + '_proxy'; - var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; - if (proxyUrl) { - var parsedProxyUrl = url.parse(proxyUrl); - var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; - var shouldProxy = true; + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; - if (noProxyEnv) { - var noProxy = noProxyEnv.split(',').map(function trim(s) { - return s.trim(); - }); + if (h < 0) { + h += 360; + } - shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { - if (!proxyElement) { - return false; - } - if (proxyElement === '*') { - return true; - } - if (proxyElement[0] === '.' && - parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { - return true; - } + const c = Math.sqrt(a * a + b * b); - return parsed.hostname === proxyElement; - }); - } + return [l, c, h]; +}; - if (shouldProxy) { - proxy = { - host: parsedProxyUrl.hostname, - port: parsedProxyUrl.port, - protocol: parsedProxyUrl.protocol - }; +convert.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; - if (parsedProxyUrl.auth) { - var proxyUrlAuth = parsedProxyUrl.auth.split(':'); - proxy.auth = { - username: proxyUrlAuth[0], - password: proxyUrlAuth[1] - }; - } - } - } - } + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); - if (proxy) { - options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); - setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); - } + return [l, a, b]; +}; - var transport; - var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsProxy ? https : http; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - transport = isHttpsProxy ? httpsFollow : httpFollow; - } +convert.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; - } + value = Math.round(value / 50); - // Create the request - var req = transport.request(options, function handleResponse(res) { - if (req.aborted) return; + if (value === 0) { + return 30; + } - // uncompress the response body transparently if required - var stream = res; + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); - // return the last request in case of redirects - var lastRequest = res.req || req; + if (value === 2) { + ansi += 60; + } + return ansi; +}; - // if no content, is HEAD request or decompress disabled we should not decompress - if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { - switch (res.headers['content-encoding']) { - /*eslint default-case:0*/ - case 'gzip': - case 'compress': - case 'deflate': - // add the unzipper to the body stream processing pipeline - stream = stream.pipe(zlib.createUnzip()); +convert.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - } - } +convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; - var response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: res.headers, - config: config, - request: lastRequest - }; + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } - if (config.responseType === 'stream') { - response.data = stream; - settle(resolve, reject, response); - } else { - var responseBuffer = []; - stream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); + if (r > 248) { + return 231; + } - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { - stream.destroy(); - reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - config, null, lastRequest)); - } - }); + return Math.round(((r - 8) / 247) * 24) + 232; + } - stream.on('error', function handleStreamError(err) { - if (req.aborted) return; - reject(enhanceError(err, config, null, lastRequest)); - }); + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); - stream.on('end', function handleStreamEnd() { - var responseData = Buffer.concat(responseBuffer); - if (config.responseType !== 'arraybuffer') { - responseData = responseData.toString(config.responseEncoding); - if (!config.responseEncoding || config.responseEncoding === 'utf8') { - responseData = utils.stripBOM(responseData); - } - } + return ansi; +}; - response.data = responseData; - settle(resolve, reject, response); - }); - } - }); +convert.ansi16.rgb = function (args) { + let color = args % 10; - // Handle errors - req.on('error', function handleRequestError(err) { - if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return; - reject(enhanceError(err, config, null, req)); - }); + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } - // Handle request timeout - if (config.timeout) { - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devoring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(config.timeout, function handleRequestTimeout() { - req.abort(); - reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); - }); - } + color = color / 10.5 * 255; - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (req.aborted) return; + return [color, color, color]; + } - req.abort(); - reject(cancel); - }); - } + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; - // Send the request - if (utils.isStream(data)) { - data.on('error', function handleStreamError(err) { - reject(enhanceError(err, config, null, req)); - }).pipe(req); - } else { - req.end(data); - } - }); + return [r, g, b]; }; +convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } -/***/ }), - -/***/ 3454: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + args -= 16; -"use strict"; + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; + return [r, g, b]; +}; -var utils = __nccwpck_require__(20328); -var settle = __nccwpck_require__(13211); -var cookies = __nccwpck_require__(21545); -var buildURL = __nccwpck_require__(30646); -var buildFullPath = __nccwpck_require__(41934); -var parseHeaders = __nccwpck_require__(86455); -var isURLSameOrigin = __nccwpck_require__(33608); -var createError = __nccwpck_require__(15226); +convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; - if (utils.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } +convert.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } - var request = new XMLHttpRequest(); + let colorString = match[0]; - // HTTP basic authentication - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } - var fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; - // Set the request timeout in MS - request.timeout = config.timeout; + return [r, g, b]; +}; - // Listen for ready state - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } +convert.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } - // Prepare the response - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } - settle(resolve, reject, response); + hue /= 6; + hue %= 1; - // Clean up request - request = null; - }; + return [hue * 360, chroma * 100, grayscale * 100]; +}; - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } +convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; - reject(createError('Request aborted', config, 'ECONNABORTED', request)); + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); - // Clean up request - request = null; - }; + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError('Network Error', config, null, request)); + return [hsl[0], c * 100, f * 100]; +}; - // Clean up request - request = null; - }; +convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; - // Handle timeout - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', - request)); + const c = s * v; + let f = 0; - // Clean up request - request = null; - }; + if (c < 1.0) { + f = (v - c) / (1 - c); + } - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (utils.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; + return [hsv[0], c * 100, f * 100]; +}; - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } +convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; - // Add responseType to request if needed - if (config.responseType) { - try { - request.responseType = config.responseType; - } catch (e) { - // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. - // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. - if (config.responseType !== 'json') { - throw e; - } - } - } + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } + mg = (1.0 - c) * g; - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (!request) { - return; - } +convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; - request.abort(); - reject(cancel); - // Clean up request - request = null; - }); - } + const v = c + g * (1.0 - c); + let f = 0; - if (!requestData) { - requestData = null; - } + if (v > 0.0) { + f = c / v; + } - // Send the request - request.send(requestData); - }); + return [hcg[0], f * 100, v * 100]; }; +convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; -/***/ }), + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; -/***/ 52618: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } -"use strict"; + return [hcg[0], s * 100, l * 100]; +}; +convert.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; -var utils = __nccwpck_require__(20328); -var bind = __nccwpck_require__(77065); -var Axios = __nccwpck_require__(98178); -var mergeConfig = __nccwpck_require__(74831); -var defaults = __nccwpck_require__(98190); +convert.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; -/** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ -function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind(Axios.prototype.request, context); + if (c < 1) { + g = (v - c) / (1 - c); + } - // Copy axios.prototype to instance - utils.extend(instance, Axios.prototype, context); + return [hwb[0], c * 100, g * 100]; +}; - // Copy context to instance - utils.extend(instance, context); +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; - return instance; -} +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; -// Create the default instance to be exported -var axios = createInstance(defaults); +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; -// Expose Axios class to allow class inheritance -axios.Axios = Axios; +convert.gray.hsl = function (args) { + return [0, 0, args[0]]; +}; -// Factory for creating new instances -axios.create = function create(instanceConfig) { - return createInstance(mergeConfig(axios.defaults, instanceConfig)); +convert.gray.hsv = convert.gray.hsl; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; }; -// Expose Cancel & CancelToken -axios.Cancel = __nccwpck_require__(98875); -axios.CancelToken = __nccwpck_require__(71587); -axios.isCancel = __nccwpck_require__(64057); +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; }; -axios.spread = __nccwpck_require__(74850); -// Expose isAxiosError -axios.isAxiosError = __nccwpck_require__(60650); +convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; -module.exports = axios; + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; -// Allow use of default import syntax in TypeScript -module.exports.default = axios; +convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; /***/ }), -/***/ 98875: -/***/ ((module) => { +/***/ 86931: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const conversions = __nccwpck_require__(97391); +const route = __nccwpck_require__(30880); +const convert = {}; -/** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ -function Cancel(message) { - this.message = message; -} +const models = Object.keys(conversions); -Cancel.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); -}; +function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } -Cancel.prototype.__CANCEL__ = true; + if (arg0.length > 1) { + args = arg0; + } -module.exports = Cancel; + return fn(args); + }; + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } -/***/ }), + return wrappedFn; +} -/***/ 71587: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; -"use strict"; + if (arg0 === undefined || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } -var Cancel = __nccwpck_require__(98875); + const result = fn(args); -/** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ -function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } - var resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); + return result; + }; - var token = this; - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; - } + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } - token.reason = new Cancel(message); - resolvePromise(token.reason); - }); + return wrappedFn; } -/** - * Throws a `Cancel` if cancellation has been requested. - */ -CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } -}; +models.forEach(fromModel => { + convert[fromModel] = {}; -/** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ -CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; -}; + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); -module.exports = CancelToken; + const routes = route(fromModel); + const routeModels = Object.keys(routes); + routeModels.forEach(toModel => { + const fn = routes[toModel]; -/***/ }), + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); -/***/ 64057: -/***/ ((module) => { +module.exports = convert; -"use strict"; +/***/ }), -module.exports = function isCancel(value) { - return !!(value && value.__CANCEL__); -}; +/***/ 30880: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const conversions = __nccwpck_require__(97391); -/***/ }), +/* + This function routes a model to all other models. -/***/ 98178: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). -"use strict"; + conversions that are not possible simply are not included. +*/ +function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); -var utils = __nccwpck_require__(20328); -var buildURL = __nccwpck_require__(30646); -var InterceptorManager = __nccwpck_require__(3214); -var dispatchRequest = __nccwpck_require__(85062); -var mergeConfig = __nccwpck_require__(74831); + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ -function Axios(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; + return graph; } -/** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ -Axios.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } - - config = mergeConfig(this.defaults, config); +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop - // Set config.method - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } + graph[fromModel].distance = 0; - // Hook up interceptors middleware - var chain = [dispatchRequest, undefined]; - var promise = Promise.resolve(config); + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - chain.unshift(interceptor.fulfilled, interceptor.rejected); - }); + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - chain.push(interceptor.fulfilled, interceptor.rejected); - }); + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } + return graph; +} - return promise; -}; +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} -Axios.prototype.getUri = function getUri(config) { - config = mergeConfig(this.defaults, config); - return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); -}; +function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; -// Provide aliases for supported request methods -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; -}); - -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, data, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: data - })); - }; -}); - -module.exports = Axios; - - -/***/ }), - -/***/ 3214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + fn.conversion = path; + return fn; +} -var utils = __nccwpck_require__(20328); +module.exports = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; -function InterceptorManager() { - this.handlers = []; -} + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; -/** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ -InterceptorManager.prototype.use = function use(fulfilled, rejected) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected - }); - return this.handlers.length - 1; -}; + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } -/** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - */ -InterceptorManager.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } -}; + conversion[toModel] = wrapConversion(toModel, graph); + } -/** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ -InterceptorManager.prototype.forEach = function forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); + return conversion; }; -module.exports = InterceptorManager; /***/ }), -/***/ 41934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 78510: +/***/ ((module) => { "use strict"; - - -var isAbsoluteURL = __nccwpck_require__(41301); -var combineURLs = __nccwpck_require__(57189); - -/** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path - */ -module.exports = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -}; + + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; /***/ }), -/***/ 15226: +/***/ 85443: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -var enhanceError = __nccwpck_require__(21516); - -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ -module.exports = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError(error, config, code, request, response); -}; - - -/***/ }), - -/***/ 85062: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var util = __nccwpck_require__(31669); +var Stream = __nccwpck_require__(92413).Stream; +var DelayedStream = __nccwpck_require__(18611); -"use strict"; +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); -var utils = __nccwpck_require__(20328); -var transformData = __nccwpck_require__(19812); -var isCancel = __nccwpck_require__(64057); -var defaults = __nccwpck_require__(98190); +CombinedStream.create = function(options) { + var combinedStream = new this(); -/** - * Throws a `Cancel` if cancellation has been requested. - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; } -} - -/** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled - */ -module.exports = function dispatchRequest(config) { - throwIfCancellationRequested(config); - // Ensure headers exist - config.headers = config.headers || {}; + return combinedStream; +}; - // Transform request data - config.data = transformData( - config.data, - config.headers, - config.transformRequest - ); +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; - // Flatten headers - config.headers = utils.merge( - config.headers.common || {}, - config.headers[config.method] || {}, - config.headers - ); +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); - utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - function cleanHeaderConfig(method) { - delete config.headers[method]; + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; } - ); - - var adapter = config.adapter || defaults.adapter; - - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - - // Transform response data - response.data = transformData( - response.data, - response.headers, - config.transformResponse - ); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); + this._handleErrors(stream); - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData( - reason.response.data, - reason.response.headers, - config.transformResponse - ); - } + if (this.pauseStreams) { + stream.pause(); } + } - return Promise.reject(reason); - }); + this._streams.push(stream); + return this; }; +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; -/***/ }), - -/***/ 21516: -/***/ ((module) => { - -"use strict"; - +CombinedStream.prototype._getNext = function() { + this._currentStream = null; -/** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ -module.exports = function enhanceError(error, config, code, request, response) { - error.config = config; - if (code) { - error.code = code; + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call } - error.request = request; - error.response = response; - error.isAxiosError = true; - - error.toJSON = function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code - }; - }; - return error; + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } }; +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); -/***/ }), - -/***/ 74831: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(20328); - -/** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ -module.exports = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - var valueFromConfig2Keys = ['url', 'method', 'data']; - var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; - var defaultToConfig2Keys = [ - 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', - 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', - 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', - 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', - 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' - ]; - var directMergeKeys = ['validateStatus']; - function getMergedValue(target, source) { - if (utils.isPlainObject(target) && utils.isPlainObject(source)) { - return utils.merge(target, source); - } else if (utils.isPlainObject(source)) { - return utils.merge({}, source); - } else if (utils.isArray(source)) { - return source.slice(); - } - return source; + if (typeof stream == 'undefined') { + this.end(); + return; } - function mergeDeepProperties(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(config1[prop], config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - config[prop] = getMergedValue(undefined, config1[prop]); - } + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; } - utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(undefined, config2[prop]); - } - }); - - utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); - - utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - config[prop] = getMergedValue(undefined, config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - config[prop] = getMergedValue(undefined, config1[prop]); - } - }); - - utils.forEach(directMergeKeys, function merge(prop) { - if (prop in config2) { - config[prop] = getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - config[prop] = getMergedValue(undefined, config1[prop]); + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); } - }); - var axiosKeys = valueFromConfig2Keys - .concat(mergeDeepPropertiesKeys) - .concat(defaultToConfig2Keys) - .concat(directMergeKeys); - - var otherKeys = Object - .keys(config1) - .concat(Object.keys(config2)) - .filter(function filterAxiosKeys(key) { - return axiosKeys.indexOf(key) === -1; - }); - - utils.forEach(otherKeys, mergeDeepProperties); - - return config; + this._pipeNext(stream); + }.bind(this)); }; +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; -/***/ }), - -/***/ 13211: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var createError = __nccwpck_require__(15226); - -/** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - */ -module.exports = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError( - 'Request failed with status code ' + response.status, - response.config, - null, - response.request, - response - )); + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; } -}; - - -/***/ }), - -/***/ 19812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -var utils = __nccwpck_require__(20328); + var value = stream; + this.write(value); + this._getNext(); +}; -/** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data - */ -module.exports = function transformData(data, headers, fns) { - /*eslint no-param-reassign:0*/ - utils.forEach(fns, function transform(fn) { - data = fn(data, headers); +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); }); - - return data; }; - -/***/ }), - -/***/ 98190: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(20328); -var normalizeHeaderName = __nccwpck_require__(36240); - -var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' +CombinedStream.prototype.write = function(data) { + this.emit('data', data); }; -function setContentTypeIfUnset(headers, value) { - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } -} - -function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = __nccwpck_require__(3454); - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = __nccwpck_require__(68104); +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; } - return adapter; -} - -var defaults = { - adapter: getDefaultAdapter(), - - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - if (utils.isFormData(data) || - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - if (utils.isObject(data)) { - setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); - return JSON.stringify(data); - } - return data; - }], - - transformResponse: [function transformResponse(data) { - /*eslint no-param-reassign:0*/ - if (typeof data === 'string') { - try { - data = JSON.parse(data); - } catch (e) { /* Ignore */ } - } - return data; - }], - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - - maxContentLength: -1, - maxBodyLength: -1, - - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - } + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); }; -defaults.headers = { - common: { - 'Accept': 'application/json, text/plain, */*' +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); } -}; - -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); - -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); -}); - -module.exports = defaults; - - -/***/ }), - -/***/ 77065: -/***/ ((module) => { - -"use strict"; - -module.exports = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - return fn.apply(thisArg, args); - }; + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); }; +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; -/***/ }), - -/***/ 30646: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(20328); +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; -function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); -} +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ -module.exports = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; } - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - - utils.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils.forEach(val, function parseValue(v) { - if (utils.isDate(v)) { - v = v.toISOString(); - } else if (utils.isObject(v)) { - v = JSON.stringify(v); - } - parts.push(encode(key) + '=' + encode(v)); - }); - }); + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; - serializedParams = parts.join('&'); - } +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; } - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; } +}; - return url; +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); }; /***/ }), -/***/ 57189: +/***/ 86891: /***/ ((module) => { -"use strict"; - - -/** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL - */ -module.exports = function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; }; - -/***/ }), - -/***/ 21545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(20328); - -module.exports = ( - utils.isStandardBrowserEnv() ? - - // Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); - - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } - - if (utils.isString(path)) { - cookie.push('path=' + path); - } - - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } - - if (secure === true) { - cookie.push('secure'); - } - - document.cookie = cookie.join('; '); - }, - - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, - - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : - - // Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })() -); +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; /***/ }), -/***/ 41301: -/***/ ((module) => { +/***/ 96787: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - - -/** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ -module.exports = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); -}; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HostType = exports.ConnectionString = void 0; +var main_1 = __nccwpck_require__(22382); +Object.defineProperty(exports, "ConnectionString", ({ enumerable: true, get: function () { return main_1.ConnectionString; } })); +var types_1 = __nccwpck_require__(30920); +Object.defineProperty(exports, "HostType", ({ enumerable: true, get: function () { return types_1.HostType; } })); /***/ }), -/***/ 60650: -/***/ ((module) => { +/***/ 2602: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - - -/** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ -module.exports = function isAxiosError(payload) { - return (typeof payload === 'object') && (payload.isAxiosError === true); -}; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.setupCustomInspect = void 0; +var inspect = __nccwpck_require__(31669).inspect; +var EOL = __nccwpck_require__(12087).EOL; +var setupCustomInspect = function (obj) { + // istanbul ignore else + if (true) { + var inspecting_1 = false; + Object.defineProperty(obj.prototype, inspect.custom, { + value: function () { + if (inspecting_1) { + return this; + } + inspecting_1 = true; + var options = { colors: process.stdout.isTTY }; + var src = inspect(this, options); + var _a = this, host = _a.host, hostname = _a.hostname, port = _a.port, type = _a.type; + var vp = inspect({ host: host, hostname: hostname, port: port, type: type }, options); + inspecting_1 = false; + return "" + src + EOL + "Virtual Properties: " + vp; + } + }); + } +}; +exports.setupCustomInspect = setupCustomInspect; /***/ }), -/***/ 33608: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 22382: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; + +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConnectionString = void 0; +var types_1 = __nccwpck_require__(30920); +var static_1 = __nccwpck_require__(50022); +var inspect_1 = __nccwpck_require__(2602); +var errInvalidDefaults = "Invalid \"defaults\" parameter: "; +var ConnectionString = /** @class */ (function () { + /** + * Constructor. + * + * @param cs - connection string (can be empty). + * + * @param defaults - optional defaults, which can also be set + * explicitly, via method setDefaults. + */ + function ConnectionString(cs, defaults) { + var _this = this; + if (!(this instanceof ConnectionString)) { + throw new TypeError("Class constructor ConnectionString cannot be invoked without 'new'"); + } + cs = cs !== null && cs !== void 0 ? cs : ''; + if (typeof cs !== 'string') { + throw new TypeError("Invalid connection string: " + JSON.stringify(cs)); + } + if (typeof (defaults !== null && defaults !== void 0 ? defaults : {}) !== 'object') { + throw new TypeError(errInvalidDefaults + JSON.stringify(defaults)); + } + cs = cs.trim(); + static_1.validateUrl(cs); // will throw, if failed + // Extracting the protocol: + var m = cs.match(/^(.*)?:\/\//); + if (m) { + var p = m[1]; // protocol name + if (p) { + var m2 = p.match(/^([a-z]+[a-z0-9+-.:]*)/i); + if (p && (!m2 || m2[1] !== p)) { + throw new Error("Invalid protocol name: " + p); + } + this.protocol = p; + } + cs = cs.substr(m[0].length); + } + // Extracting user + password: + m = cs.match(/^([\w-_.+!*'()$%]*):?([\w-_.+!*'()$%]*)@/); + if (m) { + if (m[1]) { + this.user = static_1.decode(m[1]); + } + if (m[2]) { + this.password = static_1.decode(m[2]); + } + cs = cs.substr(m[0].length); + } + // Extracting hosts details: + // (if it starts with `/`, it is the first path segment, i.e. no hosts specified) + if (cs[0] !== '/') { + var endOfHosts = cs.search(/[\/?]/); + var hosts = (endOfHosts === -1 ? cs : cs.substr(0, endOfHosts)).split(','); + hosts.forEach(function (h) { + var host = static_1.parseHost(h); + if (host) { + if (!_this.hosts) { + _this.hosts = []; + } + _this.hosts.push(host); + } + }); + if (endOfHosts >= 0) { + cs = cs.substr(endOfHosts); + } + } + // Extracting the path: + m = cs.match(/\/([\w-_.+!*'()$%]+)/g); + if (m) { + this.path = m.map(function (s) { return static_1.decode(s.substr(1)); }); + } + // Extracting parameters: + var idx = cs.indexOf('?'); + if (idx !== -1) { + cs = cs.substr(idx + 1); + m = cs.match(/([\w-_.+!*'()$%]+)=([\w-_.+!*'()$%,]+)/g); + if (m) { + var params_1 = {}; + m.forEach(function (s) { + var _a; + var a = s.split('='); + var prop = static_1.decode(a[0]); + var val = a[1].split(',').map(static_1.decode); + if (prop in params_1) { + if (Array.isArray(params_1[prop])) { + (_a = params_1[prop]).push.apply(_a, val); + } + else { + params_1[prop] = __spreadArray([params_1[prop]], val); + } + } + else { + params_1[prop] = val.length > 1 ? val : val[0]; + } + }); + this.params = params_1; + } + } + if (defaults) { + this.setDefaults(defaults); + } + } + Object.defineProperty(ConnectionString.prototype, "host", { + /** + * Safe read-accessor to the first host's full name (hostname + port). + */ + get: function () { + var _a; + return (_a = this.hosts) === null || _a === void 0 ? void 0 : _a[0].toString(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ConnectionString.prototype, "hostname", { + /** + * Safe read-accessor to the first host's name (without port). + */ + get: function () { + var _a; + return (_a = this.hosts) === null || _a === void 0 ? void 0 : _a[0].name; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ConnectionString.prototype, "port", { + /** + * Safe read-accessor to the first host's port. + */ + get: function () { + var _a; + return (_a = this.hosts) === null || _a === void 0 ? void 0 : _a[0].port; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ConnectionString.prototype, "type", { + /** + * Safe read-accessor to the first host's type. + */ + get: function () { + var _a; + return (_a = this.hosts) === null || _a === void 0 ? void 0 : _a[0].type; + }, + enumerable: false, + configurable: true + }); + /** + * Parses a host name into an object, which then can be passed into `setDefaults`. + * + * It returns `null` only when no valid host recognized. + */ + ConnectionString.parseHost = function (host) { + return static_1.parseHost(host, true); + }; + /** + * Converts this object into a valid connection string. + */ + ConnectionString.prototype.toString = function (options) { + var s = this.protocol ? this.protocol + "://" : ""; + var opts = options || {}; + if (this.user || this.password) { + if (this.user) { + s += static_1.encode(this.user, opts); + } + if (this.password) { + s += ':'; + var h = opts.passwordHash; + if (h) { + var code = (typeof h === 'string' && h[0]) || '#'; + s += code.repeat(this.password.length); + } + else { + s += static_1.encode(this.password, opts); + } + } + s += '@'; + } + if (Array.isArray(this.hosts)) { + s += this.hosts.map(function (h) { return static_1.fullHostName(h, options); }).join(); + } + if (Array.isArray(this.path)) { + this.path.forEach(function (seg) { + s += "/" + static_1.encode(seg, opts); + }); + } + if (this.params && typeof this.params === 'object') { + var params = []; + for (var a in this.params) { + var value = this.params[a]; + value = Array.isArray(value) ? value : [value]; + value = value.map(function (v) { + return static_1.encode(typeof v === 'string' ? v : JSON.stringify(v), opts); + }).join(); + if (opts.plusForSpace) { + value = value.replace(/%20/g, '+'); + } + params.push(static_1.encode(a, opts) + "=" + value); + } + if (params.length) { + s += "?" + params.join('&'); + } + } + return s; + }; + /** + * Applies default parameters, and returns itself. + */ + ConnectionString.prototype.setDefaults = function (defaults) { + if (!defaults || typeof defaults !== 'object') { + throw new TypeError(errInvalidDefaults + JSON.stringify(defaults)); + } + if (!('protocol' in this) && static_1.hasText(defaults.protocol)) { + this.protocol = defaults.protocol && defaults.protocol.trim(); + } + // Missing default `hosts` are merged with the existing ones: + if (Array.isArray(defaults.hosts)) { + var hosts_1 = Array.isArray(this.hosts) ? this.hosts : []; + var dhHosts = defaults.hosts.filter(function (d) { return d && typeof d === 'object'; }); + dhHosts.forEach(function (dh) { + var dhName = static_1.hasText(dh.name) ? dh.name.trim() : undefined; + var h = { name: dhName, port: dh.port, type: dh.type }; + var found = false; + for (var i = 0; i < hosts_1.length; i++) { + var thisHost = static_1.fullHostName(hosts_1[i]), defHost = static_1.fullHostName(h); + if (thisHost.toLowerCase() === defHost.toLowerCase()) { + found = true; + break; + } + } + if (!found) { + var obj_1 = {}; + if (h.name) { + if (h.type && h.type in types_1.HostType) { + obj_1.name = h.name; + obj_1.type = h.type; + } + else { + var t = static_1.parseHost(h.name, true); + if (t) { + obj_1.name = t.name; + obj_1.type = t.type; + } + } + } + var p = h.port; + if (typeof p === 'number' && p > 0 && p < 65536) { + obj_1.port = p; + } + if (obj_1.name || obj_1.port) { + Object.defineProperty(obj_1, 'toString', { + value: function (options) { return static_1.fullHostName(obj_1, options); } + }); + hosts_1.push(obj_1); + } + } + }); + if (hosts_1.length) { + this.hosts = hosts_1; + } + } + if (!('user' in this) && static_1.hasText(defaults.user)) { + this.user = defaults.user.trim(); + } + if (!('password' in this) && static_1.hasText(defaults.password)) { + this.password = defaults.password.trim(); + } + // Since the order of `path` segments is usually important, we set default + // `path` segments as they are, but only when they are missing completely: + if (!('path' in this) && Array.isArray(defaults.path)) { + var s = defaults.path.filter(static_1.hasText); + if (s.length) { + this.path = s; + } + } + // Missing default `params` are merged with the existing ones: + if (defaults.params && typeof defaults.params === 'object') { + var keys = Object.keys(defaults.params); + if (keys.length) { + if (this.params && typeof this.params === 'object') { + for (var a in defaults.params) { + if (!(a in this.params)) { + this.params[a] = defaults.params[a]; + } + } + } + else { + this.params = {}; + for (var b in defaults.params) { + this.params[b] = defaults.params[b]; + } + } + } + } + return this; + }; + return ConnectionString; +}()); +exports.ConnectionString = ConnectionString; +(function () { + // hiding prototype methods, to keep the type signature clean: + ['setDefaults', 'toString'].forEach(function (prop) { + var desc = Object.getOwnPropertyDescriptor(ConnectionString.prototype, prop); + desc.enumerable = false; + Object.defineProperty(ConnectionString.prototype, prop, desc); + }); + inspect_1.setupCustomInspect(ConnectionString); +})(); -var utils = __nccwpck_require__(20328); - -module.exports = ( - utils.isStandardBrowserEnv() ? - - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; - - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - function resolveURL(url) { - var href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); - - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); +/***/ }), - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - return function isURLSameOrigin(requestURL) { - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && - parsed.host === originURL.host); - }; - })() : +/***/ 50022: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })() -); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseHost = exports.validateUrl = exports.hasText = exports.decode = exports.encode = exports.fullHostName = void 0; +var types_1 = __nccwpck_require__(30920); +function fullHostName(obj, options) { + var a = ''; + if (obj.name) { + var skipEncoding = obj.type === types_1.HostType.IPv4 || obj.type === types_1.HostType.IPv6; + a = skipEncoding ? obj.name : encode(obj.name, options !== null && options !== void 0 ? options : {}); + } + if (obj.port) { + a += ":" + obj.port; + } + return a; +} +exports.fullHostName = fullHostName; +function encode(text, options) { + text = encodeURIComponent(text); + if (options.plusForSpace) { + text = text.replace(/%20/g, '+'); + } + return options.encodeDollar ? text : text.replace(/%24/g, '$'); +} +exports.encode = encode; +function decode(text) { + return decodeURIComponent(text.replace(/\+/g, '%20')); +} +exports.decode = decode; +function hasText(txt) { + return typeof txt === 'string' && /\S/.test(txt); +} +exports.hasText = hasText; +function validateUrl(url) { + var idx = url.search(/[^a-z0-9-._:\/?[\]@!$&'()*+,;=%]/i); + if (idx >= 0) { + var s = JSON.stringify(url[idx]).replace(/^"|"$/g, "'"); + throw new Error("Invalid URL character " + s + " at position " + idx); + } +} +exports.validateUrl = validateUrl; +function parseHost(host, direct) { + if (direct) { + if (typeof host !== 'string') { + throw new TypeError("Invalid \"host\" parameter: " + JSON.stringify(host)); + } + host = host.trim(); + } + var m, isIPv6; + if (host[0] === '[') { + // This is IPv6, with [::] being the shortest possible + m = host.match(/((\[[0-9a-z:%]{2,45}])(?::(-?[0-9a-z]+))?)/i); + isIPv6 = true; + } + else { + // It is either IPv4 or domain/socket + if (direct) { + // Allowed directly: ForwardSlash + Space + m = host.match(/(([a-z0-9.$/\- ]*)(?::(-?[0-9a-z]+))?)/i); + } + else { + // Allow when indirectly: + and % + m = host.match(/(([a-z0-9.+$%\-]*)(?::(-?[0-9a-z]+))?)/i); + } + } + if (m) { + var h_1 = {}; + if (m[2]) { + if (isIPv6) { + h_1.name = m[2]; + h_1.type = types_1.HostType.IPv6; + } + else { + if (m[2].match(/([0-9]{1,3}\.){3}[0-9]{1,3}/)) { + h_1.name = m[2]; + h_1.type = types_1.HostType.IPv4; + } + else { + h_1.name = direct ? m[2] : decode(m[2]); + h_1.type = h_1.name.match(/\/|.*\.sock$/i) ? types_1.HostType.socket : types_1.HostType.domain; + } + } + } + if (m[3]) { + var p = m[3], port = parseInt(p); + if (port > 0 && port < 65536 && port.toString() === p) { + h_1.port = port; + } + else { + throw new Error("Invalid port: " + JSON.stringify(p) + ". Valid port range is: [1...65535]"); + } + } + if (h_1.name || h_1.port) { + Object.defineProperty(h_1, 'toString', { + value: function (options) { return fullHostName(h_1, options); }, + enumerable: false + }); + return h_1; + } + } + return null; +} +exports.parseHost = parseHost; /***/ }), -/***/ 36240: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 30920: +/***/ ((__unused_webpack_module, exports) => { "use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HostType = void 0; +var HostType; +(function (HostType) { + HostType["domain"] = "domain"; + HostType["socket"] = "socket"; + HostType["IPv4"] = "IPv4"; + HostType["IPv6"] = "IPv6"; +})(HostType = exports.HostType || (exports.HostType = {})); -var utils = __nccwpck_require__(20328); +/***/ }), -module.exports = function normalizeHeaderName(headers, normalizedName) { - utils.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); -}; +/***/ 73645: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -/***/ }), -/***/ 86455: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// These tables borrowed from `ansi` -"use strict"; +var prefix = '\x1b[' +exports.up = function up (num) { + return prefix + (num || '') + 'A' +} -var utils = __nccwpck_require__(20328); +exports.down = function down (num) { + return prefix + (num || '') + 'B' +} -// Headers whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -var ignoreDuplicateOf = [ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]; +exports.forward = function forward (num) { + return prefix + (num || '') + 'C' +} -/** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object - */ -module.exports = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; +exports.back = function back (num) { + return prefix + (num || '') + 'D' +} - if (!headers) { return parsed; } +exports.nextLine = function nextLine (num) { + return prefix + (num || '') + 'E' +} - utils.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils.trim(line.substr(0, i)).toLowerCase(); - val = utils.trim(line.substr(i + 1)); +exports.previousLine = function previousLine (num) { + return prefix + (num || '') + 'F' +} - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); +exports.horizontalAbsolute = function horizontalAbsolute (num) { + if (num == null) throw new Error('horizontalAboslute requires a column to position to') + return prefix + num + 'G' +} - return parsed; -}; +exports.eraseData = function eraseData () { + return prefix + 'J' +} +exports.eraseLine = function eraseLine () { + return prefix + 'K' +} -/***/ }), +exports.goto = function (x, y) { + return prefix + y + ';' + x + 'H' +} -/***/ 74850: -/***/ ((module) => { +exports.gotoSOL = function () { + return '\r' +} -"use strict"; +exports.beep = function () { + return '\x07' +} +exports.hideCursor = function hideCursor () { + return prefix + '?25l' +} -/** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} - */ -module.exports = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; -}; +exports.showCursor = function showCursor () { + return prefix + '?25h' +} +var colors = { + reset: 0, +// styles + bold: 1, + italic: 3, + underline: 4, + inverse: 7, +// resets + stopBold: 22, + stopItalic: 23, + stopUnderline: 24, + stopInverse: 27, +// colors + white: 37, + black: 30, + blue: 34, + cyan: 36, + green: 32, + magenta: 35, + red: 31, + yellow: 33, + bgWhite: 47, + bgBlack: 40, + bgBlue: 44, + bgCyan: 46, + bgGreen: 42, + bgMagenta: 45, + bgRed: 41, + bgYellow: 43, -/***/ }), + grey: 90, + brightBlack: 90, + brightRed: 91, + brightGreen: 92, + brightYellow: 93, + brightBlue: 94, + brightMagenta: 95, + brightCyan: 96, + brightWhite: 97, -/***/ 20328: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + bgGrey: 100, + bgBrightBlack: 100, + bgBrightRed: 101, + bgBrightGreen: 102, + bgBrightYellow: 103, + bgBrightBlue: 104, + bgBrightMagenta: 105, + bgBrightCyan: 106, + bgBrightWhite: 107 +} -"use strict"; +exports.color = function color (colorWith) { + if (arguments.length !== 1 || !Array.isArray(colorWith)) { + colorWith = Array.prototype.slice.call(arguments) + } + return prefix + colorWith.map(colorNameToCode).join(';') + 'm' +} +function colorNameToCode (color) { + if (colors[color] != null) return colors[color] + throw new Error('Unknown color or style name: ' + color) +} -var bind = __nccwpck_require__(77065); -/*global toString:true*/ +/***/ }), -// utils is a library of generic helper functions non-specific to axios +/***/ 95898: +/***/ ((__unused_webpack_module, exports) => { -var toString = Object.prototype.toString; +var __webpack_unused_export__; +// 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. -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ -function isArray(val) { - return toString.call(val) === '[object Array]'; -} +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. -/** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ -function isUndefined(val) { - return typeof val === 'undefined'; +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; } +__webpack_unused_export__ = isArray; -/** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +function isBoolean(arg) { + return typeof arg === 'boolean'; } +__webpack_unused_export__ = isBoolean; -/** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ -function isArrayBuffer(val) { - return toString.call(val) === '[object ArrayBuffer]'; +function isNull(arg) { + return arg === null; } +__webpack_unused_export__ = isNull; -/** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ -function isFormData(val) { - return (typeof FormData !== 'undefined') && (val instanceof FormData); +function isNullOrUndefined(arg) { + return arg == null; } +__webpack_unused_export__ = isNullOrUndefined; -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - var result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); - } - return result; +function isNumber(arg) { + return typeof arg === 'number'; } +__webpack_unused_export__ = isNumber; -/** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ -function isString(val) { - return typeof val === 'string'; +function isString(arg) { + return typeof arg === 'string'; } +__webpack_unused_export__ = isString; -/** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ -function isNumber(val) { - return typeof val === 'number'; +function isSymbol(arg) { + return typeof arg === 'symbol'; } +__webpack_unused_export__ = isSymbol; -/** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ -function isObject(val) { - return val !== null && typeof val === 'object'; +function isUndefined(arg) { + return arg === void 0; } +__webpack_unused_export__ = isUndefined; -/** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ -function isPlainObject(val) { - if (toString.call(val) !== '[object Object]') { - return false; - } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; } +__webpack_unused_export__ = isRegExp; -/** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ -function isDate(val) { - return toString.call(val) === '[object Date]'; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; } +__webpack_unused_export__ = isObject; -/** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -function isFile(val) { - return toString.call(val) === '[object File]'; +function isDate(d) { + return objectToString(d) === '[object Date]'; } +__webpack_unused_export__ = isDate; -/** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ -function isBlob(val) { - return toString.call(val) === '[object Blob]'; +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); } +exports.VZ = isError; -/** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -function isFunction(val) { - return toString.call(val) === '[object Function]'; +function isFunction(arg) { + return typeof arg === 'function'; } +__webpack_unused_export__ = isFunction; -/** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ -function isStream(val) { - return isObject(val) && isFunction(val.pipe); +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; } +__webpack_unused_export__ = isPrimitive; -/** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -function isURLSearchParams(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; -} +__webpack_unused_export__ = Buffer.isBuffer; -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ -function trim(str) { - return str.replace(/^\s*/, '').replace(/\s*$/, ''); +function objectToString(o) { + return Object.prototype.toString.call(o); } -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ -function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || - navigator.product === 'NativeScript' || - navigator.product === 'NS')) { - return false; - } - return ( - typeof window !== 'undefined' && - typeof document !== 'undefined' - ); -} -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ -function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } +/***/ }), - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } +/***/ 82902: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } -} -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - var result = {}; - function assignValue(val, key) { - if (isPlainObject(result[key]) && isPlainObject(val)) { - result[key] = merge(result[key], val); - } else if (isPlainObject(val)) { - result[key] = merge({}, val); - } else if (isArray(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } +/* +CSV Stringify - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - return result; -} +Please look at the [project documentation](https://csv.js.org/stringify/) for +additional information. +*/ -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ -function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }); - return a; -} +const { Transform } = __nccwpck_require__(92413) +const bom_utf8 = Buffer.from([239, 187, 191]) -/** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM - */ -function stripBOM(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); +class Stringifier extends Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}) + const options = {} + let err + // Merge with user options + for(let opt in opts){ + options[underscore(opt)] = opts[opt] + } + if(err = this.normalize(options)) throw err + switch(options.record_delimiter){ + case 'auto': + options.record_delimiter = null + break + case 'unix': + options.record_delimiter = "\n" + break + case 'mac': + options.record_delimiter = "\r" + break + case 'windows': + options.record_delimiter = "\r\n" + break + case 'ascii': + options.record_delimiter = "\u001e" + break + case 'unicode': + options.record_delimiter = "\u2028" + break + } + // Expose options + this.options = options + // Internal state + this.state = { + stop: false + } + // Information + this.info = { + records: 0 + } + } + normalize(options){ + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false + }else if(options.bom !== true){ + return new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ]) + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ',' + }else if(Buffer.isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString() + }else if(typeof options.delimiter !== 'string'){ + return new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ]) + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"' + }else if(options.quote === true){ + options.quote = '"' + }else if(options.quote === false){ + options.quote = '' + }else if (Buffer.isBuffer(options.quote)){ + options.quote = options.quote.toString() + }else if(typeof options.quote !== 'string'){ + return new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ]) + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false + }else{ + // todo + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined + }else{ + // todo + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match] + } + if(options.quoted_match){ + for(let quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string' + const isRegExp = quoted_match instanceof RegExp + if(!isString && !isRegExp){ + return Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`) + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false + }else{ + // todo + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true + }else{ + // todo + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"' + }else if(Buffer.isBuffer(options.escape)){ + options.escape = options.escape.toString() + }else if(typeof options.escape !== 'string'){ + return Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`) + } + if (options.escape.length > 1){ + return Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`) + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false + }else{ + // todo + } + // Normalize option `columns` + options.columns = this.normalize_columns(options.columns) + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false + }else{ + // todo + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {} + }else{ + // todo + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : '' + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime() + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value) + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value} + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n' + }else if(Buffer.isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString() + }else if(typeof options.record_delimiter !== 'string'){ + return Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`) + } + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return + } + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + this.state.stop = true + return callback(Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`)) + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && !this.options.columns){ + this.state.stop = true + return callback(Error('Undiscoverable Columns: header option requires column option or object records')) + } + }else if(this.options.columns === undefined || this.options.columns === null){ + this.options.columns = this.normalize_columns(Object.keys(chunk)) + } + } + // Emit the header + if(this.info.records === 0){ + this.bom() + this.headers() + } + // Emit and stringify the record if an object or an array + try{ + this.emit('record', chunk, this.info.records) + }catch(err){ + this.state.stop = true + return this.emit('error', err) + } + // Convert the record into a string + let chunk_string + if(this.options.eof){ + chunk_string = this.stringify(chunk) + if(chunk_string === undefined){ + return + }else{ + chunk_string = chunk_string + this.options.record_delimiter + } + }else{ + chunk_string = this.stringify(chunk) + if(chunk_string === undefined){ + return + }else{ + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string + } + } + } + // Emit the csv + this.info.records++ + this.push(chunk_string) + callback() + } + _flush(callback){ + if(this.info.records === 0){ + this.bom() + this.headers() + } + callback() + } + stringify(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return chunk + } + const {columns, header} = this.options + const record = [] + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length) + } + // Cast record elements + for(let i=0; i= 0 + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0 + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote) + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0 + const quotedString = quoted_string && typeof field === 'string' + let quotedMatch = quoted_match && quoted_match.filter( quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1 + }else{ + return quoted_match.test(value) + } + }) + quotedMatch = quotedMatch && quotedMatch.length > 0 + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g') + value = value.replace(regexp, escape + escape) + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g') + value = value.replace(regexp, escape + quote) + } + if(shouldQuote === true){ + value = quote + value + quote + } + csvrecord += value + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote + } + if(i !== record.length - 1){ + csvrecord += delimiter + } + } + return csvrecord + } + bom(){ + if(this.options.bom !== true){ + return + } + this.push(bom_utf8) + } + headers(){ + if(this.options.header === false){ + return + } + if(this.options.columns === undefined){ + return + } + let headers = this.options.columns.map(column => column.header) + if(this.options.eof){ + headers = this.stringify(headers, true) + this.options.record_delimiter + }else{ + headers = this.stringify(headers) + } + this.push(headers) + } + __cast(value, context){ + const type = typeof value + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)] + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)] + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)] + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)] + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)] + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)] + }else{ + return [undefined, value, value] + } + }catch(err){ + return [err] + } + } + normalize_columns(columns){ + if(columns === undefined || columns === null){ + return undefined + } + if(typeof columns !== 'object'){ + throw Error('Invalid option "columns": expect an array or an object') + } + if(!Array.isArray(columns)){ + const newcolumns = [] + for(let k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }) + } + columns = newcolumns + }else{ + const newcolumns = [] + for(let column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }) + }else if(typeof column === 'object' && column !== undefined && !Array.isArray(column)){ + if(!column.key){ + throw Error('Invalid column definition: property "key" is required') + } + if(column.header === undefined){ + column.header = column.key + } + newcolumns.push(column) + }else{ + throw Error('Invalid column definition: expect a string or an object') + } + } + columns = newcolumns + } + return columns } - return content; } -module.exports = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isPlainObject: isPlainObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - extend: extend, - trim: trim, - stripBOM: stripBOM -}; - - -/***/ }), +const stringify = function(){ + let data, options, callback + for(let i in arguments){ + const argument = arguments[i] + const type = typeof argument + if(data === undefined && (Array.isArray(argument))){ + data = argument + }else if(options === undefined && isObject(argument)){ + options = argument + }else if(callback === undefined && type === 'function'){ + callback = argument + }else{ + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]) + } + } + const stringifier = new Stringifier(options) + if(callback){ + const chunks = [] + stringifier.on('readable', function(){ + let chunk + while((chunk = this.read()) !== null){ + chunks.push(chunk) + } + }) + stringifier.on('error', function(err){ + callback(err) + }) + stringifier.on('end', function(){ + callback(undefined, chunks.join('')) + }) + } + if(data !== undefined){ + // Give a chance for events to be registered later + if(typeof setImmediate === 'function'){ + setImmediate(function(){ + for(let record of data){ + stringifier.write(record) + } + stringifier.end() + }) + }else{ + for(let record of data){ + stringifier.write(record) + } + stringifier.end() + } + } + return stringifier +} -/***/ 9417: -/***/ ((module) => { +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' ') + super(message) + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError) + } + this.code = code + for(const context of contexts){ + for(const key in context){ + const value = context[key] + this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)) + } + } + } +} -"use strict"; +stringify.Stringifier = Stringifier -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); +stringify.CsvError = CsvError - var r = range(a, b, str); +module.exports = stringify - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; +const isObject = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj) } -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase() + }) } -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; +// Lodash implementation of `get` - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; +const charCodeOfDot = '.'.charCodeAt(0) +const reEscapeChar = /\\(\\)?/g +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' +, 'g') +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/ +const reIsPlainProp = /^\w*$/ +const getTag = function(value){ + if(!value) + value === undefined ? '[object Undefined]' : '[object Null]' + return Object.prototype.toString.call(value) +} +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false + } + const type = typeof value + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)) +} +const isSymbol = function(value){ + const type = typeof value + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]') +} +const stringToPath = function(string){ + const result = [] + if(string.charCodeAt(0) === charCodeOfDot){ + result.push('') + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match + if(quote){ + key = subString.replace(reEscapeChar, '$1') + }else if(expression){ + key = expression.trim() } - begs = []; - left = str.length; + result.push(key) + }) + return result +} +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value + } else { + return isKey(value, object) ? [value] : stringToPath(value) + } +} +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value + const result = `${value}` + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result +} +const get = function(object, path){ + path = castPath(path, object) + let index = 0 + const length = path.length + while(object != null && index < length){ + object = object[toKey(path[index++])] + } + return (index && index === length) ? object : undefined +} - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - bi = str.indexOf(b, i + 1); - } +/***/ }), - i = ai < bi && ai >= 0 ? ai : bi; - } +/***/ 1693: +/***/ ((module, exports) => { - if (begs.length) { - result = [ left, right ]; +/* + +© 2011 by Jerry Sievert + +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 () { + /** @class Date */ + // constants + var monthsAbbr = [], monthsFull = [], daysAbbr = [], daysFull = [], dayNames = {}, monthsAll, daysAll = [], monthNames = []; + monthsAbbr = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec' + ]; + + monthsFull = [ + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December' + ]; + + daysAbbr = [ + 'Sun', + 'Mon', + 'Tue', + 'Wed', + 'Thu', + 'Fri', + 'Sat' + ]; + + daysFull = [ + 'Sunday', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday' + ]; + + dayNames = { + 'su': 0, + 'sun': 0, + 'sunday': 0, + 'mo': 1, + 'mon': 1, + 'monday': 1, + 'tu': 2, + 'tue': 2, + 'tuesday': 2, + 'we': 3, + 'wed': 3, + 'wednesday': 3, + 'th': 4, + 'thu': 4, + 'thursday': 4, + 'fr': 5, + 'fri': 5, + 'friday': 5, + 'sa': 6, + 'sat': 6, + 'saturday': 6 + }; + monthsAll = monthsFull.concat(monthsAbbr); + daysAll = [ + 'su', + 'sun', + 'sunday', + 'mo', + 'mon', + 'monday', + 'tu', + 'tue', + 'tuesday', + 'we', + 'wed', + 'wednesday', + 'th', + 'thu', + 'thursday', + 'fr', + 'fri', + 'friday', + 'sa', + 'sat', + 'saturday' + ]; + + monthNames = { + 'jan': 0, + 'january': 0, + 'feb': 1, + 'february': 1, + 'mar': 2, + 'march': 2, + 'apr': 3, + 'april': 3, + 'may': 4, + 'jun': 5, + 'june': 5, + 'jul': 6, + 'july': 6, + 'aug': 7, + 'august': 7, + 'sep': 8, + 'september': 8, + 'oct': 9, + 'october': 9, + 'nov': 10, + 'november': 10, + 'dec': 11, + 'december': 11 + }; + + var daysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]; + + + // private helper functions + /** @ignore */ + function pad(str, length) { + str = String(str); + while (str.length < length) { + str = '0' + str; + } + return str; } - } - return result; -} + var isInteger = function (str) { + if (str.match(/^(\d+)$/)) { + return true; + } + return false; + }; + var getInt = function (str, i, minlength, maxlength) { + for (var x = maxlength; x >= minlength; x--) { + var token = str.substring(i, i + x); + if (token.length < minlength) { + return null; + } + if (isInteger(token)) { + return token; + } + } + return null; + }; + // static class methods + var origParse = Date.parse; + // ------------------------------------------------------------------ + // getDateFromFormat( date_string , format_string ) + // + // This function takes a date string and a format string. It matches + // If the date string matches the format string, it returns the + // getTime() of the date. If it does not match, it returns NaN. + // Original Author: Matt Kruse + // WWW: http://www.mattkruse.com/ + // Adapted from: http://www.mattkruse.com/javascript/date/source.html + // ------------------------------------------------------------------ -/***/ }), -/***/ 87558: -/***/ (function(module) { - -;(function (globalObject) { - 'use strict'; - -/* - * bignumber.js v9.0.0 - * A JavaScript library for arbitrary-precision arithmetic. - * https://github.com/MikeMcl/bignumber.js - * Copyright (c) 2019 Michael Mclaughlin - * MIT Licensed. - * - * BigNumber.prototype methods | BigNumber methods - * | - * absoluteValue abs | clone - * comparedTo | config set - * decimalPlaces dp | DECIMAL_PLACES - * dividedBy div | ROUNDING_MODE - * dividedToIntegerBy idiv | EXPONENTIAL_AT - * exponentiatedBy pow | RANGE - * integerValue | CRYPTO - * isEqualTo eq | MODULO_MODE - * isFinite | POW_PRECISION - * isGreaterThan gt | FORMAT - * isGreaterThanOrEqualTo gte | ALPHABET - * isInteger | isBigNumber - * isLessThan lt | maximum max - * isLessThanOrEqualTo lte | minimum min - * isNaN | random - * isNegative | sum - * isPositive | - * isZero | - * minus | - * modulo mod | - * multipliedBy times | - * negated | - * plus | - * precision sd | - * shiftedBy | - * squareRoot sqrt | - * toExponential | - * toFixed | - * toFormat | - * toFraction | - * toJSON | - * toNumber | - * toPrecision | - * toString | - * valueOf | - * - */ - - - var BigNumber, - isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, - mathceil = Math.ceil, - mathfloor = Math.floor, - - bignumberError = '[BigNumber Error] ', - tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', - - BASE = 1e14, - LOG_BASE = 14, - MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 - // MAX_INT32 = 0x7fffffff, // 2^31 - 1 - POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], - SQRT_BASE = 1e7, - - // EDITABLE - // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and - // the arguments to toExponential, toFixed, toFormat, and toPrecision. - MAX = 1E9; // 0 to MAX_INT32 - - - /* - * Create and return a BigNumber constructor. - */ - function clone(configObject) { - var div, convertBase, parseNumeric, - P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, - ONE = new BigNumber(1), - - - //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- - - - // The default values below must be integers within the inclusive ranges stated. - // The values can also be changed at run-time using BigNumber.set. - - // The maximum number of decimal places for operations involving division. - DECIMAL_PLACES = 20, // 0 to MAX - - // The rounding mode used when rounding to the above decimal places, and when using - // toExponential, toFixed, toFormat and toPrecision, and round (default value). - // UP 0 Away from zero. - // DOWN 1 Towards zero. - // CEIL 2 Towards +Infinity. - // FLOOR 3 Towards -Infinity. - // HALF_UP 4 Towards nearest neighbour. If equidistant, up. - // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. - // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. - // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. - // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. - ROUNDING_MODE = 4, // 0 to 8 - - // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] - - // The exponent value at and beneath which toString returns exponential notation. - // Number type: -7 - TO_EXP_NEG = -7, // 0 to -MAX - - // The exponent value at and above which toString returns exponential notation. - // Number type: 21 - TO_EXP_POS = 21, // 0 to MAX - - // RANGE : [MIN_EXP, MAX_EXP] - - // The minimum exponent value, beneath which underflow to zero occurs. - // Number type: -324 (5e-324) - MIN_EXP = -1e7, // -1 to -MAX - - // The maximum exponent value, above which overflow to Infinity occurs. - // Number type: 308 (1.7976931348623157e+308) - // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. - MAX_EXP = 1e7, // 1 to MAX - - // Whether to use cryptographically-secure random number generation, if available. - CRYPTO = false, // true or false - - // The modulo mode used when calculating the modulus: a mod n. - // The quotient (q = a / n) is calculated according to the corresponding rounding mode. - // The remainder (r) is calculated as: r = a - n * q. - // - // UP 0 The remainder is positive if the dividend is negative, else is negative. - // DOWN 1 The remainder has the same sign as the dividend. - // This modulo mode is commonly known as 'truncated division' and is - // equivalent to (a % n) in JavaScript. - // FLOOR 3 The remainder has the same sign as the divisor (Python %). - // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. - // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). - // The remainder is always positive. - // - // The truncated division, floored division, Euclidian division and IEEE 754 remainder - // modes are commonly used for the modulus operation. - // Although the other rounding modes can also be used, they may not give useful results. - MODULO_MODE = 1, // 0 to 9 - - // The maximum number of significant digits of the result of the exponentiatedBy operation. - // If POW_PRECISION is 0, there will be unlimited significant digits. - POW_PRECISION = 0, // 0 to MAX - - // The format specification used by the BigNumber.prototype.toFormat method. - FORMAT = { - prefix: '', - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ',', - decimalSeparator: '.', - fractionGroupSize: 0, - fractionGroupSeparator: '\xA0', // non-breaking space - suffix: '' - }, - - // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', - // '-', '.', whitespace, or repeated character. - // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' - ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; - - - //------------------------------------------------------------------------------------------ - - - // CONSTRUCTOR - - - /* - * The BigNumber constructor and exported function. - * Create and return a new instance of a BigNumber object. - * - * v {number|string|BigNumber} A numeric value. - * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. - */ - function BigNumber(v, b) { - var alphabet, c, caseChanged, e, i, isNum, len, str, - x = this; - - // Enable constructor call without `new`. - if (!(x instanceof BigNumber)) return new BigNumber(v, b); - - if (b == null) { - - if (v && v._isBigNumber === true) { - x.s = v.s; - - if (!v.c || v.e > MAX_EXP) { - x.c = x.e = null; - } else if (v.e < MIN_EXP) { - x.c = [x.e = 0]; - } else { - x.e = v.e; - x.c = v.c.slice(); - } - - return; - } - - if ((isNum = typeof v == 'number') && v * 0 == 0) { - - // Use `1 / n` to handle minus zero also. - x.s = 1 / v < 0 ? (v = -v, -1) : 1; - - // Fast path for integers, where n < 2147483648 (2**31). - if (v === ~~v) { - for (e = 0, i = v; i >= 10; i /= 10, e++); - - if (e > MAX_EXP) { - x.c = x.e = null; - } else { - x.e = e; - x.c = [v]; - } - - return; - } - - str = String(v); - } else { - - if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); - - x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - - // Decimal point? - if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - - // Exponential form? - if ((i = str.search(/e/i)) > 0) { - - // Determine exponent. - if (e < 0) e = i; - e += +str.slice(i + 1); - str = str.substring(0, i); - } else if (e < 0) { - - // Integer. - e = str.length; - } - - } else { - - // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' - intCheck(b, 2, ALPHABET.length, 'Base'); - - // Allow exponential notation to be used with base 10 argument, while - // also rounding to DECIMAL_PLACES as with other bases. - if (b == 10) { - x = new BigNumber(v); - return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); - } - - str = String(v); - - if (isNum = typeof v == 'number') { - - // Avoid potential interpretation of Infinity and NaN as base 44+ values. - if (v * 0 != 0) return parseNumeric(x, str, isNum, b); - - x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; - - // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' - if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { - throw Error - (tooManyDigits + v); - } - } else { - x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - - alphabet = ALPHABET.slice(0, b); - e = i = 0; - - // Check that str is a valid base b number. - // Don't use RegExp, so alphabet can contain special characters. - for (len = str.length; i < len; i++) { - if (alphabet.indexOf(c = str.charAt(i)) < 0) { - if (c == '.') { - - // If '.' is not the first character and it has not be found before. - if (i > e) { - e = len; - continue; - } - } else if (!caseChanged) { - - // Allow e.g. hexadecimal 'FF' as well as 'ff'. - if (str == str.toUpperCase() && (str = str.toLowerCase()) || - str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i = -1; - e = 0; - continue; - } - } - - return parseNumeric(x, String(v), isNum, b); - } - } - - // Prevent later check for length on converted number. - isNum = false; - str = convertBase(str, b, 10, x.s); - - // Decimal point? - if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - else e = str.length; - } - - // Determine leading zeros. - for (i = 0; str.charCodeAt(i) === 48; i++); - - // Determine trailing zeros. - for (len = str.length; str.charCodeAt(--len) === 48;); - - if (str = str.slice(i, ++len)) { - len -= i; - - // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' - if (isNum && BigNumber.DEBUG && - len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { - throw Error - (tooManyDigits + (x.s * v)); - } - - // Overflow? - if ((e = e - i - 1) > MAX_EXP) { - - // Infinity. - x.c = x.e = null; - - // Underflow? - } else if (e < MIN_EXP) { - - // Zero. - x.c = [x.e = 0]; - } else { - x.e = e; - x.c = []; - - // Transform base - - // e is the base 10 exponent. - // i is where to slice str to get the first element of the coefficient array. - i = (e + 1) % LOG_BASE; - if (e < 0) i += LOG_BASE; // i < 1 - - if (i < len) { - if (i) x.c.push(+str.slice(0, i)); - - for (len -= LOG_BASE; i < len;) { - x.c.push(+str.slice(i, i += LOG_BASE)); - } - - i = LOG_BASE - (str = str.slice(i)).length; - } else { - i -= len; - } - - for (; i--; str += '0'); - x.c.push(+str); - } - } else { - - // Zero. - x.c = [x.e = 0]; - } - } - - - // CONSTRUCTOR PROPERTIES - - - BigNumber.clone = clone; - - BigNumber.ROUND_UP = 0; - BigNumber.ROUND_DOWN = 1; - BigNumber.ROUND_CEIL = 2; - BigNumber.ROUND_FLOOR = 3; - BigNumber.ROUND_HALF_UP = 4; - BigNumber.ROUND_HALF_DOWN = 5; - BigNumber.ROUND_HALF_EVEN = 6; - BigNumber.ROUND_HALF_CEIL = 7; - BigNumber.ROUND_HALF_FLOOR = 8; - BigNumber.EUCLID = 9; - - - /* - * Configure infrequently-changing library-wide settings. - * - * Accept an object with the following optional properties (if the value of a property is - * a number, it must be an integer within the inclusive range stated): - * - * DECIMAL_PLACES {number} 0 to MAX - * ROUNDING_MODE {number} 0 to 8 - * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] - * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] - * CRYPTO {boolean} true or false - * MODULO_MODE {number} 0 to 9 - * POW_PRECISION {number} 0 to MAX - * ALPHABET {string} A string of two or more unique characters which does - * not contain '.'. - * FORMAT {object} An object with some of the following properties: - * prefix {string} - * groupSize {number} - * secondaryGroupSize {number} - * groupSeparator {string} - * decimalSeparator {string} - * fractionGroupSize {number} - * fractionGroupSeparator {string} - * suffix {string} - * - * (The values assigned to the above FORMAT object properties are not checked for validity.) - * - * E.g. - * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) - * - * Ignore properties/parameters set to null or undefined, except for ALPHABET. - * - * Return an object with the properties current values. - */ - BigNumber.config = BigNumber.set = function (obj) { - var p, v; - - if (obj != null) { - - if (typeof obj == 'object') { - - // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. - // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { - v = obj[p]; - intCheck(v, 0, MAX, p); - DECIMAL_PLACES = v; - } - - // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. - // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { - v = obj[p]; - intCheck(v, 0, 8, p); - ROUNDING_MODE = v; - } - - // EXPONENTIAL_AT {number|number[]} - // Integer, -MAX to MAX inclusive or - // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. - // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { - v = obj[p]; - if (v && v.pop) { - intCheck(v[0], -MAX, 0, p); - intCheck(v[1], 0, MAX, p); - TO_EXP_NEG = v[0]; - TO_EXP_POS = v[1]; - } else { - intCheck(v, -MAX, MAX, p); - TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); - } - } - - // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or - // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. - // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' - if (obj.hasOwnProperty(p = 'RANGE')) { - v = obj[p]; - if (v && v.pop) { - intCheck(v[0], -MAX, -1, p); - intCheck(v[1], 1, MAX, p); - MIN_EXP = v[0]; - MAX_EXP = v[1]; - } else { - intCheck(v, -MAX, MAX, p); - if (v) { - MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); - } else { - throw Error - (bignumberError + p + ' cannot be zero: ' + v); - } - } - } - - // CRYPTO {boolean} true or false. - // '[BigNumber Error] CRYPTO not true or false: {v}' - // '[BigNumber Error] crypto unavailable' - if (obj.hasOwnProperty(p = 'CRYPTO')) { - v = obj[p]; - if (v === !!v) { - if (v) { - if (typeof crypto != 'undefined' && crypto && - (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v; - } else { - CRYPTO = !v; - throw Error - (bignumberError + 'crypto unavailable'); - } - } else { - CRYPTO = v; - } - } else { - throw Error - (bignumberError + p + ' not true or false: ' + v); - } - } - - // MODULO_MODE {number} Integer, 0 to 9 inclusive. - // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'MODULO_MODE')) { - v = obj[p]; - intCheck(v, 0, 9, p); - MODULO_MODE = v; - } - - // POW_PRECISION {number} Integer, 0 to MAX inclusive. - // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' - if (obj.hasOwnProperty(p = 'POW_PRECISION')) { - v = obj[p]; - intCheck(v, 0, MAX, p); - POW_PRECISION = v; - } - - // FORMAT {object} - // '[BigNumber Error] FORMAT not an object: {v}' - if (obj.hasOwnProperty(p = 'FORMAT')) { - v = obj[p]; - if (typeof v == 'object') FORMAT = v; - else throw Error - (bignumberError + p + ' not an object: ' + v); - } - - // ALPHABET {string} - // '[BigNumber Error] ALPHABET invalid: {v}' - if (obj.hasOwnProperty(p = 'ALPHABET')) { - v = obj[p]; - - // Disallow if only one character, - // or if it contains '+', '-', '.', whitespace, or a repeated character. - if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) { - ALPHABET = v; - } else { - throw Error - (bignumberError + p + ' invalid: ' + v); - } - } - - } else { - - // '[BigNumber Error] Object expected: {v}' - throw Error - (bignumberError + 'Object expected: ' + obj); - } - } - - return { - DECIMAL_PLACES: DECIMAL_PLACES, - ROUNDING_MODE: ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO: CRYPTO, - MODULO_MODE: MODULO_MODE, - POW_PRECISION: POW_PRECISION, - FORMAT: FORMAT, - ALPHABET: ALPHABET - }; - }; - - - /* - * Return true if v is a BigNumber instance, otherwise return false. - * - * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. - * - * v {any} - * - * '[BigNumber Error] Invalid BigNumber: {v}' - */ - BigNumber.isBigNumber = function (v) { - if (!v || v._isBigNumber !== true) return false; - if (!BigNumber.DEBUG) return true; - - var i, n, - c = v.c, - e = v.e, - s = v.s; - - out: if ({}.toString.call(c) == '[object Array]') { - - if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { - - // If the first element is zero, the BigNumber value must be zero. - if (c[0] === 0) { - if (e === 0 && c.length === 1) return true; - break out; - } - - // Calculate number of digits that c[0] should have, based on the exponent. - i = (e + 1) % LOG_BASE; - if (i < 1) i += LOG_BASE; - - // Calculate number of digits of c[0]. - //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { - if (String(c[0]).length == i) { - - for (i = 0; i < c.length; i++) { - n = c[i]; - if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; - } - - // Last element cannot be zero, unless it is the only element. - if (n !== 0) return true; - } - } - - // Infinity/NaN - } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { - return true; - } - - throw Error - (bignumberError + 'Invalid BigNumber: ' + v); - }; - - - /* - * Return a new BigNumber whose value is the maximum of the arguments. - * - * arguments {number|string|BigNumber} - */ - BigNumber.maximum = BigNumber.max = function () { - return maxOrMin(arguments, P.lt); - }; - - - /* - * Return a new BigNumber whose value is the minimum of the arguments. - * - * arguments {number|string|BigNumber} - */ - BigNumber.minimum = BigNumber.min = function () { - return maxOrMin(arguments, P.gt); - }; - - - /* - * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, - * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing - * zeros are produced). - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' - * '[BigNumber Error] crypto unavailable' - */ - BigNumber.random = (function () { - var pow2_53 = 0x20000000000000; - - // Return a 53 bit integer n, where 0 <= n < 9007199254740992. - // Check if Math.random() produces more than 32 bits of randomness. - // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. - // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. - var random53bitInt = (Math.random() * pow2_53) & 0x1fffff - ? function () { return mathfloor(Math.random() * pow2_53); } - : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + - (Math.random() * 0x800000 | 0); }; - - return function (dp) { - var a, b, e, k, v, - i = 0, - c = [], - rand = new BigNumber(ONE); - - if (dp == null) dp = DECIMAL_PLACES; - else intCheck(dp, 0, MAX); - - k = mathceil(dp / LOG_BASE); - - if (CRYPTO) { - - // Browsers supporting crypto.getRandomValues. - if (crypto.getRandomValues) { - - a = crypto.getRandomValues(new Uint32Array(k *= 2)); - - for (; i < k;) { - - // 53 bits: - // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) - // 11111 11111111 11111111 11111111 11100000 00000000 00000000 - // ((Math.pow(2, 32) - 1) >>> 11).toString(2) - // 11111 11111111 11111111 - // 0x20000 is 2^21. - v = a[i] * 0x20000 + (a[i + 1] >>> 11); - - // Rejection sampling: - // 0 <= v < 9007199254740992 - // Probability that v >= 9e15, is - // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 - if (v >= 9e15) { - b = crypto.getRandomValues(new Uint32Array(2)); - a[i] = b[0]; - a[i + 1] = b[1]; - } else { - - // 0 <= v <= 8999999999999999 - // 0 <= (v % 1e14) <= 99999999999999 - c.push(v % 1e14); - i += 2; - } - } - i = k / 2; - - // Node.js supporting crypto.randomBytes. - } else if (crypto.randomBytes) { - - // buffer - a = crypto.randomBytes(k *= 7); - - for (; i < k;) { - - // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 - // 0x100000000 is 2^32, 0x1000000 is 2^24 - // 11111 11111111 11111111 11111111 11111111 11111111 11111111 - // 0 <= v < 9007199254740992 - v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + - (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + - (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; - - if (v >= 9e15) { - crypto.randomBytes(7).copy(a, i); - } else { - - // 0 <= (v % 1e14) <= 99999999999999 - c.push(v % 1e14); - i += 7; - } - } - i = k / 7; - } else { - CRYPTO = false; - throw Error - (bignumberError + 'crypto unavailable'); - } - } - - // Use Math.random. - if (!CRYPTO) { - - for (; i < k;) { - v = random53bitInt(); - if (v < 9e15) c[i++] = v % 1e14; - } - } - - k = c[--i]; - dp %= LOG_BASE; - - // Convert trailing digits to zeros according to dp. - if (k && dp) { - v = POWS_TEN[LOG_BASE - dp]; - c[i] = mathfloor(k / v) * v; - } - - // Remove trailing elements which are zero. - for (; c[i] === 0; c.pop(), i--); - - // Zero? - if (i < 0) { - c = [e = 0]; - } else { - - // Remove leading elements which are zero and adjust exponent accordingly. - for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); - - // Count the digits of the first element of c to determine leading zeros, and... - for (i = 1, v = c[0]; v >= 10; v /= 10, i++); - - // adjust the exponent accordingly. - if (i < LOG_BASE) e -= LOG_BASE - i; - } - - rand.e = e; - rand.c = c; - return rand; - }; - })(); - - - /* - * Return a BigNumber whose value is the sum of the arguments. - * - * arguments {number|string|BigNumber} - */ - BigNumber.sum = function () { - var i = 1, - args = arguments, - sum = new BigNumber(args[0]); - for (; i < args.length;) sum = sum.plus(args[i++]); - return sum; - }; - - - // PRIVATE FUNCTIONS - - - // Called by BigNumber and BigNumber.prototype.toString. - convertBase = (function () { - var decimal = '0123456789'; - - /* - * Convert string of baseIn to an array of numbers of baseOut. - * Eg. toBaseOut('255', 10, 16) returns [15, 15]. - * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. - */ - function toBaseOut(str, baseIn, baseOut, alphabet) { - var j, - arr = [0], - arrL, - i = 0, - len = str.length; - - for (; i < len;) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); - - arr[0] += alphabet.indexOf(str.charAt(i++)); - - for (j = 0; j < arr.length; j++) { - - if (arr[j] > baseOut - 1) { - if (arr[j + 1] == null) arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; - } - } - } - - return arr.reverse(); - } - - // Convert a numeric string of baseIn to a numeric string of baseOut. - // If the caller is toString, we are converting from base 10 to baseOut. - // If the caller is BigNumber, we are converting from baseIn to base 10. - return function (str, baseIn, baseOut, sign, callerIsToString) { - var alphabet, d, e, k, r, x, xc, y, - i = str.indexOf('.'), - dp = DECIMAL_PLACES, - rm = ROUNDING_MODE; - - // Non-integer. - if (i >= 0) { - k = POW_PRECISION; - - // Unlimited precision. - POW_PRECISION = 0; - str = str.replace('.', ''); - y = new BigNumber(baseIn); - x = y.pow(str.length - i); - POW_PRECISION = k; - - // Convert str as if an integer, then restore the fraction part by dividing the - // result by its base raised to a power. - - y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), - 10, baseOut, decimal); - y.e = y.c.length; - } - - // Convert the number as integer. - - xc = toBaseOut(str, baseIn, baseOut, callerIsToString - ? (alphabet = ALPHABET, decimal) - : (alphabet = decimal, ALPHABET)); - - // xc now represents str as an integer and converted to baseOut. e is the exponent. - e = k = xc.length; - - // Remove trailing zeros. - for (; xc[--k] == 0; xc.pop()); - - // Zero? - if (!xc[0]) return alphabet.charAt(0); - - // Does str represent an integer? If so, no need for the division. - if (i < 0) { - --e; - } else { - x.c = xc; - x.e = e; - - // The sign is needed for correct rounding. - x.s = sign; - x = div(x, y, dp, rm, baseOut); - xc = x.c; - r = x.r; - e = x.e; - } - - // xc now represents str converted to baseOut. - - // THe index of the rounding digit. - d = e + dp + 1; - - // The rounding digit: the digit to the right of the digit that may be rounded up. - i = xc[d]; - - // Look at the rounding digits and mode to determine whether to round up. - - k = baseOut / 2; - r = r || d < 0 || xc[d + 1] != null; - - r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) - : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || - rm == (x.s < 0 ? 8 : 7)); - - // If the index of the rounding digit is not greater than zero, or xc represents - // zero, then the result of the base conversion is zero or, if rounding up, a value - // such as 0.00001. - if (d < 1 || !xc[0]) { - - // 1^-dp or 0 - str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); - } else { - - // Truncate xc to the required number of decimal places. - xc.length = d; - - // Round up? - if (r) { - - // Rounding up may mean the previous digit has to be rounded up and so on. - for (--baseOut; ++xc[--d] > baseOut;) { - xc[d] = 0; - - if (!d) { - ++e; - xc = [1].concat(xc); - } - } - } - - // Determine trailing zeros. - for (k = xc.length; !xc[--k];); - - // E.g. [4, 11, 15] becomes 4bf. - for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); - - // Add leading zeros, decimal point and trailing zeros as required. - str = toFixedPoint(str, e, alphabet.charAt(0)); - } - - // The caller will add the sign. - return str; - }; - })(); - - - // Perform division in the specified base. Called by div and convertBase. - div = (function () { - - // Assume non-zero x and k. - function multiply(x, k, base) { - var m, temp, xlo, xhi, - carry = 0, - i = x.length, - klo = k % SQRT_BASE, - khi = k / SQRT_BASE | 0; - - for (x = x.slice(); i--;) { - xlo = x[i] % SQRT_BASE; - xhi = x[i] / SQRT_BASE | 0; - m = khi * xlo + xhi * klo; - temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; - carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; - x[i] = temp % base; - } - - if (carry) x = [carry].concat(x); - - return x; - } - - function compare(a, b, aL, bL) { - var i, cmp; - - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - - for (i = cmp = 0; i < aL; i++) { - - if (a[i] != b[i]) { - cmp = a[i] > b[i] ? 1 : -1; - break; - } - } - } - - return cmp; - } - - function subtract(a, b, aL, base) { - var i = 0; - - // Subtract b from a. - for (; aL--;) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; - } - - // Remove leading zeros. - for (; !a[0] && a.length > 1; a.splice(0, 1)); - } - - // x: dividend, y: divisor. - return function (x, y, dp, rm, base) { - var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, - yL, yz, - s = x.s == y.s ? 1 : -1, - xc = x.c, - yc = y.c; - - // Either NaN, Infinity or 0? - if (!xc || !xc[0] || !yc || !yc[0]) { - - return new BigNumber( - - // Return NaN if either NaN, or both Infinity or 0. - !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : - - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s * 0 : s / 0 - ); - } - - q = new BigNumber(s); - qc = q.c = []; - e = x.e - y.e; - s = dp + e + 1; - - if (!base) { - base = BASE; - e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); - s = s / LOG_BASE | 0; - } - - // Result exponent may be one less then the current value of e. - // The coefficients of the BigNumbers from convertBase may have trailing zeros. - for (i = 0; yc[i] == (xc[i] || 0); i++); - - if (yc[i] > (xc[i] || 0)) e--; - - if (s < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i = 0; - s += 2; - - // Normalise xc and yc so highest order digit of yc is >= base / 2. - - n = mathfloor(base / (yc[0] + 1)); - - // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. - // if (n > 1 || n++ == 1 && yc[0] < base / 2) { - if (n > 1) { - yc = multiply(yc, n, base); - xc = multiply(xc, n, base); - yL = yc.length; - xL = xc.length; - } - - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - - // Add zeros to make remainder as long as divisor. - for (; remL < yL; rem[remL++] = 0); - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base / 2) yc0++; - // Not necessary, but to prevent trial digit n > base, when using base 3. - // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; - - do { - n = 0; - - // Compare divisor and remainder. - cmp = compare(yc, rem, yL, remL); - - // If divisor < remainder. - if (cmp < 0) { - - // Calculate trial digit, n. - - rem0 = rem[0]; - if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - - // n is how many times the divisor goes into the current remainder. - n = mathfloor(rem0 / yc0); - - // Algorithm: - // product = divisor multiplied by trial digit (n). - // Compare product and remainder. - // If product is greater than remainder: - // Subtract divisor from product, decrement trial digit. - // Subtract product from remainder. - // If product was less than remainder at the last compare: - // Compare new remainder and divisor. - // If remainder is greater than divisor: - // Subtract divisor from remainder, increment trial digit. - - if (n > 1) { - - // n may be > base only when base is 3. - if (n >= base) n = base - 1; - - // product = divisor * trial digit. - prod = multiply(yc, n, base); - prodL = prod.length; - remL = rem.length; - - // Compare product and remainder. - // If product > remainder then trial digit n too high. - // n is 1 too high about 5% of the time, and is not known to have - // ever been more than 1 too high. - while (compare(prod, rem, prodL, remL) == 1) { - n--; - - // Subtract divisor from product. - subtract(prod, yL < prodL ? yz : yc, prodL, base); - prodL = prod.length; - cmp = 1; - } - } else { - - // n is 0 or 1, cmp is -1. - // If n is 0, there is no need to compare yc and rem again below, - // so change cmp to 1 to avoid it. - // If n is 1, leave cmp as -1, so yc and rem are compared again. - if (n == 0) { - - // divisor < remainder, so n must be at least 1. - cmp = n = 1; - } - - // product = divisor - prod = yc.slice(); - prodL = prod.length; - } - - if (prodL < remL) prod = [0].concat(prod); - - // Subtract product from remainder. - subtract(rem, prod, remL, base); - remL = rem.length; - - // If product was < remainder. - if (cmp == -1) { - - // Compare divisor and new remainder. - // If divisor < new remainder, subtract divisor from remainder. - // Trial digit n too low. - // n is 1 too low about 5% of the time, and very rarely 2 too low. - while (compare(yc, rem, yL, remL) < 1) { - n++; - - // Subtract divisor from remainder. - subtract(rem, yL < remL ? yz : yc, remL, base); - remL = rem.length; - } - } - } else if (cmp === 0) { - n++; - rem = [0]; - } // else cmp === 1 and n will be 0 - - // Add the next digit, n, to the result array. - qc[i++] = n; - - // Update the remainder. - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s--); - - more = rem[0] != null; - - // Leading zero? - if (!qc[0]) qc.splice(0, 1); - } - - if (base == BASE) { - - // To calculate q.e, first get the number of digits of qc[0]. - for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); - - round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); - - // Caller is convertBase. - } else { - q.e = e; - q.r = +more; - } - - return q; - }; - })(); - - - /* - * Return a string representing the value of BigNumber n in fixed-point or exponential - * notation rounded to the specified decimal places or significant digits. - * - * n: a BigNumber. - * i: the index of the last digit required (i.e. the digit that may be rounded up). - * rm: the rounding mode. - * id: 1 (toExponential) or 2 (toPrecision). - */ - function format(n, i, rm, id) { - var c0, e, ne, len, str; - - if (rm == null) rm = ROUNDING_MODE; - else intCheck(rm, 0, 8); - - if (!n.c) return n.toString(); - - c0 = n.c[0]; - ne = n.e; - - if (i == null) { - str = coeffToString(n.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) - ? toExponential(str, ne) - : toFixedPoint(str, ne, '0'); - } else { - n = round(new BigNumber(n), i, rm); - - // n.e may have changed if the value was rounded up. - e = n.e; - - str = coeffToString(n.c); - len = str.length; - - // toPrecision returns exponential notation if the number of significant digits - // specified is less than the number of digits necessary to represent the integer - // part of the value in fixed-point notation. - - // Exponential notation. - if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { - - // Append zeros? - for (; len < i; str += '0', len++); - str = toExponential(str, e); - - // Fixed-point notation. - } else { - i -= ne; - str = toFixedPoint(str, e, '0'); - - // Append zeros? - if (e + 1 > len) { - if (--i > 0) for (str += '.'; i--; str += '0'); - } else { - i += e - len; - if (i > 0) { - if (e + 1 == len) str += '.'; - for (; i--; str += '0'); - } - } - } - } - - return n.s < 0 && c0 ? '-' + str : str; - } - - - // Handle BigNumber.max and BigNumber.min. - function maxOrMin(args, method) { - var n, - i = 1, - m = new BigNumber(args[0]); - - for (; i < args.length; i++) { - n = new BigNumber(args[i]); - - // If any number is NaN, return NaN. - if (!n.s) { - m = n; - break; - } else if (method.call(m, n)) { - m = n; - } - } - - return m; - } - - - /* - * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. - * Called by minus, plus and times. - */ - function normalise(n, c, e) { - var i = 1, - j = c.length; - - // Remove trailing zeros. - for (; !c[--j]; c.pop()); - - // Calculate the base 10 exponent. First get the number of digits of c[0]. - for (j = c[0]; j >= 10; j /= 10, i++); - - // Overflow? - if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { - - // Infinity. - n.c = n.e = null; - - // Underflow? - } else if (e < MIN_EXP) { - - // Zero. - n.c = [n.e = 0]; - } else { - n.e = e; - n.c = c; - } - - return n; - } - - - // Handle values that fail the validity test in BigNumber. - parseNumeric = (function () { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, - dotAfter = /^([^.]+)\.$/, - dotBefore = /^\.([^.]+)$/, - isInfinityOrNaN = /^-?(Infinity|NaN)$/, - whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - - return function (x, str, isNum, b) { - var base, - s = isNum ? str : str.replace(whitespaceOrPlus, ''); - - // No exception on ±Infinity or NaN. - if (isInfinityOrNaN.test(s)) { - x.s = isNaN(s) ? null : s < 0 ? -1 : 1; - } else { - if (!isNum) { - - // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i - s = s.replace(basePrefix, function (m, p1, p2) { - base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; - return !b || b == base ? p1 : m; - }); - - if (b) { - base = b; - - // E.g. '1.' to '1', '.1' to '0.1' - s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); - } - - if (str != s) return new BigNumber(s, base); - } - - // '[BigNumber Error] Not a number: {n}' - // '[BigNumber Error] Not a base {b} number: {n}' - if (BigNumber.DEBUG) { - throw Error - (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); - } - - // NaN - x.s = null; - } - - x.c = x.e = null; - } - })(); - - - /* - * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. - * If r is truthy, it is known that there are more digits after the rounding digit. - */ - function round(x, sd, rm, r) { - var d, i, j, k, n, ni, rd, - xc = x.c, - pows10 = POWS_TEN; - - // if x is not Infinity or NaN... - if (xc) { - - // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. - // n is a base 1e14 number, the value of the element of array x.c containing rd. - // ni is the index of n within x.c. - // d is the number of digits of n. - // i is the index of rd within n including leading zeros. - // j is the actual index of rd within n (if < 0, rd is a leading zero). - out: { - - // Get the number of digits of the first element of xc. - for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); - i = sd - d; - - // If the rounding digit is in the first element of xc... - if (i < 0) { - i += LOG_BASE; - j = sd; - n = xc[ni = 0]; - - // Get the rounding digit at index j of n. - rd = n / pows10[d - j - 1] % 10 | 0; - } else { - ni = mathceil((i + 1) / LOG_BASE); - - if (ni >= xc.length) { - - if (r) { - - // Needed by sqrt. - for (; xc.length <= ni; xc.push(0)); - n = rd = 0; - d = 1; - i %= LOG_BASE; - j = i - LOG_BASE + 1; - } else { - break out; - } - } else { - n = k = xc[ni]; - - // Get the number of digits of n. - for (d = 1; k >= 10; k /= 10, d++); - - // Get the index of rd within n. - i %= LOG_BASE; - - // Get the index of rd within n, adjusted for leading zeros. - // The number of leading zeros of n is given by LOG_BASE - d. - j = i - LOG_BASE + d; - - // Get the rounding digit at index j of n. - rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; - } - } - - r = r || sd < 0 || - - // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); - - r = rm < 4 - ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) - : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && - - // Check whether the digit to the left of the rounding digit is odd. - ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || - rm == (x.s < 0 ? 8 : 7)); - - if (sd < 1 || !xc[0]) { - xc.length = 0; - - if (r) { - - // Convert sd to decimal places. - sd -= x.e + 1; - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; - x.e = -sd || 0; - } else { - - // Zero. - xc[0] = x.e = 0; - } - - return x; - } - - // Remove excess digits. - if (i == 0) { - xc.length = ni; - k = 1; - ni--; - } else { - xc.length = ni + 1; - k = pows10[LOG_BASE - i]; - - // E.g. 56700 becomes 56000 if 7 is the rounding digit. - // j > 0 means i > number of leading zeros of n. - xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; - } - - // Round up? - if (r) { - - for (; ;) { - - // If the digit to be rounded up is in the first element of xc... - if (ni == 0) { - - // i will be the length of xc[0] before k is added. - for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); - j = xc[0] += k; - for (k = 1; j >= 10; j /= 10, k++); - - // if i != k the length has increased. - if (i != k) { - x.e++; - if (xc[0] == BASE) xc[0] = 1; - } - - break; - } else { - xc[ni] += k; - if (xc[ni] != BASE) break; - xc[ni--] = 0; - k = 1; - } - } - } - - // Remove trailing zeros. - for (i = xc.length; xc[--i] === 0; xc.pop()); - } - - // Overflow? Infinity. - if (x.e > MAX_EXP) { - x.c = x.e = null; - - // Underflow? Zero. - } else if (x.e < MIN_EXP) { - x.c = [x.e = 0]; - } - } - - return x; - } - - - function valueOf(n) { - var str, - e = n.e; - - if (e === null) return n.toString(); - - str = coeffToString(n.c); - - str = e <= TO_EXP_NEG || e >= TO_EXP_POS - ? toExponential(str, e) - : toFixedPoint(str, e, '0'); - - return n.s < 0 ? '-' + str : str; - } - - - // PROTOTYPE/INSTANCE METHODS - - - /* - * Return a new BigNumber whose value is the absolute value of this BigNumber. - */ - P.absoluteValue = P.abs = function () { - var x = new BigNumber(this); - if (x.s < 0) x.s = 1; - return x; - }; - - - /* - * Return - * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), - * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), - * 0 if they have the same value, - * or null if the value of either is NaN. - */ - P.comparedTo = function (y, b) { - return compare(this, new BigNumber(y, b)); - }; - - - /* - * If dp is undefined or null or true or false, return the number of decimal places of the - * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. - * - * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this - * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or - * ROUNDING_MODE if rm is omitted. - * - * [dp] {number} Decimal places: integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.decimalPlaces = P.dp = function (dp, rm) { - var c, n, v, - x = this; - - if (dp != null) { - intCheck(dp, 0, MAX); - if (rm == null) rm = ROUNDING_MODE; - else intCheck(rm, 0, 8); - - return round(new BigNumber(x), dp + x.e + 1, rm); - } - - if (!(c = x.c)) return null; - n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; - - // Subtract the number of trailing zeros of the last number. - if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); - if (n < 0) n = 0; - - return n; - }; - - - /* - * n / 0 = I - * n / N = N - * n / I = 0 - * 0 / n = 0 - * 0 / 0 = N - * 0 / N = N - * 0 / I = 0 - * N / n = N - * N / 0 = N - * N / N = N - * N / I = N - * I / n = I - * I / 0 = I - * I / N = N - * I / I = N - * - * Return a new BigNumber whose value is the value of this BigNumber divided by the value of - * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. - */ - P.dividedBy = P.div = function (y, b) { - return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); - }; - - - /* - * Return a new BigNumber whose value is the integer part of dividing the value of this - * BigNumber by the value of BigNumber(y, b). - */ - P.dividedToIntegerBy = P.idiv = function (y, b) { - return div(this, new BigNumber(y, b), 0, 1); - }; - - - /* - * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. - * - * If m is present, return the result modulo m. - * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. - * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. - * - * The modular power operation works efficiently when x, n, and m are integers, otherwise it - * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. - * - * n {number|string|BigNumber} The exponent. An integer. - * [m] {number|string|BigNumber} The modulus. - * - * '[BigNumber Error] Exponent not an integer: {n}' - */ - P.exponentiatedBy = P.pow = function (n, m) { - var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, - x = this; - - n = new BigNumber(n); - - // Allow NaN and ±Infinity, but not other non-integers. - if (n.c && !n.isInteger()) { - throw Error - (bignumberError + 'Exponent not an integer: ' + valueOf(n)); - } - - if (m != null) m = new BigNumber(m); - - // Exponent of MAX_SAFE_INTEGER is 15. - nIsBig = n.e > 14; - - // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. - if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { - - // The sign of the result of pow when x is negative depends on the evenness of n. - // If +n overflows to ±Infinity, the evenness of n would be not be known. - y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n))); - return m ? y.mod(m) : y; - } - - nIsNeg = n.s < 0; - - if (m) { - - // x % m returns NaN if abs(m) is zero, or m is NaN. - if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); - - isModExp = !nIsNeg && x.isInteger() && m.isInteger(); - - if (isModExp) x = x.mod(m); - - // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. - // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. - } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 - // [1, 240000000] - ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 - // [80000000000000] [99999750000000] - : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { - - // If x is negative and n is odd, k = -0, else k = 0. - k = x.s < 0 && isOdd(n) ? -0 : 0; - - // If x >= 1, k = ±Infinity. - if (x.e > -1) k = 1 / k; - - // If n is negative return ±0, else return ±Infinity. - return new BigNumber(nIsNeg ? 1 / k : k); - - } else if (POW_PRECISION) { - - // Truncating each coefficient array to a length of k after each multiplication - // equates to truncating significant digits to POW_PRECISION + [28, 41], - // i.e. there will be a minimum of 28 guard digits retained. - k = mathceil(POW_PRECISION / LOG_BASE + 2); - } - - if (nIsBig) { - half = new BigNumber(0.5); - if (nIsNeg) n.s = 1; - nIsOdd = isOdd(n); - } else { - i = Math.abs(+valueOf(n)); - nIsOdd = i % 2; - } - - y = new BigNumber(ONE); - - // Performs 54 loop iterations for n of 9007199254740991. - for (; ;) { - - if (nIsOdd) { - y = y.times(x); - if (!y.c) break; - - if (k) { - if (y.c.length > k) y.c.length = k; - } else if (isModExp) { - y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); - } - } - - if (i) { - i = mathfloor(i / 2); - if (i === 0) break; - nIsOdd = i % 2; - } else { - n = n.times(half); - round(n, n.e + 1, 1); - - if (n.e > 14) { - nIsOdd = isOdd(n); - } else { - i = +valueOf(n); - if (i === 0) break; - nIsOdd = i % 2; - } - } - - x = x.times(x); - - if (k) { - if (x.c && x.c.length > k) x.c.length = k; - } else if (isModExp) { - x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); - } - } - - if (isModExp) return y; - if (nIsNeg) y = ONE.div(y); - - return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer - * using rounding mode rm, or ROUNDING_MODE if rm is omitted. - * - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' - */ - P.integerValue = function (rm) { - var n = new BigNumber(this); - if (rm == null) rm = ROUNDING_MODE; - else intCheck(rm, 0, 8); - return round(n, n.e + 1, rm); - }; - - - /* - * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), - * otherwise return false. - */ - P.isEqualTo = P.eq = function (y, b) { - return compare(this, new BigNumber(y, b)) === 0; - }; - - - /* - * Return true if the value of this BigNumber is a finite number, otherwise return false. - */ - P.isFinite = function () { - return !!this.c; - }; - - - /* - * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), - * otherwise return false. - */ - P.isGreaterThan = P.gt = function (y, b) { - return compare(this, new BigNumber(y, b)) > 0; - }; - - - /* - * Return true if the value of this BigNumber is greater than or equal to the value of - * BigNumber(y, b), otherwise return false. - */ - P.isGreaterThanOrEqualTo = P.gte = function (y, b) { - return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; - - }; - - - /* - * Return true if the value of this BigNumber is an integer, otherwise return false. - */ - P.isInteger = function () { - return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; - }; - - - /* - * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), - * otherwise return false. - */ - P.isLessThan = P.lt = function (y, b) { - return compare(this, new BigNumber(y, b)) < 0; - }; - - - /* - * Return true if the value of this BigNumber is less than or equal to the value of - * BigNumber(y, b), otherwise return false. - */ - P.isLessThanOrEqualTo = P.lte = function (y, b) { - return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; - }; - - - /* - * Return true if the value of this BigNumber is NaN, otherwise return false. - */ - P.isNaN = function () { - return !this.s; - }; - - - /* - * Return true if the value of this BigNumber is negative, otherwise return false. - */ - P.isNegative = function () { - return this.s < 0; - }; - - - /* - * Return true if the value of this BigNumber is positive, otherwise return false. - */ - P.isPositive = function () { - return this.s > 0; - }; - - - /* - * Return true if the value of this BigNumber is 0 or -0, otherwise return false. - */ - P.isZero = function () { - return !!this.c && this.c[0] == 0; - }; - - - /* - * n - 0 = n - * n - N = N - * n - I = -I - * 0 - n = -n - * 0 - 0 = 0 - * 0 - N = N - * 0 - I = -I - * N - n = N - * N - 0 = N - * N - N = N - * N - I = N - * I - n = I - * I - 0 = I - * I - N = N - * I - I = N - * - * Return a new BigNumber whose value is the value of this BigNumber minus the value of - * BigNumber(y, b). - */ - P.minus = function (y, b) { - var i, j, t, xLTy, - x = this, - a = x.s; - - y = new BigNumber(y, b); - b = y.s; - - // Either NaN? - if (!a || !b) return new BigNumber(NaN); - - // Signs differ? - if (a != b) { - y.s = -b; - return x.plus(y); - } - - var xe = x.e / LOG_BASE, - ye = y.e / LOG_BASE, - xc = x.c, - yc = y.c; - - if (!xe || !ye) { - - // Either Infinity? - if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); - - // Either zero? - if (!xc[0] || !yc[0]) { - - // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. - return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : - - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0); - } - } - - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - - // Determine which is the bigger number. - if (a = xe - ye) { - - if (xLTy = a < 0) { - a = -a; - t = xc; - } else { - ye = xe; - t = yc; - } - - t.reverse(); - - // Prepend zeros to equalise exponents. - for (b = a; b--; t.push(0)); - t.reverse(); - } else { - - // Exponents equal. Check digit by digit. - j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; - - for (a = b = 0; b < j; b++) { - - if (xc[b] != yc[b]) { - xLTy = xc[b] < yc[b]; - break; - } - } - } - - // x < y? Point xc to the array of the bigger number. - if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; - - b = (j = yc.length) - (i = xc.length); - - // Append zeros to xc if shorter. - // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. - if (b > 0) for (; b--; xc[i++] = 0); - b = BASE - 1; - - // Subtract yc from xc. - for (; j > a;) { - - if (xc[--j] < yc[j]) { - for (i = j; i && !xc[--i]; xc[i] = b); - --xc[i]; - xc[j] += BASE; - } - - xc[j] -= yc[j]; - } - - // Remove leading zeros and adjust exponent accordingly. - for (; xc[0] == 0; xc.splice(0, 1), --ye); - - // Zero? - if (!xc[0]) { - - // Following IEEE 754 (2008) 6.3, - // n - n = +0 but n - n = -0 when rounding towards -Infinity. - y.s = ROUNDING_MODE == 3 ? -1 : 1; - y.c = [y.e = 0]; - return y; - } - - // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity - // for finite x and y. - return normalise(y, xc, ye); - }; - - - /* - * n % 0 = N - * n % N = N - * n % I = n - * 0 % n = 0 - * -0 % n = -0 - * 0 % 0 = N - * 0 % N = N - * 0 % I = 0 - * N % n = N - * N % 0 = N - * N % N = N - * N % I = N - * I % n = N - * I % 0 = N - * I % N = N - * I % I = N - * - * Return a new BigNumber whose value is the value of this BigNumber modulo the value of - * BigNumber(y, b). The result depends on the value of MODULO_MODE. - */ - P.modulo = P.mod = function (y, b) { - var q, s, - x = this; - - y = new BigNumber(y, b); - - // Return NaN if x is Infinity or NaN, or y is NaN or zero. - if (!x.c || !y.s || y.c && !y.c[0]) { - return new BigNumber(NaN); - - // Return x if y is Infinity or x is zero. - } else if (!y.c || x.c && !x.c[0]) { - return new BigNumber(x); - } - - if (MODULO_MODE == 9) { - - // Euclidian division: q = sign(y) * floor(x / abs(y)) - // r = x - qy where 0 <= r < abs(y) - s = y.s; - y.s = 1; - q = div(x, y, 0, 3); - y.s = s; - q.s *= s; - } else { - q = div(x, y, 0, MODULO_MODE); - } - - y = x.minus(q.times(y)); - - // To match JavaScript %, ensure sign of zero is sign of dividend. - if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; - - return y; - }; - - - /* - * n * 0 = 0 - * n * N = N - * n * I = I - * 0 * n = 0 - * 0 * 0 = 0 - * 0 * N = N - * 0 * I = N - * N * n = N - * N * 0 = N - * N * N = N - * N * I = N - * I * n = I - * I * 0 = N - * I * N = N - * I * I = I - * - * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value - * of BigNumber(y, b). - */ - P.multipliedBy = P.times = function (y, b) { - var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, - base, sqrtBase, - x = this, - xc = x.c, - yc = (y = new BigNumber(y, b)).c; - - // Either NaN, ±Infinity or ±0? - if (!xc || !yc || !xc[0] || !yc[0]) { - - // Return NaN if either is NaN, or one is 0 and the other is Infinity. - if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y.c = y.e = y.s = null; - } else { - y.s *= x.s; - - // Return ±Infinity if either is ±Infinity. - if (!xc || !yc) { - y.c = y.e = null; - - // Return ±0 if either is ±0. - } else { - y.c = [0]; - y.e = 0; - } - } - - return y; - } - - e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); - y.s *= x.s; - xcL = xc.length; - ycL = yc.length; - - // Ensure xc points to longer array and xcL to its length. - if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; - - // Initialise the result array with zeros. - for (i = xcL + ycL, zc = []; i--; zc.push(0)); - - base = BASE; - sqrtBase = SQRT_BASE; - - for (i = ycL; --i >= 0;) { - c = 0; - ylo = yc[i] % sqrtBase; - yhi = yc[i] / sqrtBase | 0; - - for (k = xcL, j = i + k; j > i;) { - xlo = xc[--k] % sqrtBase; - xhi = xc[k] / sqrtBase | 0; - m = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; - c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; - zc[j--] = xlo % base; - } - - zc[j] = c; - } - - if (c) { - ++e; - } else { - zc.splice(0, 1); - } - - return normalise(y, zc, e); - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber negated, - * i.e. multiplied by -1. - */ - P.negated = function () { - var x = new BigNumber(this); - x.s = -x.s || null; - return x; - }; - - - /* - * n + 0 = n - * n + N = N - * n + I = I - * 0 + n = n - * 0 + 0 = 0 - * 0 + N = N - * 0 + I = I - * N + n = N - * N + 0 = N - * N + N = N - * N + I = N - * I + n = I - * I + 0 = I - * I + N = N - * I + I = I - * - * Return a new BigNumber whose value is the value of this BigNumber plus the value of - * BigNumber(y, b). - */ - P.plus = function (y, b) { - var t, - x = this, - a = x.s; - - y = new BigNumber(y, b); - b = y.s; - - // Either NaN? - if (!a || !b) return new BigNumber(NaN); - - // Signs differ? - if (a != b) { - y.s = -b; - return x.minus(y); - } - - var xe = x.e / LOG_BASE, - ye = y.e / LOG_BASE, - xc = x.c, - yc = y.c; - - if (!xe || !ye) { - - // Return ±Infinity if either ±Infinity. - if (!xc || !yc) return new BigNumber(a / 0); - - // Either zero? - // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. - if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); - } - - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - - // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. - if (a = xe - ye) { - if (a > 0) { - ye = xe; - t = yc; - } else { - a = -a; - t = xc; - } - - t.reverse(); - for (; a--; t.push(0)); - t.reverse(); - } - - a = xc.length; - b = yc.length; - - // Point xc to the longer array, and b to the shorter length. - if (a - b < 0) t = yc, yc = xc, xc = t, b = a; - - // Only start adding at yc.length - 1 as the further digits of xc can be ignored. - for (a = 0; b;) { - a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; - xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; - } - - if (a) { - xc = [a].concat(xc); - ++ye; - } - - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - // ye = MAX_EXP + 1 possible - return normalise(y, xc, ye); - }; - - - /* - * If sd is undefined or null or true or false, return the number of significant digits of - * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. - * If sd is true include integer-part trailing zeros in the count. - * - * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this - * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or - * ROUNDING_MODE if rm is omitted. - * - * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. - * boolean: whether to count integer-part trailing zeros: true or false. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' - */ - P.precision = P.sd = function (sd, rm) { - var c, n, v, - x = this; - - if (sd != null && sd !== !!sd) { - intCheck(sd, 1, MAX); - if (rm == null) rm = ROUNDING_MODE; - else intCheck(rm, 0, 8); - - return round(new BigNumber(x), sd, rm); - } - - if (!(c = x.c)) return null; - v = c.length - 1; - n = v * LOG_BASE + 1; - - if (v = c[v]) { - - // Subtract the number of trailing zeros of the last element. - for (; v % 10 == 0; v /= 10, n--); - - // Add the number of digits of the first element. - for (v = c[0]; v >= 10; v /= 10, n++); - } - - if (sd && x.e + 1 > n) n = x.e + 1; - - return n; - }; - - - /* - * Return a new BigNumber whose value is the value of this BigNumber shifted by k places - * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. - * - * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' - */ - P.shiftedBy = function (k) { - intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); - return this.times('1e' + k); - }; - - - /* - * sqrt(-n) = N - * sqrt(N) = N - * sqrt(-I) = N - * sqrt(I) = I - * sqrt(0) = 0 - * sqrt(-0) = -0 - * - * Return a new BigNumber whose value is the square root of the value of this BigNumber, - * rounded according to DECIMAL_PLACES and ROUNDING_MODE. - */ - P.squareRoot = P.sqrt = function () { - var m, n, r, rep, t, - x = this, - c = x.c, - s = x.s, - e = x.e, - dp = DECIMAL_PLACES + 4, - half = new BigNumber('0.5'); - - // Negative/NaN/Infinity/zero? - if (s !== 1 || !c || !c[0]) { - return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); - } - - // Initial estimate. - s = Math.sqrt(+valueOf(x)); - - // Math.sqrt underflow/overflow? - // Pass x to Math.sqrt as integer, then adjust the exponent of the result. - if (s == 0 || s == 1 / 0) { - n = coeffToString(c); - if ((n.length + e) % 2 == 0) n += '0'; - s = Math.sqrt(+n); - e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); - - if (s == 1 / 0) { - n = '1e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new BigNumber(n); - } else { - r = new BigNumber(s + ''); - } - - // Check for zero. - // r could be zero if MIN_EXP is changed after the this value was created. - // This would cause a division by zero (x/t) and hence Infinity below, which would cause - // coeffToString to throw. - if (r.c[0]) { - e = r.e; - s = e + dp; - if (s < 3) s = 0; - - // Newton-Raphson iteration. - for (; ;) { - t = r; - r = half.times(t.plus(div(x, t, dp, 1))); - - if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { - - // The exponent of r may here be one less than the final result exponent, - // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits - // are indexed correctly. - if (r.e < e) --s; - n = n.slice(s - 3, s + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits - // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the - // iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the - // exact result as the nines may infinitely repeat. - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - - if (t.times(t).eq(x)) { - r = t; - break; - } - } - - dp += 4; - s += 4; - rep = 1; - } else { - - // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact - // result. If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - round(r, r.e + DECIMAL_PLACES + 2, 1); - m = !r.times(r).eq(x); - } - - break; - } - } - } - } - - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); - }; - - - /* - * Return a string representing the value of this BigNumber in exponential notation and - * rounded using ROUNDING_MODE to dp fixed decimal places. - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toExponential = function (dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp++; - } - return format(this, dp, rm, 1); - }; - - - /* - * Return a string representing the value of this BigNumber in fixed-point notation rounding - * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. - * - * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', - * but e.g. (-0.00001).toFixed(0) is '-0'. - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toFixed = function (dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - - - /* - * Return a string representing the value of this BigNumber in fixed-point notation rounded - * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties - * of the format or FORMAT object (see BigNumber.set). - * - * The formatting object may contain some or all of the properties shown below. - * - * FORMAT = { - * prefix: '', - * groupSize: 3, - * secondaryGroupSize: 0, - * groupSeparator: ',', - * decimalSeparator: '.', - * fractionGroupSize: 0, - * fractionGroupSeparator: '\xA0', // non-breaking space - * suffix: '' - * }; - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * [format] {object} Formatting options. See FORMAT pbject above. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - * '[BigNumber Error] Argument not an object: {format}' - */ - P.toFormat = function (dp, rm, format) { - var str, - x = this; - - if (format == null) { - if (dp != null && rm && typeof rm == 'object') { - format = rm; - rm = null; - } else if (dp && typeof dp == 'object') { - format = dp; - dp = rm = null; - } else { - format = FORMAT; - } - } else if (typeof format != 'object') { - throw Error - (bignumberError + 'Argument not an object: ' + format); - } - - str = x.toFixed(dp, rm); - - if (x.c) { - var i, - arr = str.split('.'), - g1 = +format.groupSize, - g2 = +format.secondaryGroupSize, - groupSeparator = format.groupSeparator || '', - intPart = arr[0], - fractionPart = arr[1], - isNeg = x.s < 0, - intDigits = isNeg ? intPart.slice(1) : intPart, - len = intDigits.length; - - if (g2) i = g1, g1 = g2, g2 = i, len -= i; - - if (g1 > 0 && len > 0) { - i = len % g1 || g1; - intPart = intDigits.substr(0, i); - for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); - if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); - if (isNeg) intPart = '-' + intPart; - } - - str = fractionPart - ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) - ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), - '$&' + (format.fractionGroupSeparator || '')) - : fractionPart) - : intPart; - } - - return (format.prefix || '') + str + (format.suffix || ''); - }; - - - /* - * Return an array of two BigNumbers representing the value of this BigNumber as a simple - * fraction with an integer numerator and an integer denominator. - * The denominator will be a positive non-zero value less than or equal to the specified - * maximum denominator. If a maximum denominator is not specified, the denominator will be - * the lowest value necessary to represent the number exactly. - * - * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. - * - * '[BigNumber Error] Argument {not an integer|out of range} : {md}' - */ - P.toFraction = function (md) { - var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, - x = this, - xc = x.c; - - if (md != null) { - n = new BigNumber(md); - - // Throw if md is less than one or is not an integer, unless it is Infinity. - if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { - throw Error - (bignumberError + 'Argument ' + - (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); - } - } - - if (!xc) return new BigNumber(x); - - d = new BigNumber(ONE); - n1 = d0 = new BigNumber(ONE); - d1 = n0 = new BigNumber(ONE); - s = coeffToString(xc); - - // Determine initial denominator. - // d is a power of 10 and the minimum max denominator that specifies the value exactly. - e = d.e = s.length - x.e - 1; - d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; - md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; - - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n = new BigNumber(s); - - // n0 = d1 = 0 - n0.c[0] = 0; - - for (; ;) { - q = div(n, d, 0, 1); - d2 = d0.plus(q.times(d1)); - if (d2.comparedTo(md) == 1) break; - d0 = d1; - d1 = d2; - n1 = n0.plus(q.times(d2 = n1)); - n0 = d2; - d = n.minus(q.times(d2 = d)); - n = d2; - } - - d2 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - e = e * 2; - - // Determine which fraction is closer to x, n0/d0 or n1/d1 - r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( - div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; - - MAX_EXP = exp; - - return r; - }; - - - /* - * Return the value of this BigNumber converted to a number primitive. - */ - P.toNumber = function () { - return +valueOf(this); - }; - - - /* - * Return a string representing the value of this BigNumber rounded to sd significant digits - * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits - * necessary to represent the integer part of the value in fixed-point notation, then use - * exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' - */ - P.toPrecision = function (sd, rm) { - if (sd != null) intCheck(sd, 1, MAX); - return format(this, sd, rm, 2); - }; - - - /* - * Return a string representing the value of this BigNumber in base b, or base 10 if b is - * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and - * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent - * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than - * TO_EXP_NEG, return exponential notation. - * - * [b] {number} Integer, 2 to ALPHABET.length inclusive. - * - * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' - */ - P.toString = function (b) { - var str, - n = this, - s = n.s, - e = n.e; - - // Infinity or NaN? - if (e === null) { - if (s) { - str = 'Infinity'; - if (s < 0) str = '-' + str; - } else { - str = 'NaN'; - } - } else { - if (b == null) { - str = e <= TO_EXP_NEG || e >= TO_EXP_POS - ? toExponential(coeffToString(n.c), e) - : toFixedPoint(coeffToString(n.c), e, '0'); - } else if (b === 10) { - n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); - str = toFixedPoint(coeffToString(n.c), n.e, '0'); - } else { - intCheck(b, 2, ALPHABET.length, 'Base'); - str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); - } - - if (s < 0 && n.c[0]) str = '-' + str; - } - - return str; - }; - - - /* - * Return as toString, but do not accept a base argument, and include the minus sign for - * negative zero. - */ - P.valueOf = P.toJSON = function () { - return valueOf(this); - }; - - - P._isBigNumber = true; - - if (configObject != null) BigNumber.set(configObject); - - return BigNumber; - } - - - // PRIVATE HELPER FUNCTIONS - - // These functions don't need access to variables, - // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. - - - function bitFloor(n) { - var i = n | 0; - return n > 0 || n === i ? i : i - 1; - } - - - // Return a coefficient array as a string of base 10 digits. - function coeffToString(a) { - var s, z, - i = 1, - j = a.length, - r = a[0] + ''; - - for (; i < j;) { - s = a[i++] + ''; - z = LOG_BASE - s.length; - for (; z--; s = '0' + s); - r += s; - } - - // Determine trailing zeros. - for (j = r.length; r.charCodeAt(--j) === 48;); - - return r.slice(0, j + 1 || 1); - } - - - // Compare the value of BigNumbers x and y. - function compare(x, y) { - var a, b, - xc = x.c, - yc = y.c, - i = x.s, - j = y.s, - k = x.e, - l = y.e; - - // Either NaN? - if (!i || !j) return null; - - a = xc && !xc[0]; - b = yc && !yc[0]; - - // Either zero? - if (a || b) return a ? b ? 0 : -j : i; - - // Signs differ? - if (i != j) return i; - - a = i < 0; - b = k == l; - - // Either Infinity? - if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; - - // Compare exponents. - if (!b) return k > l ^ a ? 1 : -1; - - j = (k = xc.length) < (l = yc.length) ? k : l; - - // Compare digit by digit. - for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; - - // Compare lengths. - return k == l ? 0 : k > l ^ a ? 1 : -1; - } - - - /* - * Check that n is a primitive number, an integer, and in range, otherwise throw. - */ - function intCheck(n, min, max, name) { - if (n < min || n > max || n !== mathfloor(n)) { - throw Error - (bignumberError + (name || 'Argument') + (typeof n == 'number' - ? n < min || n > max ? ' out of range: ' : ' not an integer: ' - : ' not a primitive number: ') + String(n)); - } - } - - - // Assumes finite n. - function isOdd(n) { - var k = n.c.length - 1; - return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; - } - - - function toExponential(str, e) { - return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + - (e < 0 ? 'e' : 'e+') + e; - } - - - function toFixedPoint(str, e, z) { - var len, zs; - - // Negative exponent? - if (e < 0) { - - // Prepend zeros. - for (zs = z + '.'; ++e; zs += z); - str = zs + str; - - // Positive exponent - } else { - len = str.length; - - // Append zeros. - if (++e > len) { - for (zs = z, e -= len; --e; zs += z); - str += zs; - } else if (e < len) { - str = str.slice(0, e) + '.' + str.slice(e); - } - } - - return str; - } - - - // EXPORT - - - BigNumber = clone(); - BigNumber['default'] = BigNumber.BigNumber = BigNumber; - - // AMD. - if (typeof define == 'function' && define.amd) { - define(function () { return BigNumber; }); - - // Node.js and other environments that support module.exports. - } else if ( true && module.exports) { - module.exports = BigNumber; - - // Browser. - } else { - if (!globalObject) { - globalObject = typeof self != 'undefined' && self ? self : window; - } - - globalObject.BigNumber = BigNumber; - } -})(this); - - -/***/ }), - -/***/ 23664: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + var getDateFromFormat = function (val, format) { + val = val + ""; + format = format + ""; + var iVal = 0; + var iFormat = 0; + var c = ""; + var token = ""; + var token2 = ""; + var x, y; + var now = new Date(); + var year = now.getYear(); + var month = now.getMonth() + 1; + var date = 1; + var hh = 0; + var mm = 0; + var ss = 0; + var ampm = ""; -const { Buffer } = __nccwpck_require__(64293) -const symbol = Symbol.for('BufferList') -function BufferList (buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf) - } - - BufferList._init.call(this, buf) -} + while (iFormat < format.length) { + // Get next token from format string + c = format.charAt(iFormat); + token = ""; + while ((format.charAt(iFormat) === c) && (iFormat < format.length)) { + token += format.charAt(iFormat++); + } + // Extract contents of value based on format token + if (token === "yyyy" || token === "yy" || token === "y") { + if (token === "yyyy") { + x = 4; + y = 4; + } + if (token === "yy") { + x = 2; + y = 2; + } + if (token === "y") { + x = 2; + y = 4; + } + year = getInt(val, iVal, x, y); + if (year === null) { + return NaN; + } + iVal += year.length; + if (year.length === 2) { + if (year > 70) { + year = 1900 + (year - 0); + } else { + year = 2000 + (year - 0); + } + } + } else if (token === "MMM" || token === "NNN") { + month = 0; + for (var i = 0; i < monthsAll.length; i++) { + var monthName = monthsAll[i]; + if (val.substring(iVal, iVal + monthName.length).toLowerCase() === monthName.toLowerCase()) { + if (token === "MMM" || (token === "NNN" && i > 11)) { + month = i + 1; + if (month > 12) { + month -= 12; + } + iVal += monthName.length; + break; + } + } + } + if ((month < 1) || (month > 12)) { + return NaN; + } + } else if (token === "EE" || token === "E") { + for (var n = 0; n < daysAll.length; n++) { + var dayName = daysAll[n]; + if (val.substring(iVal, iVal + dayName.length).toLowerCase() === dayName.toLowerCase()) { + iVal += dayName.length; + break; + } + } + } else if (token === "MM" || token === "M") { + month = getInt(val, iVal, token.length, 2); + if (month === null || (month < 1) || (month > 12)) { + return NaN; + } + iVal += month.length; + } else if (token === "dd" || token === "d") { + date = getInt(val, iVal, token.length, 2); + if (date === null || (date < 1) || (date > 31)) { + return NaN; + } + iVal += date.length; + } else if (token === "hh" || token === "h") { + hh = getInt(val, iVal, token.length, 2); + if (hh === null || (hh < 1) || (hh > 12)) { + return NaN; + } + iVal += hh.length; + } else if (token === "HH" || token === "H") { + hh = getInt(val, iVal, token.length, 2); + if (hh === null || (hh < 0) || (hh > 23)) { + return NaN; + } + iVal += hh.length; + } else if (token === "KK" || token === "K") { + hh = getInt(val, iVal, token.length, 2); + if (hh === null || (hh < 0) || (hh > 11)) { + return NaN; + } + iVal += hh.length; + } else if (token === "kk" || token === "k") { + hh = getInt(val, iVal, token.length, 2); + if (hh === null || (hh < 1) || (hh > 24)) { + return NaN; + } + iVal += hh.length; + hh--; + } else if (token === "mm" || token === "m") { + mm = getInt(val, iVal, token.length, 2); + if (mm === null || (mm < 0) || (mm > 59)) { + return NaN; + } + iVal += mm.length; + } else if (token === "ss" || token === "s") { + ss = getInt(val, iVal, token.length, 2); + if (ss === null || (ss < 0) || (ss > 59)) { + return NaN; + } + iVal += ss.length; + } else if (token === "a") { + if (val.substring(iVal, iVal + 2).toLowerCase() === "am") { + ampm = "AM"; + } else if (val.substring(iVal, iVal + 2).toLowerCase() === "pm") { + ampm = "PM"; + } else { + return NaN; + } + iVal += 2; + } else { + if (val.substring(iVal, iVal + token.length) !== token) { + return NaN; + } else { + iVal += token.length; + } + } + } + // If there are any trailing characters left in the value, it doesn't match + if (iVal !== val.length) { + return NaN; + } + // Is date valid for month? + if (month === 2) { + // Check for leap year + if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) { // leap year + if (date > 29) { + return NaN; + } + } else { + if (date > 28) { + return NaN; + } + } + } + if ((month === 4) || (month === 6) || (month === 9) || (month === 11)) { + if (date > 30) { + return NaN; + } + } + // Correct hours value + if (hh < 12 && ampm === "PM") { + hh = hh - 0 + 12; + } else if (hh > 11 && ampm === "AM") { + hh -= 12; + } + var newdate = new Date(year, month - 1, date, hh, mm, ss); + return newdate.getTime(); + }; -BufferList._init = function _init (buf) { - Object.defineProperty(this, symbol, { value: true }) - this._bufs = [] - this.length = 0 + /** @ignore */ + Date.parse = function (date, format) { + if (format) { + return getDateFromFormat(date, format); + } + var timestamp = origParse(date), minutesOffset = 0, match; + if (isNaN(timestamp) && (match = /^(\d{4}|[+\-]\d{6})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?))?/.exec(date))) { + if (match[8] !== 'Z') { + minutesOffset = +match[10] * 60 + (+match[11]); - if (buf) { - this.append(buf) - } -} + if (match[9] === '+') { + minutesOffset = 0 - minutesOffset; + } + } -BufferList.prototype._new = function _new (buf) { - return new BufferList(buf) -} + match[7] = match[7] || '000'; -BufferList.prototype._offset = function _offset (offset) { - if (offset === 0) { - return [0, 0] - } + timestamp = Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4], +match[5] + minutesOffset, +match[6], +match[7].substr(0, 3)); + } - let tot = 0 + return timestamp; + }; - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot] + function polyfill(name, func) { + if (Date.prototype[name] === undefined) { + Date.prototype[name] = func; + } } - tot = _t - } -} -BufferList.prototype._reverseOffset = function (blOffset) { - const bufferId = blOffset[0] - let offset = blOffset[1] + /** + Returns new instance of Date object with the date set to today and + the time set to midnight + @static + @returns {Date} Today's Date + @function today + @memberof Date + */ + Date.today = function () { + return new Date().clearTime(); + }; - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } + /** + Returns new instance of Date object with the date set to today and + the time set to midnight in UTC + @static + @returns {Date} Today's Date in UTC + @function UTCtoday + @memberof Date + */ + Date.UTCtoday = function () { + return new Date().clearUTCTime(); + }; - return offset -} + /** + Returns new instance of Date object with the date set to tomorrow and + the time set to midnight + @static + @returns {Date} Tomorrow's Date + @function tomorrow + @memberof Date + */ + Date.tomorrow = function () { + return Date.today().add({days: 1}); + }; -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } + /** + Returns new instance of Date object with the date set to tomorrow and + the time set to midnight in UTC + @static + @returns {Date} Tomorrow's Date in UTC + @function UTCtomorrow + @memberof Date + */ + Date.UTCtomorrow = function () { + return Date.UTCtoday().add({days: 1}); + }; - const offset = this._offset(index) + /** + Returns new instance of Date object with the date set to yesterday and + the time set to midnight + @static + @returns {Date} Yesterday's Date + @function yesterday + @memberof Date + */ + Date.yesterday = function () { + return Date.today().add({days: -1}); + }; - return this._bufs[offset[0]][offset[1]] -} + /** + Returns new instance of Date object with the date set to yesterday and + the time set to midnight in UTC + @static + @returns {Date} Yesterday's Date in UTC + @function UTCyesterday + @memberof Date + */ + Date.UTCyesterday = function () { + return Date.UTCtoday().add({days: -1}); + }; -BufferList.prototype.slice = function slice (start, end) { - if (typeof start === 'number' && start < 0) { - start += this.length - } + /** + Returns whether the day is valid + @static + @param day {Number} day of the month + @param year {Number} year + @param month {Number} month of the year [0-11] + @returns {Boolean} + @function validateDay + @memberof Date + */ + Date.validateDay = function (day, year, month) { + var date = new Date(year, month, day); + return (date.getFullYear() === year && + date.getMonth() === month && + date.getDate() === day); + }; - if (typeof end === 'number' && end < 0) { - end += this.length - } - - return this.copy(null, 0, start, end) -} - -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== 'number' || srcStart < 0) { - srcStart = 0 - } - - if (typeof srcEnd !== 'number' || srcEnd > this.length) { - srcEnd = this.length - } - - if (srcStart >= this.length) { - return dst || Buffer.alloc(0) - } - - if (srcEnd <= 0) { - return dst || Buffer.alloc(0) - } - - const copy = !!dst - const off = this._offset(srcStart) - const len = srcEnd - srcStart - let bytes = len - let bufoff = (copy && dstStart) || 0 - let start = off[1] - - // copy/slice everything - if (srcStart === 0 && srcEnd === this.length) { - if (!copy) { - // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } + /** + Returns whether the year is valid + @static + @param year {Number} year + @returns {Boolean} + @function validateYear + @memberof Date + */ + Date.validateYear = function (year) { + return (year >= 0 && year <= 9999); + }; - // copy, need to copy individual buffers - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } + /** + Returns whether the second is valid + @static + @param second {Number} second + @returns {Boolean} + @function validateSecond + @memberof Date + */ + Date.validateSecond = function (second) { + return (second >= 0 && second < 60); + }; - return dst - } + /** + Returns whether the month is valid [0-11] + @static + @param month {Number} month + @returns {Boolean} + @function validateMonth + @memberof Date + */ + Date.validateMonth = function (month) { + return (month >= 0 && month < 12); + }; - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } + /** + Returns whether the minute is valid + @static + @param minute {Number} minute + @returns {Boolean} + @function validateMinute + @memberof Date + */ + Date.validateMinute = function (minute) { + return (minute >= 0 && minute < 60); + }; - if (!copy) { - // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - } + /** + Returns whether the millisecond is valid + @static + @param millisecond {Number} millisecond + @returns {Boolean} + @function validateMillisecond + @memberof Date + */ + Date.validateMillisecond = function (milli) { + return (milli >= 0 && milli < 1000); + }; - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start + /** + Returns whether the hour is valid [0-23] + @static + @param hour {Number} hour + @returns {Boolean} + @function validateHour + @memberof Date + */ + Date.validateHour = function (hour) { + return (hour >= 0 && hour < 24); + }; - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break - } + /** + Compares two dates + @static + @param date1 {Date} first date + @param date2 {Date} second date + @returns {Number} -1 if date1 is less than date2, 0 if they are equal, 1 if date1 is more than date2 + @function compare + @memberof Date + */ + Date.compare = function (date1, date2) { + if (date1.valueOf() < date2.valueOf()) { + return -1; + } else if (date1.valueOf() > date2.valueOf()) { + return 1; + } + return 0; + }; - bytes -= l + /** + Compares two dates to the millisecond + @static + @param date1 {Date} first date + @param date2 {Date} second date + @returns {Boolean} + @function equals + @memberof Date + */ + Date.equals = function (date1, date2) { + return date1.valueOf() === date2.valueOf(); + }; - if (start) { - start = 0 - } - } + /** + Compares two dates by day + @static + @param date1 {Date} first date + @param date2 {Date} second date + @returns {Boolean} + @function equalsDay + @memberof Date + */ + Date.equalsDay = function (date1, date2) { + return date1.toYMD() === date2.toYMD(); + }; - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) + /** + Returns the day number for a day [0-6] + @static + @param day {String} day name + @returns {Number} + @function getDayNumberFromName + @memberof Date + */ + Date.getDayNumberFromName = function (name) { + return dayNames[name.toLowerCase()]; + }; - return dst -} + /** + Returns the day number for a month [0-11] + @static + @param month {String} month name + @returns {Number} + @function getMonthNumberFromName + @memberof Date + */ + Date.getMonthNumberFromName = function (name) { + return monthNames[name.toLowerCase()]; + }; -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end + /** + Returns the month name for a month [0-11] + @static + @param month {Number} month + @returns {String} + @function getMonthNameFromNumber + @memberof Date + */ + Date.getMonthNameFromNumber = function (number) { + return monthsFull[number]; + }; - if (start < 0) { - start += this.length - } + /** + Returns the month name abbreviated for a month [0-11] + @static + @param month {Number} month + @returns {String} + @function getMonthAbbrFromNumber + @memberof Date + */ + Date.getMonthAbbrFromNumber = function (number) { + return monthsAbbr[number]; + }; - if (end < 0) { - end += this.length - } + /** + Returns whether or not the year is a leap year + @static + @param year {Number} year + @returns {Boolean} + @function isLeapYear + @memberof Date + */ + Date.isLeapYear = function (year) { + return (new Date(year, 1, 29).getDate() === 29); + }; - if (start === end) { - return this._new() - } + /** + Returns the number of days in a month + @static + @param year {Number} year + @param month {Number} month + @returns {Number} + @function getDaysInMonth + @memberof Date + */ + Date.getDaysInMonth = function (year, month) { + if (month === 1) { + return Date.isLeapYear(year) ? 29 : 28; + } + return daysInMonth[month]; + }; - const startOffset = this._offset(start) - const endOffset = this._offset(end) - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) + /** + Returns the abbreviated month name + @returns {String} + @function getMonthAbbr + @instance + @memberof Date + */ + polyfill('getMonthAbbr', function () { + return monthsAbbr[this.getMonth()]; + }); - if (endOffset[1] === 0) { - buffers.pop() - } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) - } + /** + Returns the month name + @returns {String} + @function getMonthName + @instance + @memberof Date + */ + polyfill('getMonthName', function () { + return monthsFull[this.getMonth()]; + }); - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]) - } + /** + Returns the name of last month + @returns {String} + @function getLastMonthName + @instance + @memberof Date + */ + polyfill('getLastMonthName', function () { + var i = this.getMonth(); + i = (i === 0 ? 11 : i - 1); + return monthsFull[i]; + }); - return this._new(buffers) -} + /** + Returns the current UTC office + @returns {String} + @function getUTCOffset + @instance + @memberof Date + */ + polyfill('getUTCOffset', function () { + var tz = pad(Math.abs(this.getTimezoneOffset() / 0.6), 4); + if (this.getTimezoneOffset() > 0) { + tz = '-' + tz; + } + return tz; + }); -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} + /** + Returns a padded Common Log Format + @returns {String} + @function toCLFString + @deprecated Will be deprecated in version 2.0 in favor of toFormat + @instance + @memberof Date + */ + polyfill('toCLFString', function () { + return pad(this.getDate(), 2) + '/' + this.getMonthAbbr() + '/' + + this.getFullYear() + ':' + pad(this.getHours(), 2) + ':' + + pad(this.getMinutes(), 2) + ':' + pad(this.getSeconds(), 2) + + ' ' + this.getUTCOffset(); + }); -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this + /** + Returns a padded Year/Month/Day + @returns {String} + @param separator {String} optional, defaults to "-" + @function toYMD + @deprecated Will be deprecated in version 2.0 in favor of toFormat + @instance + @memberof Date + */ + polyfill('toYMD', function (separator) { + separator = typeof separator === 'undefined' ? '-' : separator; + return this.getFullYear() + separator + pad(this.getMonth() + 1, 2) + + separator + pad(this.getDate(), 2); + }); - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } - } + /** + Returns a formatted String for database insertion + @returns {String} + @function toDBString + @deprecated Will be deprecated in version 2.0 in favor of toFormat + @instance + @memberof Date + */ + polyfill('toDBString', function () { + return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1, 2) + + '-' + pad(this.getUTCDate(), 2) + ' ' + pad(this.getUTCHours(), 2) + + ':' + pad(this.getUTCMinutes(), 2) + ':' + pad(this.getUTCSeconds(), 2); + }); - return this -} + /** + Sets the time to 00:00:00.0000 and returns a new Date object + @returns {Date} + @function clearTime + @instance + @memberof Date + */ + polyfill('clearTime', function () { + this.setHours(0); + this.setMinutes(0); + this.setSeconds(0); + this.setMilliseconds(0); -BufferList.prototype.duplicate = function duplicate () { - const copy = this._new() + return this; + }); - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]) - } + /** + Sets the time to 00:00:00.0000 and returns a new Date object with set to UTC + @returns {Date} + @function clearUTCTime + @instance + @memberof Date + */ + polyfill('clearUTCTime', function () { + this.setUTCHours(0); + this.setUTCMinutes(0); + this.setUTCSeconds(0); + this.setUTCMilliseconds(0); - return copy -} + return this; + }); -BufferList.prototype.append = function append (buf) { - if (buf == null) { - return this - } + /** + Adds `milliseconds`, `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, and `years` and returns a new Date. + Usage: `data.add({ "seconds": 10, "days": 1 })` + @param additions {Object} + @returns {Date} + @function add + @instance + @memberof Date + */ + polyfill('add', function (obj) { + if (obj.milliseconds !== undefined) { + this.setMilliseconds(this.getMilliseconds() + obj.milliseconds); + } + if (obj.seconds !== undefined) { + this.setSeconds(this.getSeconds() + obj.seconds); + } + if (obj.minutes !== undefined) { + this.setMinutes(this.getMinutes() + obj.minutes); + } + if (obj.hours !== undefined) { + this.setHours(this.getHours() + obj.hours); + } + if (obj.days !== undefined) { + this.setDate(this.getDate() + obj.days); + } + if (obj.weeks !== undefined) { + this.setDate(this.getDate() + (obj.weeks * 7)); + } + if (obj.months !== undefined) { + this.setMonth(this.getMonth() + obj.months); + } + if (obj.years !== undefined) { + this.setFullYear(this.getFullYear() + obj.years); + } + return this; + }); - if (buf.buffer) { - // append a view of the underlying ArrayBuffer - this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]) - } - } else if (this._isBufferList(buf)) { - // unwrap argument into individual BufferLists - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]) - } - } else { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf === 'number') { - buf = buf.toString() - } + /** + Adds milliseconds to the Date and returns it + @returns {Date} + @param milliseconds {Number} Number of milliseconds to add + @function addMilliseconds + @deprecated Will be deprecated in version 2.0 in favor of add + @instance + @memberof Date + */ + polyfill('addMilliseconds', function (milliseconds) { + return this.add({ milliseconds: milliseconds }); + }); - this._appendBuffer(Buffer.from(buf)) - } + /** + Adds seconds to the Date and returns it + @returns {Date} + @param seconds {Number} Number of seconds to add + @function addSeconds + @deprecated Will be deprecated in version 2.0 in favor of add + @instance + @memberof Date + */ + polyfill('addSeconds', function (seconds) { + return this.add({ seconds: seconds }); + }); - return this -} + /** + Adds minutes to the Date and returns it + @returns {Date} + @param minutes {Number} Number of minutes to add + @function addMinutes + @deprecated Will be deprecated in version 2.0 in favor of add + @instance + @memberof Date + */ + polyfill('addMinutes', function (minutes) { + return this.add({ minutes: minutes }); + }); -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} + /** + Adds hours to the Date and returns it + @returns {Date} + @param hours {Number} Number of hours to add + @function addHours + @deprecated Will be deprecated in version 2.0 in favor of add + @instance + @memberof Date + */ + polyfill('addHours', function (hours) { + return this.add({ hours: hours }); + }); -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } + /** + Adds days to the Date and returns it + @returns {Date} + @param days {Number} Number of days to add + @function addSeconds + @deprecated Will be deprecated in version 2.0 in favor of add + @instance + @memberof Date + */ + polyfill('addDays', function (days) { + return this.add({ days: days }); + }); - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (this._isBufferList(search)) { - search = search.slice() - } else if (Array.isArray(search.buffer)) { - search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } + /** + Adds weeks to the Date and returns it + @returns {Date} + @param weeks {Number} Number of weeks to add + @function addWeeks + @deprecated Will be deprecated in version 2.0 in favor of add + @instance + @memberof Date + */ + polyfill('addWeeks', function (weeks) { + return this.add({ days: (weeks * 7) }); + }); - offset = Number(offset || 0) + /** + Adds months to the Date and returns it + @returns {Date} + @param months {Number} Number of months to add + @function addMonths + @deprecated Will be deprecated in version 2.0 in favor of add + @instance + @memberof Date + */ + polyfill('addMonths', function (months) { + return this.add({ months: months }); + }); - if (isNaN(offset)) { - offset = 0 - } + /** + Adds years to the Date and returns it + @returns {Date} + @param years {Number} Number of years to add + @function addYears + @deprecated Will be deprecated in version 2.0 in favor of add + @instance + @memberof Date + */ + polyfill('addYears', function (years) { + return this.add({ years: years }); + }); - if (offset < 0) { - offset = this.length + offset - } + /** + Removes `milliseconds`, `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, and `years` and returns a new Date. + Usage: `data.remove({ "seconds": 10, "days": 1 })` + @param removals {Object} + @returns {Date} + @function remove + @instance + @memberof Date + */ + polyfill('remove', function (obj) { + if (obj.seconds !== undefined) { + this.setSeconds(this.getSeconds() - obj.seconds); + } + if (obj.minutes !== undefined) { + this.setMinutes(this.getMinutes() - obj.minutes); + } + if (obj.hours !== undefined) { + this.setHours(this.getHours() - obj.hours); + } + if (obj.days !== undefined) { + this.setDate(this.getDate() - obj.days); + } + if (obj.weeks !== undefined) { + this.setDate(this.getDate() - (obj.weeks * 7)); + } + if (obj.months !== undefined) { + this.setMonth(this.getMonth() - obj.months); + } + if (obj.years !== undefined) { + this.setFullYear(this.getFullYear() - obj.years); + } + return this; + }); - if (offset < 0) { - offset = 0 - } + /** + Removes milliseconds from the Date and returns it + @returns {Date} + @param milliseconds {Number} Number of millseconds to remove + @function removeMilliseconds + @deprecated Will be deprecated in version 2.0 in favor of remove + @instance + @memberof Date + */ + polyfill('removeMilliseconds', function (milliseconds) { + throw new Error('Not implemented'); + }); - if (search.length === 0) { - return offset > this.length ? this.length : offset - } + /** + Removes seconds from the Date and returns it + @returns {Date} + @param seconds {Number} Number of seconds to remove + @function removeSeconds + @deprecated Will be deprecated in version 2.0 in favor of remove + @instance + @memberof Date + */ + polyfill('removeSeconds', function (seconds) { + return this.remove({ seconds: seconds }); + }); - const blOffset = this._offset(offset) - let blIndex = blOffset[0] // index of which internal buffer we're working on - let buffOffset = blOffset[1] // offset of the internal buffer we're working on + /** + Removes minutes from the Date and returns it + @returns {Date} + @param seconds {Number} Number of minutes to remove + @function removeMinutes + @deprecated Will be deprecated in version 2.0 in favor of remove + @instance + @memberof Date + */ + polyfill('removeMinutes', function (minutes) { + return this.remove({ minutes: minutes }); + }); - // scan over each buffer - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex] + /** + Removes hours from the Date and returns it + @returns {Date} + @param hours {Number} Number of hours to remove + @function removeHours + @deprecated Will be deprecated in version 2.0 in favor of remove + @instance + @memberof Date + */ + polyfill('removeHours', function (hours) { + return this.remove({ hours: hours }); + }); - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset + /** + Removes days from the Date and returns it + @returns {Date} + @param days {Number} Number of days to remove + @function removeDays + @deprecated Will be deprecated in version 2.0 in favor of remove + @instance + @memberof Date + */ + polyfill('removeDays', function (days) { + return this.remove({ days: days }); + }); - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset) + /** + Removes weeks from the Date and returns it + @returns {Date} + @param weeks {Number} Number of weeks to remove + @function removeWeeks + @deprecated Will be deprecated in version 2.0 in favor of remove + @instance + @memberof Date + */ + polyfill('removeWeeks', function (weeks) { + return this.remove({ days: (weeks * 7) }); + }); - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) - } + /** + Removes months from the Date and returns it + @returns {Date} + @param months {Number} Number of months to remove + @function removeMonths + @deprecated Will be deprecated in version 2.0 in favor of remove + @instance + @memberof Date + */ + polyfill('removeMonths', function (months) { + return this.remove({ months: months }); + }); - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]) + /** + Removes years from the Date and returns it + @returns {Date} + @param years {Number} Number of years to remove + @function removeYears + @deprecated Will be deprecated in version 2.0 in favor of remove + @instance + @memberof Date + */ + polyfill('removeYears', function (years) { + return this.remove({ years: years }); + }); - if (this._match(revOffset, search)) { - return revOffset + /** + Adds weekdays based on a Mon-Fri work schedule and returns it + @returns {Date} + @param weekdays {Number} Number of weekdays to add + @function addWeekdays + @instance + @memberof Date + */ + polyfill('addWeekdays', function (weekdays) { + var day = this.getDay(); + if (day === 0) { day = 7; } + var daysOffset = weekdays; + var weekspan = Math.floor(( weekdays + day - 1 ) / 5.0); + if (weekdays > 0){ + daysOffset += weekspan * 2; + if ( day > 5 ) { daysOffset -= day - 5; } + } else { + daysOffset += Math.min( weekspan * 2, 0); + if ( day > 6 ) { daysOffset -= 1; } } + return this.addDays( daysOffset ); + }); - buffOffset++ - } - } + /** + Sets the time and date to now + @function setTimeToNow + @instance + @memberof Date + */ + polyfill('setTimeToNow', function () { + var n = new Date(); + this.setMilliseconds(n.getMilliseconds()); + this.setSeconds(n.getSeconds()); + this.setMinutes(n.getMinutes()); + this.setHours(n.getHours()); + }); - buffOffset = 0 - } + /** + Returns a cloned copy of the current Date + @function clone + @instance + @memberof Date + */ + polyfill('clone', function () { + return new Date(this.valueOf()); + }); - return -1 -} + /** + Returns whether this Date is between a start and end date + @function between + @returns {Boolean} + @instance + @memberof Date + */ + polyfill('between', function (start, end) { + return (this.valueOf() >= start.valueOf() && + this.valueOf() <= end.valueOf()); + }); + /** + Compares a Date to this Date + @param {Date} Date to compare to + @function compareTo + @returns {Number} -1 if less than date, 0 if they are equal, 1 if more than date + @instance + @memberof Date + */ + polyfill('compareTo', function (date) { + return Date.compare(this, date); + }); -BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false - } + /** + Compares a Date and time to this Date and time for equality + @param {Date} Date to compare to + @function equals + @returns {Boolean} + @instance + @memberof Date + */ + polyfill('equals', function (date) { + return Date.equals(this, date); + }); - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false - } - } - return true -} + /** + Compares a Date to this Date for equality + @param {Date} Date to compare to + @function equalsDay + @returns {Boolean} + @instance + @memberof Date + */ + polyfill('equalsDay', function (date) { + return Date.equalsDay(this, date); + }); -;(function () { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null - } - - for (const m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } else { - BufferList.prototype[m] = function (offset = 0) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) + /** + Checks to see if the Date is today + @function isToday + @returns {Boolean} + @instance + @memberof Date + */ + polyfill('isToday', function () { + return Date.equalsDay(this, Date.today()); + }); -// Used internally by the class and also as an indicator of this object being -// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser -// environment because there could be multiple different copies of the -// BufferList class and some `BufferList`s might be `BufferList`s. -BufferList.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferList || BufferList.isBufferList(b) -} + /** + Compares a Date to this Date for to see if it is after the Date passed + @param {Date} Date to compare to + @function isAfter + @returns {Boolean} + @instance + @memberof Date + */ + polyfill('isAfter', function (date) { + date = date ? date : new Date(); + return (this.compareTo(date) > 0); + }); -BufferList.isBufferList = function isBufferList (b) { - return b != null && b[symbol] -} + /** + Compares a Date to this Date for to see if it is before the Date passed + @param {Date} Date to compare to + @function isBefore + @returns {Boolean} + @instance + @memberof Date + */ + polyfill('isBefore', function (date) { + date = date ? date : new Date(); + return (this.compareTo(date) < 0); + }); -module.exports = BufferList + /** + Returns `true` if the Date is a weekend using standard Saturday/Sunday definition of a weekend + @function isWeekend + @returns {Boolean} + @instance + @memberof Date + */ + polyfill('isWeekend', function (date) { + return (this.getDay() % 6 === 0); + }); + /** + Returns the number of days between this Date and the Date passed in + @function getDaysBetween + @param {Date} Date to compare to + @returns {Number} + @instance + @memberof Date + */ + polyfill('getDaysBetween', function (date) { + return ((date.clone().valueOf() - this.valueOf()) / 86400000) | 0; + }); -/***/ }), + /** + Returns the number of hours between this Date and the Date passed in + @function getHoursBetween + @param {Date} Date to compare to + @returns {Number} + @instance + @memberof Date + */ + polyfill('getHoursBetween', function (date) { + return ((date.clone().valueOf() - this.valueOf()) / 3600000) | 0; + }); -/***/ 20336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + Returns the number of minutes between this Date and the Date passed in + @function getMinutesBetween + @param {Date} Date to compare to + @returns {Number} + @instance + @memberof Date + */ + polyfill('getMinutesBetween', function (date) { + return ((date.clone().valueOf() - this.valueOf()) / 60000) | 0; + }); -"use strict"; + /** + Returns the number of seconds between this Date and the Date passed in + @function getSecondsBetween + @param {Date} Date to compare to + @returns {Number} + @instance + @memberof Date + */ + polyfill('getSecondsBetween', function (date) { + return ((date.clone().valueOf() - this.valueOf()) / 1000) | 0; + }); + /** + Returns the number of milliseconds between this Date and the Date passed in + @function getMillisecondsBetween + @param {Date} Date to compare to + @returns {Number} + @instance + @memberof Date + */ + polyfill('getMillisecondsBetween', function (date) { + return ((date.clone().valueOf() - this.valueOf())) | 0; + }); -const DuplexStream = __nccwpck_require__(85519).Duplex -const inherits = __nccwpck_require__(44124) -const BufferList = __nccwpck_require__(23664) + /** + Returns the number of months between this Date and the Date passed in + @function getMonthsBetween + @param {Date} Date to compare to + @returns {Number} + @instance + @memberof Date + */ + polyfill('getMonthsBetween', function (date) { + var daysDiff = Math.abs(((+this) / (86400 * 1000)) - ((+date) / (86400 * 1000))); + var start = new Date((+date) < (+this) ? (+date) : (+this)); + var end = new Date((date) > (+this) ? (+date) : (+this)); -function BufferListStream (callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback) - } + var months = 0; + while (+start < +end) { + months++; + start = start.addMonths(1); + } - if (typeof callback === 'function') { - this._callback = callback + var days = Math.abs(((+start) / (86400 * 1000)) - ((+end) / (86400 * 1000))); - const piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) + return months - (days / 31); + }); - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) + /** + Returns the ordinal number of this Date + @function getOrdinalNumber + @returns {Number} + @instance + @memberof Date + */ + polyfill('getOrdinalNumber', function () { + return Math.ceil((this.clone().clearTime() - new Date(this.getFullYear(), 0, 1)) / 86400000) + 1; + }); - callback = null - } + /** + Returns the a formatted version of this Date + @function toFormat + @param format {String} Format of the Date, using `YYYY`, `YY`, `MM`, `DD`, `HH`, `HH24`, `MI`, `SS`, etc + @returns {String} + @instance + @memberof Date + */ + polyfill('toFormat', function (format) { + return toFormat(format, getReplaceMap(this)); + }); - BufferList._init.call(this, callback) - DuplexStream.call(this) -} + /** + Returns the a formatted version of the UTC version of this Date + @function toUTCFormat + @param format {String} Format of the Date, using `YYYY`, `YY`, `MM`, `DD`, `HH`, `HH24`, `MI`, `SS`, etc + @returns {String} + @instance + @memberof Date + */ + polyfill('toUTCFormat', function (format) { + return toFormat(format, getUTCReplaceMap(this)); + }); -inherits(BufferListStream, DuplexStream) -Object.assign(BufferListStream.prototype, BufferList.prototype) + /** + Returns the week number of this Date + @function getWeekNumber + @returns {Number} + @instance + @memberof Date + */ + polyfill('getWeekNumber', function() { + var onejan = new Date(this.getFullYear(),0,1); + return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7); + }); -BufferListStream.prototype._new = function _new (callback) { - return new BufferListStream(callback) -} + /** + Returns the week number of this Date, zero padded + @function getFullWeekNumber + @returns {Number} + @instance + @memberof Date + */ + polyfill('getFullWeekNumber', function() { + var weekNumber = '' + this.getWeekNumber(); + if (weekNumber.length === 1) { + weekNumber = "0" + weekNumber; + } -BufferListStream.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) + return weekNumber; + }); - if (typeof callback === 'function') { - callback() - } -} - -BufferListStream.prototype._read = function _read (size) { - if (!this.length) { - return this.push(null) - } + var toFormat = function(format, replaceMap) { + var f = [ format ], i, l, s; + var replace = function (str, rep) { + var i = 0, l = f.length, j, ll, t, n = []; + for (; i < l; i++) { + if (typeof f[i] == 'string') { + t = f[i].split(str); + for (j = 0, ll = t.length - 1; j < ll; j++) { + n.push(t[j]); + n.push([rep]); // replacement pushed as non-string + } + n.push(t[ll]); + } else { + // must be a replacement, don't process, just push + n.push(f[i]); + } + } + f = n; + }; - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} + for (i in replaceMap) { + replace(i, replaceMap[i]); + } -BufferListStream.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) + s = ''; + for (i = 0, l = f.length; i < l; i++) + s += typeof f[i] == 'string' ? f[i] : f[i][0]; + return f.join(''); + }; - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} + var getReplaceMap = function(date) { + var hours = (date.getHours() % 12) ? date.getHours() % 12 : 12; + return { + 'YYYY': date.getFullYear(), + 'YY': String(date.getFullYear()).slice(-2), + 'MMMM': monthsFull[date.getMonth()], + 'MMM': monthsAbbr[date.getMonth()], + 'MM': pad(date.getMonth() + 1, 2), + 'MI': pad(date.getMinutes(), 2), + 'M': date.getMonth() + 1, + 'DDDD': daysFull[date.getDay()], + 'DDD': daysAbbr[date.getDay()], + 'DD': pad(date.getDate(), 2), + 'D': date.getDate(), + 'HH24': pad(date.getHours(), 2), + 'HH': pad(hours, 2), + 'H': hours, + 'SS': pad(date.getSeconds(), 2), + 'PP': (date.getHours() >= 12) ? 'PM' : 'AM', + 'P': (date.getHours() >= 12) ? 'pm' : 'am', + 'LL': pad(date.getMilliseconds(), 3) + }; + }; -BufferListStream.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) -} + var getUTCReplaceMap = function(date) { + var hours = (date.getUTCHours() % 12) ? date.getUTCHours() % 12 : 12; + return { + 'YYYY': date.getUTCFullYear(), + 'YY': String(date.getUTCFullYear()).slice(-2), + 'MMMM': monthsFull[date.getUTCMonth()], + 'MMM': monthsAbbr[date.getUTCMonth()], + 'MM': pad(date.getUTCMonth() + 1, 2), + 'MI': pad(date.getUTCMinutes(), 2), + 'M': date.getUTCMonth() + 1, + 'DDDD': daysFull[date.getUTCDay()], + 'DDD': daysAbbr[date.getUTCDay()], + 'DD': pad(date.getUTCDate(), 2), + 'D': date.getUTCDate(), + 'HH24': pad(date.getUTCHours(), 2), + 'HH': pad(hours, 2), + 'H': hours, + 'SS': pad(date.getUTCSeconds(), 2), + 'PP': (date.getUTCHours() >= 12) ? 'PM' : 'AM', + 'P': (date.getUTCHours() >= 12) ? 'pm' : 'am', + 'LL': pad(date.getUTCMilliseconds(), 3) + }; + }; -BufferListStream.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) -} + /* + * change the language + * @param lang => support "es" Spanish, "fr" french, "pt-BR" Portuguese Brazil + * translate => diego + */ + var language = function (lang) { + if (lang == "es") { + monthsAbbr = [ + 'Ene', + 'Feb', + 'Mar', + 'Abr', + 'May', + 'Jun', + 'Jul', + 'Ago', + 'Sep', + 'Oct', + 'Nov', + 'Dic' + ]; -BufferListStream.isBufferList = BufferList.isBufferList + monthsFull = [ + 'Enero', + 'Febrero', + 'Marzo', + 'Abril', + 'Mayo', + 'Junio', + 'Julio', + 'Agosto', + 'Septiembre', + 'Octubre', + 'Noviembre', + 'Diciembre' + ]; -module.exports = BufferListStream -module.exports.BufferListStream = BufferListStream -module.exports.BufferList = BufferList + daysAbbr = [ + 'Dom', + 'Lun', + 'Mar', + 'Mie', + 'Jue', + 'Vie', + 'Sab' + ]; + daysFull = [ + 'Domingo', + 'Lunes', + 'Martes', + 'Miércoles', + 'Jueves', + 'Viernes', + 'Sábado' + ]; -/***/ }), + dayNames = { + 'do': 0, + 'dom': 0, + 'domingo': 0, + 'lu': 1, + 'lun': 1, + 'lunes': 1, + 'ma': 2, + 'mar': 2, + 'martes': 2, + 'mi': 3, + 'mie': 3, + 'miercoles': 3, + 'ju': 4, + 'jue': 4, + 'jueves': 4, + 'vi': 5, + 'vie': 5, + 'viernes': 5, + 'sa': 6, + 'sab': 6, + 'sabado': 6 + }; + monthsAll = monthsFull.concat(monthsAbbr); + daysAll = [ + 'do', + 'dom', + 'domingo', + 'lu', + 'lun', + 'lunes', + 'ma', + 'mar', + 'martes', + 'mi', + 'mie', + 'miércoles', + 'ju', + 'jue', + 'jueves', + 'vi', + 'vie', + 'viernes', + 'sa', + 'sab', + 'sábado' + ]; -/***/ 97713: -/***/ ((module) => { + monthNames = { + 'ene': 0, + 'enero': 0, + 'feb': 1, + 'febrero': 1, + 'mar': 2, + 'marzo': 2, + 'abr': 3, + 'abril': 3, + 'may': 4, + 'mayo':4, + 'jun': 5, + 'junio': 5, + 'jul': 6, + 'julio': 6, + 'ago': 7, + 'agosto': 7, + 'sep': 8, + 'septiembre': 8, + 'oct': 9, + 'octubre': 9, + 'nov': 10, + 'noviembre': 10, + 'dic': 11, + 'diciembre': 11 + }; + } else if (lang == "fr") { + monthsAbbr = [ + 'Jan', + 'Fév', + 'Mar', + 'Avr', + 'Mai', + 'Jui', + 'Jul', + 'Aoû', + 'Sep', + 'Oct', + 'Nov', + 'Déc' + ]; -"use strict"; + monthsFull = [ + 'Janvier', + 'Février', + 'Mars', + 'Avril', + 'Mai', + 'Juin', + 'Juillet', + 'Août', + 'Septembre', + 'Octobre', + 'Novembre', + 'Décembre' + ]; + daysAbbr = [ + 'Dim', + 'Lun', + 'Mar', + 'Mer', + 'Jeu', + 'Ven', + 'Sam' + ]; -const codes = {}; + daysFull = [ + 'Dimanchi', + 'Lundi', + 'Mardi', + 'Mercredi', + 'Jeudi', + 'Vendredi', + 'Samedi' + ]; -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error - } + dayNames = { + 'di': 0, + 'dim': 0, + 'dimanchi': 0, + 'lu': 1, + 'lun': 1, + 'lundi': 1, + 'ma': 2, + 'mar': 2, + 'mardi': 2, + 'me': 3, + 'mer': 3, + 'mercredi': 3, + 'je': 4, + 'jeu': 4, + 'jeudi': 4, + 've': 5, + 'ven': 5, + 'vendredi': 5, + 'sa': 6, + 'sam': 6, + 'samedi': 6 + }; + monthsAll = monthsFull.concat(monthsAbbr); + daysAll = [ + 'di', + 'dim', + 'dimanchi', + 'lu', + 'lun', + 'lundi', + 'ma', + 'mar', + 'mardi', + 'me', + 'mer', + 'mercredi', + 'je', + 'jeu', + 'jeudi', + 've', + 'ven', + 'vendredi', + 'sa', + 'sam', + 'samedi' + ]; - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) - } - } + monthNames = { + 'jan': 0, + 'janvier': 0, + 'fév': 1, + 'février': 1, + 'mar': 2, + 'mars': 2, + 'avr': 3, + 'avril': 3, + 'mai': 4, + 'jui': 5, + 'juin': 5, + 'jul': 6, + 'juillet': 6, + 'aoû': 7, + 'août': 7, + 'sep': 8, + 'septembre': 8, + 'oct': 9, + 'octobre': 9, + 'nov': 10, + 'novembre': 10, + 'déc': 11, + 'décembre': 11 + }; + } else if (lang == "pt-BR") { + monthsAbbr = [ + 'Jan', + 'Fev', + 'Mar', + 'Abr', + 'Mai', + 'Jun', + 'Jul', + 'Ago', + 'Set', + 'Out', + 'Nov', + 'Dez' + ]; - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } + monthsFull = [ + 'Janeiro', + 'Fevereiro', + 'Março', + 'Abril', + 'Maio', + 'Junho', + 'Julho', + 'Agosto', + 'Setembro', + 'Outubro', + 'Novembro', + 'Dezembro' + ]; - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; + daysAbbr = [ + 'Dom', + 'Seg', + 'Ter', + 'Qua', + 'Qui', + 'Sex', + 'Sab' + ]; - codes[code] = NodeError; -} + daysFull = [ + 'Domingo', + 'Segunda', + 'Terça', + 'Quarta', + 'Quinta', + 'Sexta', + 'Sábado' + ]; -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } -} + dayNames = { + 'do': 0, + 'dom': 0, + 'domingo': 0, + 'se': 1, + 'seg': 1, + 'segunda': 1, + 'te': 2, + 'ter': 2, + 'terca': 2, + 'qa': 3, + 'qua': 3, + 'quarta': 3, + 'qi': 4, + 'qui': 4, + 'quinta': 4, + 'se': 5, + 'sex': 5, + 'sexta': 5, + 'sa': 6, + 'sab': 6, + 'sabado': 6 + }; + monthsAll = monthsFull.concat(monthsAbbr); + daysAll = [ + 'do', + 'dom', + 'domingo', + 'se', + 'seg', + 'segunda', + 'te', + 'ter', + 'terça', + 'qa', + 'qua', + 'quarta', + 'qi', + 'qui', + 'quinta', + 'se', + 'sex', + 'sexta', + 'sa', + 'sab', + 'sábado' + ]; -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} + monthNames = { + 'jan': 0, + 'janeiro': 0, + 'fev': 1, + 'fevereiro': 1, + 'mar': 2, + 'março': 2, + 'abr': 3, + 'abril': 3, + 'mai': 4, + 'jun': 5, + 'junho': 5, + 'jul': 6, + 'julho': 6, + 'ago': 7, + 'agosto': 7, + 'set': 8, + 'setembro': 8, + 'out': 9, + 'outubro': 9, + 'nov': 10, + 'novembro': 10, + 'dez': 11, + 'dezembro': 11 + }; + } + }; -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} + // Are we being imported?.. + if ( true && typeof module.exports === "object") { + module.exports.language = language; + } else if (true) { + exports.language = language; + } else {} +}()); -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} +/***/ }), -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } +/***/ 28222: +/***/ ((module, exports, __nccwpck_require__) => { - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } +/* eslint-env browser */ - msg += `. Received type ${typeof actual}`; - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +/** + * This is the web browser implementation of `debug()`. + */ -module.exports.q = codes; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); -/***/ }), +/** + * Colors. + */ -/***/ 13928: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.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' +]; -"use strict"; -// 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ -/**/ +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } -var objectKeys = Object.keys || function (obj) { - var keys = []; + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - for (var key in obj) { - keys.push(key); - } + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} - return keys; -}; -/**/ +/** + * Colorize log arguments if enabled. + * + * @api public + */ +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); -module.exports = Duplex; + if (!this.useColors) { + return; + } -var Readable = __nccwpck_require__(85209); + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); -var Writable = __nccwpck_require__(58729); + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); -__nccwpck_require__(44124)(Duplex, Readable); + args.splice(lastC, 0, c); +} -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } + return r; } -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - process.nextTick(onEndNT, this); +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } -function onEndNT(self) { - self.end(); -} +module.exports = __nccwpck_require__(46243)(exports); -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } +const {formatters} = module.exports; - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); /***/ }), -/***/ 4991: +/***/ 46243: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ -module.exports = PassThrough; +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(80900); + createDebug.destroy = destroy; -var Transform = __nccwpck_require__(26753); + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); -__nccwpck_require__(44124)(PassThrough, Transform); + /** + * The currently active debug mode names, and names to skip. + */ -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} + createDebug.names = []; + createDebug.skips = []; -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; -/***/ }), + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; -/***/ 85209: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -"use strict"; -// 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. + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; -module.exports = Readable; -/**/ + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } -var Duplex; -/**/ + const self = debug; -Readable.ReadableState = ReadableState; -/**/ + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -var EE = __nccwpck_require__(28614).EventEmitter; + args[0] = createDebug.coerce(args[0]); -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } -/**/ + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -var Stream = __nccwpck_require__(36238); -/**/ + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -var Buffer = __nccwpck_require__(64293).Buffer; + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. -var OurUint8Array = global.Uint8Array || function () {}; + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ + return debug; + } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -var debugUtil = __nccwpck_require__(31669); + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); -var debug; + createDebug.names = []; + createDebug.skips = []; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -var BufferList = __nccwpck_require__(70662); + namespaces = split[i].replace(/\*/g, '.*?'); -var destroyImpl = __nccwpck_require__(36994); + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -var _require = __nccwpck_require__(3533), - getHighWaterMark = _require.getHighWaterMark; + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } -var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + let i; + let len; -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } -__nccwpck_require__(44124)(Readable, Stream); + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + return false; + } -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; } -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(13928); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. +module.exports = setup; - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" +/***/ }), - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); +} - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') +/***/ }), - this.autoDestroy = !!options.autoDestroy; // has it been destroyed +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. +/** + * Module dependencies. + */ - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s +const tty = __nccwpck_require__(33867); +const util = __nccwpck_require__(31669); - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled +/** + * This is the Node.js implementation of `debug()`. + */ - this.readingMore = false; - this.decoder = null; - this.encoding = null; +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - if (options.encoding) { - if (!StringDecoder) StringDecoder = __nccwpck_require__(94841)/* .StringDecoder */ .s; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(59318); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(13928); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); - this.readable = true; + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } + obj[prop] = val; + return obj; +}, {}); - Stream.call(this); +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); } -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed +function formatArgs(args) { + const {namespace: name, useColors} = this; + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } +function load() { + return process.env.DEBUG; +} - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ +function init(debug) { + debug.inspectOpts = {}; -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; +module.exports = __nccwpck_require__(46243)(exports); - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); +const {formatters} = module.exports; - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } +/** + * Map %o to `util.inspect()`, all on a single line. + */ - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } +/***/ }), - maybeReadMore(stream, state); +/***/ 18611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = __nccwpck_require__(92413).Stream; +var util = __nccwpck_require__(31669); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; } +util.inherits(DelayedStream, Stream); -function chunkInvalid(state, chunk) { - var er; +DelayedStream.create = function(source, options) { + var delayedStream = new this(); - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - return er; -} + delayedStream.source = source; -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __nccwpck_require__(94841)/* .StringDecoder */ .s; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + return delayedStream; +}; - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); - var p = this._readableState.buffer.head; - var content = ''; +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; - while (p !== null) { - content += decoder.write(p.data); - p = p.next; +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); } - this._readableState.buffer.clear(); + this.source.resume(); +}; - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; +DelayedStream.prototype.release = function() { + this._released = true; -var MAX_HWM = 0x40000000; + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; } - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + this._bufferedEvents.push(args); +}; -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. + if (this.dataSize <= this.maxDataSize) { + return; + } + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } +/***/ }), - return state.length; -} // you can override either this method, or the async _read(n) below. +/***/ 61318: +/***/ ((module) => { -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. +/** + * Expose `Delegator`. + */ - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } +module.exports = Delegator; - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. +/** + * Initialize a delegator. + * + * @param {Object} proto + * @param {String} target + * @api public + */ - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. +function Delegator(proto, target) { + if (!(this instanceof Delegator)) return new Delegator(proto, target); + this.proto = proto; + this.target = target; + this.methods = []; + this.getters = []; + this.setters = []; + this.fluents = []; +} +/** + * Delegate method `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some +Delegator.prototype.method = function(name){ + var proto = this.proto; + var target = this.target; + this.methods.push(name); - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. + proto[name] = function(){ + return this[target][name].apply(this[target], arguments); + }; + return this; +}; - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. +/** + * Delegator accessor `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ - if (state.length === 0) state.needReadable = true; // call internal read method +Delegator.prototype.access = function(name){ + return this.getter(name).setter(name); +}; - this._read(state.highWaterMark); +/** + * Delegator getter `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. +Delegator.prototype.getter = function(name){ + var proto = this.proto; + var target = this.target; + this.getters.push(name); - if (!state.reading) n = howMuchToRead(nOrig, state); - } + proto.__defineGetter__(name, function(){ + return this[target][name]; + }); - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + return this; +}; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } +/** + * Delegator setter `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. +Delegator.prototype.setter = function(name){ + var proto = this.proto; + var target = this.target; + this.setters.push(name); - if (nOrig !== n && state.ended) endReadable(this); - } + proto.__defineSetter__(name, function(val){ + return this[target][name] = val; + }); - if (ret !== null) this.emit('data', ret); - return ret; + return this; }; -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; +/** + * Delegator fluent accessor + * + * @param {String} name + * @return {Delegator} self + * @api public + */ - if (state.decoder) { - var chunk = state.decoder.end(); +Delegator.prototype.fluent = function (name) { + var proto = this.proto; + var target = this.target; + this.fluents.push(name); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + proto[name] = function(val){ + if ('undefined' != typeof val) { + this[target][name] = val; + return this; + } else { + return this[target][name]; } - } + }; - state.ended = true; + return this; +}; - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. +/***/ }), +/***/ 18883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; +/*! + * depd + * Copyright(c) 2014-2018 Douglas Christopher Wilson + * MIT Licensed + */ - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} +/** + * Module dependencies. + */ -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. +var relative = __nccwpck_require__(85622).relative +/** + * Module exports. + */ -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} +module.exports = depd -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } +/** + * Get the path to base files on. + */ - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. +var basePath = process.cwd() +/** + * Determine if namespace is contained in the string. + */ -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + for (var i = 0; i < vals.length; i++) { + var val = vals[i] - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } - case 1: - state.pipes = [state.pipes, dest]; - break; + return false +} - default: - state.pipes.push(dest); - break; - } +/** + * Convert a data descriptor to accessor descriptor. + */ - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); + descriptor.get = function getter () { return value } - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } } - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. + delete descriptor.value + delete descriptor.writable + Object.defineProperty(obj, prop, descriptor) - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; + return descriptor +} - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken +/** + * Create arguments string to keep arity. + */ - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. +function createArgumentsString (arity) { + var str = '' - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + for (var i = 0; i < arity; i++) { + str += ', arg' + i } - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); + return str.substr(2) +} - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } +/** + * Create stack string from stack. + */ - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + if (this.message) { + str += ' deprecated ' + this.message + } - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + stack[i].toString() + } + return str +} - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. +/** + * Create deprecate for namespace in caller. + */ - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') } - dest.once('close', onclose); + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + function deprecate (message) { + // call to self as log + log.call(deprecate, message) } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) - dest.emit('pipe', src); // start the flow if it hasn't been started already. + deprecate.function = wrapfunction + deprecate.property = wrapproperty - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } + return deprecate +} - return dest; -}; +/** + * Determine if event emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; +function eehaslisteners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; + return count > 0 } -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. +/** + * Determine if namespace is ignored. + */ - if (state.pipesCount === 0) return this; // just one destination. most common case. +function isignored (namespace) { + if (process.noDeprecation) { + // --no-deprecation support + return true + } - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + var str = process.env.NO_DEPRECATION || '' - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + // namespace ignored + return containsNamespace(str, namespace) +} +/** + * Determine if namespace is traced. + */ - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; +function istraced (namespace) { + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } + var str = process.env.TRACE_DEPRECATION || '' - return this; - } // try to find the right one. + // namespace traced + return containsNamespace(str, namespace) +} +/** + * Display deprecation message. + */ - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something +function log (message, site) { + var haslisteners = eehaslisteners(process, 'deprecation') + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break } } - return res; -}; + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined -Readable.prototype.addListener = Readable.prototype.on; + if (key !== undefined && key in this._warned) { + // already warned + return + } -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); + this._warned[key] = true - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) } - return res; -}; + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file } - return res; -}; + var site = [file, line, colm] -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; + site.callSite = callSite + site.name = callSite.getFunctionName() - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } + return site } -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. +/** + * Generate a default message from the site. + */ +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name -Readable.prototype.resume = function () { - var state = this._readableState; + // make useful anonymous name + if (!funcName) { + funcName = '' + } - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() - state.flowing = !state.readableListening; - resume(this, state); + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined } - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName } -function resume_(stream, state) { - debug('resume', state.reading); +/** + * Format deprecation message without color. + */ - if (!state.reading) { - stream.read(0); +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + stack[i].toString() + } + + return formatted } - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted } -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); +/** + * Format deprecation message with color. + */ - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset - this._readableState.paused = true; - return this; -}; + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m' // cyan + } -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); + return formatted + } - while (state.flowing && stream.read() !== null) { - ; + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. + return formatted +} -Readable.prototype.wrap = function (stream) { - var _this = this; +/** + * Format call site location. + */ - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } +/** + * Get the stack as array of call sites. + */ - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) - var ret = _this.push(chunk); + // capture the stack + Error.captureStackTrace(obj) - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. + // slice this function off the top + var stack = obj.stack.slice(1) - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + return stack +} - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. +/** + * Capture call site stack from v8. + */ +function prepareObjectStackTrace (obj, stack) { + return stack +} - this._read = function (n) { - debug('wrapped _read', n); +/** + * Return a wrapped function in a deprecation message. + */ - if (paused) { - paused = false; - stream.resume(); - } - }; +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } - return this; -}; + var args = createArgumentsString(fn.length) + var stack = getStack() + var site = callSiteLocation(stack[1]) -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = __nccwpck_require__(37558); - } + site.name = fn.name - return createReadableStreamAsyncIterator(this); - }; + // eslint-disable-next-line no-new-func + var deprecatedfn = new Function('fn', 'log', 'deprecate', 'message', 'site', + '"use strict"\n' + + 'return function (' + args + ') {' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '}')(fn, log, this, message, site) + + return deprecatedfn } -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. +/** + * Wrap property in a deprecation message. + */ -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); + if (!descriptor) { + throw new TypeError('must call property on owner object') + } - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') } -} -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + // set site name + site.name = prop - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) } } -} -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = __nccwpck_require__(57039); + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; } - return -1; + Object.defineProperty(obj, prop, descriptor) } -/***/ }), +/** + * Create DeprecationError for deprecation + */ -/***/ 26753: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString -"use strict"; -// 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) -module.exports = Transform; + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) -var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) -var Duplex = __nccwpck_require__(13928); + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } -__nccwpck_require__(44124)(Transform, Duplex); + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; + return error +} - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; +/***/ }), - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} +/***/ 34889: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. +"use strict"; - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; +var platform = __nccwpck_require__(12087).platform(); +var spawnSync = __nccwpck_require__(63129).spawnSync; +var readdirSync = __nccwpck_require__(35747).readdirSync; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. +var GLIBC = 'glibc'; +var MUSL = 'musl'; +var spawnOptions = { + encoding: 'utf8', + env: process.env +}; - this.on('prefinish', prefinish); +if (!spawnSync) { + spawnSync = function () { + return { status: 126, stdout: '', stderr: '' }; + }; } -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } +function contains (needle) { + return function (haystack) { + return haystack.indexOf(needle) !== -1; + }; } -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. +function versionFromMuslLdd (out) { + return out.split(/[\r\n]+/)[1].trim().split(/\s/)[1]; +} +function safeReaddirSync (path) { + try { + return readdirSync(path); + } catch (e) {} + return []; +} -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; +var family = ''; +var version = ''; +var method = ''; -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); +if (platform === 'linux') { + // Try getconf + var glibc = spawnSync('getconf', ['GNU_LIBC_VERSION'], spawnOptions); + if (glibc.status === 0) { + family = GLIBC; + version = glibc.stdout.trim().split(' ')[1]; + method = 'getconf'; } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + // Try ldd + var ldd = spawnSync('ldd', ['--version'], spawnOptions); + if (ldd.status === 0 && ldd.stdout.indexOf(MUSL) !== -1) { + family = MUSL; + version = versionFromMuslLdd(ldd.stdout); + method = 'ldd'; + } else if (ldd.status === 1 && ldd.stderr.indexOf(MUSL) !== -1) { + family = MUSL; + version = versionFromMuslLdd(ldd.stderr); + method = 'ldd'; + } else { + // Try filesystem (family only) + var lib = safeReaddirSync('/lib'); + if (lib.some(contains('-linux-gnu'))) { + family = GLIBC; + method = 'filesystem'; + } else if (lib.some(contains('libc.musl-'))) { + family = MUSL; + method = 'filesystem'; + } else if (lib.some(contains('ld-musl-'))) { + family = MUSL; + method = 'filesystem'; + } else { + var usrSbin = safeReaddirSync('/usr/sbin'); + if (usrSbin.some(contains('glibc'))) { + family = GLIBC; + method = 'filesystem'; + } + } + } } -}; +} -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; +var isNonGlibcLinux = (family !== '' && family !== GLIBC); -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided +module.exports = { + GLIBC: GLIBC, + MUSL: MUSL, + family: family, + version: version, + method: method, + isNonGlibcLinux: isNonGlibcLinux +}; - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} /***/ }), -/***/ 58729: +/***/ 12437: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +/* @flow */ +/*:: +type DotenvParseOptions = { + debug?: boolean +} -module.exports = Writable; -/* */ +// keys and values from src +type DotenvParseOutput = { [string]: string } -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream +type DotenvConfigOptions = { + path?: string, // path to .env file + encoding?: string, // encoding of .env file + debug?: string // turn on logging for debugging purposes +} +type DotenvConfigOutput = { + parsed?: DotenvParseOutput, + error?: Error +} -function CorkedRequest(state) { - var _this = this; +*/ - this.next = null; - this.entry = null; +const fs = __nccwpck_require__(35747) +const path = __nccwpck_require__(85622) - this.finish = function () { - onCorkedFinish(_this, state); - }; +function log (message /*: string */) { + console.log(`[dotenv][DEBUG] ${message}`) } -/* */ -/**/ +const NEWLINE = '\n' +const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ +const RE_NEWLINES = /\\n/g +const NEWLINES_MATCH = /\n|\r|\r\n/ +// Parses src into an Object +function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { + const debug = Boolean(options && options.debug) + const obj = {} -var Duplex; -/**/ + // convert Buffers before splitting into lines and processing + src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { + // matching "KEY' and 'VAL' in 'KEY=VAL' + const keyValueArr = line.match(RE_INI_KEY_VAL) + // matched? + if (keyValueArr != null) { + const key = keyValueArr[1] + // default undefined or missing values to empty string + let val = (keyValueArr[2] || '') + const end = val.length - 1 + const isDoubleQuoted = val[0] === '"' && val[end] === '"' + const isSingleQuoted = val[0] === "'" && val[end] === "'" -Writable.WritableState = WritableState; -/**/ + // if single or double quoted, remove quotes + if (isSingleQuoted || isDoubleQuoted) { + val = val.substring(1, end) -var internalUtil = { - deprecate: __nccwpck_require__(65278) -}; -/**/ + // if double quoted, expand newlines + if (isDoubleQuoted) { + val = val.replace(RE_NEWLINES, NEWLINE) + } + } else { + // remove surrounding whitespace + val = val.trim() + } -/**/ + obj[key] = val + } else if (debug) { + log(`did not match key and value when parsing line ${idx + 1}: ${line}`) + } + }) -var Stream = __nccwpck_require__(36238); -/**/ + return obj +} +// Populates process.env from .env file +function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { + let dotenvPath = path.resolve(process.cwd(), '.env') + let encoding /*: string */ = 'utf8' + let debug = false -var Buffer = __nccwpck_require__(64293).Buffer; + if (options) { + if (options.path != null) { + dotenvPath = options.path + } + if (options.encoding != null) { + encoding = options.encoding + } + if (options.debug != null) { + debug = true + } + } -var OurUint8Array = global.Uint8Array || function () {}; + try { + // specifying an encoding returns a string instead of a buffer + const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} + Object.keys(parsed).forEach(function (key) { + if (!Object.prototype.hasOwnProperty.call(process.env, key)) { + process.env[key] = parsed[key] + } else if (debug) { + log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) + } + }) -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + return { parsed } + } catch (e) { + return { error: e } + } } -var destroyImpl = __nccwpck_require__(36994); - -var _require = __nccwpck_require__(3533), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +module.exports.config = config +module.exports.parse = parse -var errorOrDestroy = destroyImpl.errorOrDestroy; -__nccwpck_require__(44124)(Writable, Stream); +/***/ }), -function nop() {} +/***/ 49865: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(13928); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. +var crypto = __nccwpck_require__(76417); +var BigInteger = __nccwpck_require__(85587).BigInteger; +var ECPointFp = __nccwpck_require__(3943).ECPointFp; +var Buffer = __nccwpck_require__(15118).Buffer; +exports.ECCurves = __nccwpck_require__(41452); - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. +// zero prepad +function unstupid(hex,len) +{ + return (hex.length >= len) ? hex : unstupid("0"+hex,len); +} - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() +exports.ECKey = function(curve, key, isPublic) +{ + var priv; + var c = curve(); + var n = c.getN(); + var bytes = Math.floor(n.bitLength()/8); - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + if(key) + { + if(isPublic) + { + var curve = c.getCurve(); +// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format +// var y = key.slice(bytes+1); +// this.P = new ECPointFp(curve, +// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), +// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); + this.P = curve.decodePointHex(key.toString("hex")); + }else{ + if(key.length != bytes) return false; + priv = new BigInteger(key.toString("hex"), 16); + } + }else{ + var n1 = n.subtract(BigInteger.ONE); + var r = new BigInteger(crypto.randomBytes(n.bitLength())); + priv = r.mod(n1).add(BigInteger.ONE); + this.P = c.getG().multiply(priv); + } + if(this.P) + { +// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); +// this.PublicKey = Buffer.from("04"+pubhex,"hex"); + this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); + } + if(priv) + { + this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); + this.deriveSharedSecret = function(key) + { + if(!key || !key.P) return false; + var S = key.P.multiply(priv); + return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); + } + } +} - this.finalCalled = false; // drain event flag. - this.needDrain = false; // at the start of calling end() - this.ending = false; // when end() has been called, and returned +/***/ }), - this.ended = false; // when 'finish' is emitted +/***/ 3943: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.finished = false; // has it been destroyed +// Basic Javascript Elliptic Curve implementation +// Ported loosely from BouncyCastle's Java EC code +// Only Fp curves implemented for now - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. +// Requires jsbn.js and jsbn2.js +var BigInteger = __nccwpck_require__(85587).BigInteger +var Barrett = BigInteger.prototype.Barrett - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. +// ---------------- +// ECFieldElementFp - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. +// constructor +function ECFieldElementFp(q,x) { + this.x = x; + // TODO if(x.compareTo(q) >= 0) error + this.q = q; +} - this.length = 0; // a flag to see when we're in the middle of a write. +function feFpEquals(other) { + if(other == this) return true; + return (this.q.equals(other.q) && this.x.equals(other.x)); +} - this.writing = false; // when true all writes will be buffered until .uncork() call +function feFpToBigInteger() { + return this.x; +} - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. +function feFpNegate() { + return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); +} - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. +function feFpAdd(b) { + return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); +} - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) +function feFpSubtract(b) { + return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); +} - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) +function feFpMultiply(b) { + return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); +} +function feFpSquare() { + return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); +} - this.writecb = null; // the amount that is being written when _write is called. +function feFpDivide(b) { + return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); +} - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted +ECFieldElementFp.prototype.equals = feFpEquals; +ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; +ECFieldElementFp.prototype.negate = feFpNegate; +ECFieldElementFp.prototype.add = feFpAdd; +ECFieldElementFp.prototype.subtract = feFpSubtract; +ECFieldElementFp.prototype.multiply = feFpMultiply; +ECFieldElementFp.prototype.square = feFpSquare; +ECFieldElementFp.prototype.divide = feFpDivide; - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams +// ---------------- +// ECPointFp - this.prefinished = false; // True if the error was already emitted and should not be thrown again +// constructor +function ECPointFp(curve,x,y,z) { + this.curve = curve; + this.x = x; + this.y = y; + // Projective coordinates: either zinv == null or z * zinv == 1 + // z and zinv are just BigIntegers, not fieldElements + if(z == null) { + this.z = BigInteger.ONE; + } + else { + this.z = z; + } + this.zinv = null; + //TODO: compression flag +} - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. +function pointFpGetX() { + if(this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.x.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); +} - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') +function pointFpGetY() { + if(this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.y.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); +} - this.autoDestroy = !!options.autoDestroy; // count buffered requests +function pointFpEquals(other) { + if(other == this) return true; + if(this.isInfinity()) return other.isInfinity(); + if(other.isInfinity()) return this.isInfinity(); + var u, v; + // u = Y2 * Z1 - Y1 * Z2 + u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); + if(!u.equals(BigInteger.ZERO)) return false; + // v = X2 * Z1 - X1 * Z2 + v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); + return v.equals(BigInteger.ZERO); +} - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two +function pointFpIsInfinity() { + if((this.x == null) && (this.y == null)) return true; + return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); +} - this.corkedRequestsFree = new CorkedRequest(this); +function pointFpNegate() { + return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); } -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; +function pointFpAdd(b) { + if(this.isInfinity()) return b; + if(b.isInfinity()) return this; - while (current) { - out.push(current); - current = current.next; - } + // u = Y2 * Z1 - Y1 * Z2 + var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); + // v = X2 * Z1 - X1 * Z2 + var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); - return out; -}; + if(BigInteger.ZERO.equals(v)) { + if(BigInteger.ZERO.equals(u)) { + return this.twice(); // this == b, so double + } + return this.curve.getInfinity(); // this = -b, so infinity + } -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); + var x2 = b.x.toBigInteger(); + var y2 = b.y.toBigInteger(); + var v2 = v.square(); + var v3 = v2.multiply(v); + var x1v2 = x1.multiply(v2); + var zu2 = u.square().multiply(this.z); -var realHasInstance; + // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) + var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); + // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 + var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); + // z3 = v^3 * z1 * z2 + var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; + return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(13928); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 +function pointFpTwice() { + if(this.isInfinity()) return this; + if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. + // TODO: optimized handling of constants + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); - this.writable = true; + var y1z1 = y1.multiply(this.z); + var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); + var a = this.curve.a.toBigInteger(); - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } + // w = 3 * x1^2 + a * z1^2 + var w = x1.square().multiply(THREE); + if(!BigInteger.ZERO.equals(a)) { + w = w.add(this.z.square().multiply(a)); + } + w = w.mod(this.curve.q); + //this.curve.reduce(w); + // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) + var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); + // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 + var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); + // z3 = 8 * (y1 * z1)^3 + var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. + return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); +} +// Simple NAF (Non-Adjacent Form) multiplication algorithm +// TODO: modularize the multiplication algorithm +function pointFpMultiply(k) { + if(this.isInfinity()) return this; + if(k.signum() == 0) return this.curve.getInfinity(); -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; + var e = k; + var h = e.multiply(new BigInteger("3")); -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + var neg = this.negate(); + var R = this; - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. + var i; + for(i = h.bitLength() - 2; i > 0; --i) { + R = R.twice(); + var hBit = h.testBit(i); + var eBit = e.testBit(i); -function validChunk(stream, state, chunk, cb) { - var er; + if (hBit != eBit) { + R = R.add(hBit ? this : neg); + } + } - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } + return R; +} - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; +// Compute this*j + x*k (simultaneous multiplication) +function pointFpMultiplyTwo(j,x,k) { + var i; + if(j.bitLength() > k.bitLength()) + i = j.bitLength() - 1; + else + i = k.bitLength() - 1; + + var R = this.curve.getInfinity(); + var both = this.add(x); + while(i >= 0) { + R = R.twice(); + if(j.testBit(i)) { + if(k.testBit(i)) { + R = R.add(both); + } + else { + R = R.add(this); + } + } + else { + if(k.testBit(i)) { + R = R.add(x); + } + } + --i; } - return true; + return R; } -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } +ECPointFp.prototype.getX = pointFpGetX; +ECPointFp.prototype.getY = pointFpGetY; +ECPointFp.prototype.equals = pointFpEquals; +ECPointFp.prototype.isInfinity = pointFpIsInfinity; +ECPointFp.prototype.negate = pointFpNegate; +ECPointFp.prototype.add = pointFpAdd; +ECPointFp.prototype.twice = pointFpTwice; +ECPointFp.prototype.multiply = pointFpMultiply; +ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +// ---------------- +// ECCurveFp - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; +// constructor +function ECCurveFp(q,a,b) { + this.q = q; + this.a = this.fromBigInteger(a); + this.b = this.fromBigInteger(b); + this.infinity = new ECPointFp(this, null, null); + this.reducer = new Barrett(this.q); +} -Writable.prototype.cork = function () { - this._writableState.corked++; -}; +function curveFpGetQ() { + return this.q; +} -Writable.prototype.uncork = function () { - var state = this._writableState; +function curveFpGetA() { + return this.a; +} - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; +function curveFpGetB() { + return this.b; +} -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; +function curveFpEquals(other) { + if(other == this) return true; + return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); +} -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); +function curveFpGetInfinity() { + return this.infinity; +} -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } +function curveFpFromBigInteger(x) { + return new ECFieldElementFp(this.q, x); +} - return chunk; +function curveReduce(x) { + this.reducer.reduce(x); } -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. +// for now, work with hex strings because they're easier in JS +function curveFpDecodePointHex(s) { + switch(parseInt(s.substr(0,2), 16)) { // first byte + case 0: + return this.infinity; + case 2: + case 3: + // point compression not supported yet + return null; + case 4: + case 6: + case 7: + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len+2, len); -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); + return new ECPointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; + default: // unsupported + return null; } - } +} - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. +function curveFpEncodePointHex(p) { + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var yHex = p.getY().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) { + xHex = "0" + xHex; + } + while (yHex.length < oLen) { + yHex = "0" + yHex; + } + return "04" + xHex + yHex; +} - if (!ret) state.needDrain = true; +ECCurveFp.prototype.getQ = curveFpGetQ; +ECCurveFp.prototype.getA = curveFpGetA; +ECCurveFp.prototype.getB = curveFpGetB; +ECCurveFp.prototype.equals = curveFpEquals; +ECCurveFp.prototype.getInfinity = curveFpGetInfinity; +ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; +ECCurveFp.prototype.reduce = curveReduce; +//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; +ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; +// from: https://github.com/kaielvin/jsbn-ec-point-compression +ECCurveFp.prototype.decodePointHex = function(s) +{ + var yIsEven; + switch(parseInt(s.substr(0,2), 16)) { // first byte + case 0: + return this.infinity; + case 2: + yIsEven = false; + case 3: + if(yIsEven == undefined) yIsEven = true; + var len = s.length - 2; + var xHex = s.substr(2, len); + var x = this.fromBigInteger(new BigInteger(xHex,16)); + var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); + var beta = alpha.sqrt(); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; + if (beta == null) throw "Invalid point compression"; + + var betaValue = beta.toBigInteger(); + if (betaValue.testBit(0) != yIsEven) + { + // Use the other root + beta = this.fromBigInteger(this.getQ().subtract(betaValue)); } + return new ECPointFp(this,x,beta); + case 4: + case 6: + case 7: + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len+2, len); - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } + return new ECPointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); - return ret; + default: // unsupported + return null; + } } +ECCurveFp.prototype.encodeCompressedPointHex = function(p) +{ + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) + xHex = "0" + xHex; + var yPrefix; + if(p.getY().toBigInteger().isEven()) yPrefix = "02"; + else yPrefix = "03"; -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; + return yPrefix + xHex; } -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error +ECFieldElementFp.prototype.getR = function() +{ + if(this.r != undefined) return this.r; - finishMaybe(stream, state); - } + this.r = null; + var bitLength = this.q.bitLength(); + if (bitLength > 128) + { + var firstWord = this.q.shiftRight(bitLength - 64); + if (firstWord.intValue() == -1) + { + this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); + } + } + return this.r; } - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; +ECFieldElementFp.prototype.modMult = function(x1,x2) +{ + return this.modReduce(x1.multiply(x2)); } +ECFieldElementFp.prototype.modReduce = function(x) +{ + if (this.getR() != null) + { + var qLen = q.bitLength(); + while (x.bitLength() > (qLen + 1)) + { + var u = x.shiftRight(qLen); + var v = x.subtract(u.shiftLeft(qLen)); + if (!this.getR().equals(BigInteger.ONE)) + { + u = u.multiply(this.getR()); + } + x = u.add(v); + } + while (x.compareTo(q) >= 0) + { + x = x.subtract(q); + } + } + else + { + x = x.mod(q); + } + return x; +} +ECFieldElementFp.prototype.sqrt = function() +{ + if (!this.q.testBit(0)) throw "unsupported"; -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); + // p mod 4 == 3 + if (this.q.testBit(1)) + { + var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); + return z.square().equals(this) ? z : null; } - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); + // p mod 4 == 1 + var qMinusOne = this.q.subtract(BigInteger.ONE); + + var legendreExponent = qMinusOne.shiftRight(1); + if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) + { + return null; } - } -} -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. + var u = qMinusOne.shiftRight(2); + var k = u.shiftLeft(1).add(BigInteger.ONE); + var Q = this.x; + var fourQ = modDouble(modDouble(Q)); -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it + var U, V; + do + { + var P; + do + { + P = new BigInteger(this.q.bitLength(), new SecureRandom()); + } + while (P.compareTo(this.q) >= 0 + || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); + var result = this.lucasSequence(P, Q, k); + U = result[0]; + V = result[1]; -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + if (this.modMult(V, V).equals(fourQ)) + { + // Integer division by 2, mod q + if (V.testBit(0)) + { + V = V.add(q); + } - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; + V = V.shiftRight(1); - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; + return new ECFieldElementFp(q,V); + } } + while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite + return null; +} +ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) +{ + var n = k.bitLength(); + var s = k.getLowestSetBit(); - state.pendingcb++; - state.lastBufferedRequest = null; + var Uh = BigInteger.ONE; + var Vl = BigInteger.TWO; + var Vh = P; + var Ql = BigInteger.ONE; + var Qh = BigInteger.ONE; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); + for (var j = n - 1; j >= s + 1; --j) + { + Ql = this.modMult(Ql, Qh); + + if (k.testBit(j)) + { + Qh = this.modMult(Ql, Q); + Uh = this.modMult(Uh, Vh); + Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); + } + else + { + Qh = Ql; + Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); + Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); + } } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. + Ql = this.modMult(Ql, Qh); + Qh = this.modMult(Ql, Q); + Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); + Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Ql = this.modMult(Ql, Qh); - if (state.writing) { - break; - } + for (var j = 1; j <= s; ++j) + { + Uh = this.modMult(Uh, Vl); + Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); + Ql = this.modMult(Ql, Ql); } - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; + return [ Uh, Vl ]; } -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; +var exports = { + ECCurveFp: ECCurveFp, + ECPointFp: ECPointFp, + ECFieldElementFp: ECFieldElementFp +} - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +module.exports = exports - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. +/***/ }), +/***/ 41452: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!state.ending) endWritable(this, state, cb); - return this; -}; +// Named EC curves + +// Requires ec.js, jsbn.js, and jsbn2.js +var BigInteger = __nccwpck_require__(85587).BigInteger +var ECCurveFp = __nccwpck_require__(3943).ECCurveFp -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +// ---------------- +// X9ECParameters + +// constructor +function X9ECParameters(curve,g,n,h) { + this.curve = curve; + this.g = g; + this.n = n; + this.h = h; +} + +function x9getCurve() { + return this.curve; +} + +function x9getG() { + return this.g; +} + +function x9getN() { + return this.n; +} + +function x9getH() { + return this.h; +} + +X9ECParameters.prototype.getCurve = x9getCurve; +X9ECParameters.prototype.getG = x9getG; +X9ECParameters.prototype.getN = x9getN; +X9ECParameters.prototype.getH = x9getH; + +// ---------------- +// SECNamedCurves + +function fromHex(s) { return new BigInteger(s, 16); } + +function secp128r1() { + // p = 2^128 - 2^97 - 1 + var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); + var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); + //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); + var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "161FF7528B899B2D0C28607CA52C5B86" + + "CF5AC8395BAFEB13C02DA292DDED7A83"); + return new X9ECParameters(curve, G, n, h); +} + +function secp160k1() { + // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); + var a = BigInteger.ZERO; + var b = fromHex("7"); + //byte[] S = null; + var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + + "938CF935318FDCED6BC28286531733C3F03C4FEE"); + return new X9ECParameters(curve, G, n, h); +} + +function secp160r1() { + // p = 2^160 - 2^31 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); + var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); + //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); + var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "4A96B5688EF573284664698968C38BB913CBFC82" + + "23A628553168947D59DCC912042351377AC5FB32"); + return new X9ECParameters(curve, G, n, h); +} + +function secp192k1() { + // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); + var a = BigInteger.ZERO; + var b = fromHex("3"); + //byte[] S = null; + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); + return new X9ECParameters(curve, G, n, h); +} + +function secp192r1() { + // p = 2^192 - 2^64 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); + var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); + //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); + return new X9ECParameters(curve, G, n, h); +} + +function secp224r1() { + // p = 2^224 - 2^96 + 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); + var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); + //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); + return new X9ECParameters(curve, G, n, h); +} + +function secp256r1() { + // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 + var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); + var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); + //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); + var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); + return new X9ECParameters(curve, G, n, h); +} + +// TODO: make this into a proper hashtable +function getSECCurveByName(name) { + if(name == "secp128r1") return secp128r1(); + if(name == "secp160k1") return secp160k1(); + if(name == "secp160r1") return secp160r1(); + if(name == "secp192k1") return secp192k1(); + if(name == "secp192r1") return secp192r1(); + if(name == "secp224r1") return secp224r1(); + if(name == "secp256r1") return secp256r1(); + return null; +} + +module.exports = { + "secp128r1":secp128r1, + "secp160k1":secp160k1, + "secp160r1":secp160r1, + "secp192k1":secp192k1, + "secp192r1":secp192r1, + "secp224r1":secp224r1, + "secp256r1":secp256r1 } -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - errorOrDestroy(stream, err); - } +/***/ }), - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} +/***/ 11728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} +"use strict"; -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); +var Buffer = __nccwpck_require__(21867).Buffer; - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); +var getParamBytesForAlg = __nccwpck_require__(30528); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} - return need; +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } + + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); } -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; - state.ended = true; - stream.writable = false; -} + var inputLength = signature.length; -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } - state.corkedRequestsFree.next = corkReq; -} + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } + var rLength = signature[offset++]; - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; + var rOffset = offset; + offset += rLength; -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } -/***/ }), + var sLength = signature[offset++]; -/***/ 37558: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } -"use strict"; + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + var sOffset = offset; + offset += sLength; -var _Object$setPrototypeO; + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; -var finished = __nccwpck_require__(12659); + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} + offset = paramBytes; -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' + dst = dst.toString('base64'); + dst = base64Url(dst); - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } + return dst; } -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } - iter[kHandlePromise](resolve, reject); - }, reject); - }; + return padding; } -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); - next: function next() { - var _this = this; + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; - if (error !== null) { - return Promise.reject(error); - } + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } + var shortLength = rsBytes < MAX_OCTET; - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } - promise = new Promise(this[kHandlePromise]); - } + return dst; +} - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); +/***/ }), -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; +/***/ 30528: +/***/ ((module) => { - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); +"use strict"; - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} - iterator[kError] = err; - return; - } +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; - var resolve = iterator[kLastResolve]; +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } + throw new Error('Unknown algorithm "' + alg + '"'); +} - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; +module.exports = getParamBytesForAlg; -module.exports = createReadableStreamAsyncIterator; /***/ }), -/***/ 70662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 18212: +/***/ ((module) => { "use strict"; -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +/***/ }), -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +/***/ 38171: +/***/ ((module) => { -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +"use strict"; -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -var _require = __nccwpck_require__(64293), - Buffer = _require.Buffer; +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; -var _require2 = __nccwpck_require__(31669), - inspect = _require2.inspect; +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } -var custom = inspect && inspect.custom || 'inspect'; + return toStr.call(arr) === '[object Array]'; +}; -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } - this.head = null; - this.tail = null; - this.length = 0; - } + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; - while (p = p.next) { - ret += s + p.data; - } +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } + return obj[name]; +}; - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; + // Return the modified object + return target; +}; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - break; - } +/***/ }), - ++c; - } +/***/ 87264: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. +/* + * extsprintf.js: extended POSIX-style sprintf + */ - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; +var mod_assert = __nccwpck_require__(42357); +var mod_util = __nccwpck_require__(31669); - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; +/* + * Public interface + */ +exports.sprintf = jsSprintf; +exports.printf = jsPrintf; +exports.fprintf = jsFprintf; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } +/* + * Stripped down version of s[n]printf(3c). We make a best effort to throw an + * exception when given a format string we don't understand, rather than + * ignoring it, so that we won't break existing programs if/when we go implement + * the rest of this. + * + * This implementation currently supports specifying + * - field alignment ('-' flag), + * - zero-pad ('0' flag) + * - always show numeric sign ('+' flag), + * - field width + * - conversions for strings, decimal integers, and floats (numbers). + * - argument size specifiers. These are all accepted but ignored, since + * Javascript has no notion of the physical size of an argument. + * + * Everything else is currently unsupported, most notably precision, unsigned + * numbers, non-decimal numbers, and characters. + */ +function jsSprintf(fmt) +{ + var regex = [ + '([^%]*)', /* normal text */ + '%', /* start of format */ + '([\'\\-+ #0]*?)', /* flags (optional) */ + '([1-9]\\d*)?', /* width (optional) */ + '(\\.([1-9]\\d*))?', /* precision (optional) */ + '[lhjztL]*?', /* length mods (ignored) */ + '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ + ].join(''); + + var re = new RegExp(regex); + var args = Array.prototype.slice.call(arguments, 1); + var flags, width, precision, conversion; + var left, pad, sign, arg, match; + var ret = ''; + var argn = 1; + + mod_assert.equal('string', typeof (fmt)); + + while ((match = re.exec(fmt)) !== null) { + ret += match[1]; + fmt = fmt.substring(match[0].length); + + flags = match[2] || ''; + width = match[3] || 0; + precision = match[4] || ''; + conversion = match[6]; + left = false; + sign = false; + pad = ' '; + + if (conversion == '%') { + ret += '%'; + continue; + } - break; - } + if (args.length === 0) + throw (new Error('too few args to sprintf')); - ++c; - } + arg = args.shift(); + argn++; - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. + if (flags.match(/[\' #]/)) + throw (new Error( + 'unsupported flags: ' + flags)); - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); + if (precision.length > 0) + throw (new Error( + 'non-zero precision not supported')); - return BufferList; -}(); + if (flags.match(/-/)) + left = true; -/***/ }), + if (flags.match(/0/)) + pad = '0'; -/***/ 36994: -/***/ ((module) => { + if (flags.match(/\+/)) + sign = true; -"use strict"; - // undocumented cb() API, needed for core, not for public API + switch (conversion) { + case 's': + if (arg === undefined || arg === null) + throw (new Error('argument ' + argn + + ': attempted to print undefined or null ' + + 'as a string')); + ret += doPad(pad, width, left, arg.toString()); + break; -function destroy(err, cb) { - var _this = this; + case 'd': + arg = Math.floor(arg); + /*jsl:fallthru*/ + case 'f': + sign = sign && arg > 0 ? '+' : ''; + ret += sign + doPad(pad, width, left, + arg.toString()); + break; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; + case 'x': + ret += doPad(pad, width, left, arg.toString(16)); + break; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } + case 'j': /* non-standard */ + if (width === 0) + width = 10; + ret += mod_util.inspect(arg, false, width); + break; - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks + case 'r': /* non-standard */ + ret += dumpException(arg); + break; + default: + throw (new Error('unsupported conversion: ' + + conversion)); + } + } - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well + ret += fmt; + return (ret); +} +function jsPrintf() { + var args = Array.prototype.slice.call(arguments); + args.unshift(process.stdout); + jsFprintf.apply(null, args); +} - if (this._writableState) { - this._writableState.destroyed = true; - } +function jsFprintf(stream) { + var args = Array.prototype.slice.call(arguments, 1); + return (stream.write(jsSprintf.apply(this, args))); +} - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); +function doPad(chr, width, left, str) +{ + var ret = str; - return this; -} + while (ret.length < width) { + if (left) + ret += chr; + else + ret = chr + ret; + } -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); + return (ret); } -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} +/* + * This function dumps long stack traces for exceptions having a cause() method. + * See node-verror for an example. + */ +function dumpException(ex) +{ + var ret; -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } + if (!(ex instanceof Error)) + throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} + /* Note that V8 prepends "ex.stack" with ex.toString(). */ + ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; -function emitErrorNT(self, err) { - self.emit('error', err); -} + if (ex.cause && typeof (ex.cause) === 'function') { + var cex = ex.cause(); + if (cex) { + ret += '\nCaused by: ' + dumpException(cex); + } + } -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + return (ret); } -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; /***/ }), -/***/ 12659: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 28206: +/***/ ((module) => { "use strict"; -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). - - -var ERR_STREAM_PREMATURE_CLOSE = __nccwpck_require__(97713)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - callback.apply(this, args); - }; -} +// do not edit .js files directly - edit src/index.jst -function noop() {} -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; +module.exports = function equal(a, b) { + if (a === b) return true; - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; - var writableEnded = stream._writableState && stream._writableState.finished; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - var onerror = function onerror(err) { - callback.call(stream, err); - }; + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; - var onclose = function onclose() { - var err; + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } + for (i = length; i-- !== 0;) { + var key = keys[i]; - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + if (!equal(a[key], b[key])) return false; } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); + return true; } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} + // true if both NaN, false otherwise + return a!==a && b!==b; +}; -module.exports = eos; /***/ }), -/***/ 57039: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 30969: +/***/ ((module) => { "use strict"; -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +module.exports = function (data, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + var cmp = opts.cmp && (function (f) { + return function (node) { + return function (a, b) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + var seen = []; + return (function stringify (node) { + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + if (node === undefined) return; + if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; + if (typeof node !== 'object') return JSON.stringify(node); -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + var i, out; + if (Array.isArray(node)) { + out = '['; + for (i = 0; i < node.length; i++) { + if (i) out += ','; + out += stringify(node[i]) || 'null'; + } + return out + ']'; + } -var ERR_INVALID_ARG_TYPE = __nccwpck_require__(97713)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE; + if (node === null) return 'null'; -function from(Readable, iterable, opts) { - var iterator; + if (seen.indexOf(node) !== -1) { + if (cycles) return JSON.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var seenIndex = seen.push(node) - 1; + var keys = Object.keys(node).sort(cmp && cmp(node)); + out = ''; + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node[key]); - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); // Reading boolean to protect against _read - // being called before last iteration completion. + if (!value) continue; + if (out) out += ','; + out += JSON.stringify(key) + ':' + value; + } + seen.splice(seenIndex, 1); + return '{' + out + '}'; + })(data); +}; - var reading = false; - readable._read = function () { - if (!reading) { - reading = true; - next(); - } - }; +/***/ }), - function next() { - return _next2.apply(this, arguments); - } +/***/ 31133: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _ref = yield iterator.next(), - value = _ref.value, - done = _ref.done; +var debug; - if (done) { - readable.push(null); - } else if (readable.push((yield value))) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = __nccwpck_require__(38237)("follow-redirects"); + } + catch (error) { + debug = function () { /* */ }; + } } + debug.apply(null, arguments); +}; - return readable; -} - -module.exports = from; /***/ }), -/***/ 20740: +/***/ 67707: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). - - -var eos; +var url = __nccwpck_require__(78835); +var URL = url.URL; +var http = __nccwpck_require__(98605); +var https = __nccwpck_require__(57211); +var Writable = __nccwpck_require__(92413).Writable; +var assert = __nccwpck_require__(42357); +var debug = __nccwpck_require__(31133); -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); }; -} - -var _require$codes = __nccwpck_require__(97713)/* .codes */ .q, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +}); -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} +// Error types with codes +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded" +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = __nccwpck_require__(12659); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + self._processResponse(response); }; -} -function call(fn) { - fn(); + // Perform the first request + this._performRequest(); } +RedirectableRequest.prototype = Object.create(Writable.prototype); -function pipe(from, to) { - return from.pipe(to); -} +RedirectableRequest.prototype.abort = function () { + abortRequest(this._currentRequest); + this.emit("abort"); +}; -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); + } -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; + // Validate input and shift parameters if necessary + if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (typeof encoding === "function") { + callback = encoding; + encoding = null; } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } +}; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (typeof data === "function") { + callback = data; + data = encoding = null; + } + else if (typeof encoding === "function") { + callback = encoding; + encoding = null; } - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; - -/***/ }), - -/***/ 3533: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + this._ending = true; + } +}; +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; -var ERR_INVALID_OPT_VALUE = __nccwpck_require__(97713)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE; +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + if (callback) { + this.on("timeout", callback); + } -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } - return Math.floor(hwm); - } // Default value + // Prevent a timeout from triggering + function clearTimer() { + clearTimeout(this._timeout); + if (callback) { + self.removeListener("timeout", callback); + } + if (!this.socket) { + self._currentRequest.removeListener("socket", startTimer); + } + } + // Start the timer when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } - return state.objectMode ? 16 : 16 * 1024; -} + this.on("socket", destroyOnTimeout); + this.once("response", clearTimer); + this.once("error", clearTimer); -module.exports = { - getHighWaterMark: getHighWaterMark + return this; }; -/***/ }), +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); -/***/ 36238: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); -module.exports = __nccwpck_require__(92413); +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } -/***/ }), + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; -/***/ 85519: -/***/ ((module, exports, __nccwpck_require__) => { -var Stream = __nccwpck_require__(92413); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream.Readable; - Object.assign(module.exports, Stream); - module.exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(85209); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(58729); - exports.Duplex = __nccwpck_require__(13928); - exports.Transform = __nccwpck_require__(26753); - exports.PassThrough = __nccwpck_require__(4991); - exports.finished = __nccwpck_require__(12659); - exports.pipeline = __nccwpck_require__(20740); -} +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + this.emit("error", new TypeError("Unsupported protocol " + protocol)); + return; + } + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.substr(0, protocol.length - 1); + this._options.agent = this._options.agents[scheme]; + } -/***/ }), + // Create the native request + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + this._currentUrl = url.format(this._options); -/***/ 33717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Set up event handlers + request._redirectable = this; + for (var e = 0; e < events.length; e++) { + request.on(events[e], eventHandlers[events[e]]); + } -var concatMap = __nccwpck_require__(86891); -var balanced = __nccwpck_require__(9417); - -module.exports = expandTop; + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end. + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + /* istanbul ignore else */ + if (request === self._currentRequest) { + // Report any write errors + /* istanbul ignore if */ + if (error) { + self.emit("error", error); + } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + /* istanbul ignore else */ + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } +}; -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. + var location = response.headers.location; + if (location && this._options.followRedirects !== false && + statusCode >= 300 && statusCode < 400) { + // Abort the current request + abortRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + this.emit("error", new TooManyRedirectsError()); + return; + } -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + // Drop the Host header, as the redirect might lead to a different host + var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) || + url.parse(this._currentUrl).hostname; -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; + // Create the redirected request + var redirectUrl = url.resolve(this._currentUrl, location); + debug("redirecting to", redirectUrl); + this._isRedirect = true; + var redirectUrlParts = url.parse(redirectUrl); + Object.assign(this._options, redirectUrlParts); - var parts = []; - var m = balanced('{', '}', str); + // Drop the Authorization header if redirecting to another host + if (redirectUrlParts.hostname !== previousHostName) { + removeMatchingHeaders(/^authorization$/i, this._options.headers); + } - if (!m) - return str.split(','); + // Evaluate the beforeRedirect callback + if (typeof this._options.beforeRedirect === "function") { + var responseDetails = { headers: response.headers }; + try { + this._options.beforeRedirect.call(null, this._options, responseDetails); + } + catch (err) { + this.emit("error", err); + return; + } + this._sanitizeOptions(this._options); + } - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); + // Perform the redirected request + try { + this._performRequest(); + } + catch (cause) { + var error = new RedirectionError("Redirected request failed: " + cause.message); + error.cause = cause; + this.emit("error", error); + } + } + else { + // The response is not a redirect; return it as-is + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); + // Clean up + this._requestBodyBuffers = []; } +}; - parts.push.apply(parts, p); +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; - return parts; -} + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); -function expandTop(str) { - if (!str) - return []; + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters + if (typeof input === "string") { + var urlStr = input; + try { + input = urlToOptions(new URL(urlStr)); + } + catch (err) { + /* istanbul ignore next */ + input = url.parse(urlStr); + } + } + else if (URL && (input instanceof URL)) { + input = urlToOptions(input); + } + else { + callback = options; + options = input; + input = { protocol: protocol }; + } + if (typeof options === "function") { + callback = options; + options = null; + } - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; - return expand(escapeBraces(str), true).map(unescapeBraces); -} + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } -function identity(e) { - return e; + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; } -function embrace(str) { - return '{' + str + '}'; +/* istanbul ignore next */ +function noop() { /* empty */ } + +// from https://github.com/nodejs/node/blob/master/lib/internal/url.js +function urlToOptions(urlObject) { + var options = { + protocol: urlObject.protocol, + hostname: urlObject.hostname.startsWith("[") ? + /* istanbul ignore next */ + urlObject.hostname.slice(1, -1) : + urlObject.hostname, + hash: urlObject.hash, + search: urlObject.search, + pathname: urlObject.pathname, + path: urlObject.pathname + urlObject.search, + href: urlObject.href, + }; + if (urlObject.port !== "") { + options.port = Number(urlObject.port); + } + return options; } -function isPadded(el) { - return /^-?0\d/.test(el); + +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return lastValue; } -function lte(i, y) { - return i <= y; +function createErrorType(code, defaultMessage) { + function CustomError(message) { + Error.captureStackTrace(this, this.constructor); + this.message = message || defaultMessage; + } + CustomError.prototype = new Error(); + CustomError.prototype.constructor = CustomError; + CustomError.prototype.name = "Error [" + code + "]"; + CustomError.prototype.code = code; + return CustomError; } -function gte(i, y) { - return i >= y; + +function abortRequest(request) { + for (var e = 0; e < events.length; e++) { + request.removeListener(events[e], eventHandlers[events[e]]); + } + request.on("error", noop); + request.abort(); } -function expand(str, isTop) { - var expansions = []; +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } +/***/ }), - var n; - if (isSequence) { - n = m.body.split(/\.\./); +/***/ 47568: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = ForeverAgent +ForeverAgent.SSL = ForeverAgentSSL + +var util = __nccwpck_require__(31669) + , Agent = __nccwpck_require__(98605).Agent + , net = __nccwpck_require__(11631) + , tls = __nccwpck_require__(4016) + , AgentSSL = __nccwpck_require__(57211).Agent + +function getConnectionName(host, port) { + var name = '' + if (typeof host === 'string') { + name = host + ':' + port } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } + // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. + name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') } + return name +} - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. +function ForeverAgent(options) { + var self = this + self.options = options || {} + self.requests = {} + self.sockets = {} + self.freeSockets = {} + self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets + self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets + self.on('free', function(socket, host, port) { + var name = getConnectionName(host, port) + + if (self.requests[name] && self.requests[name].length) { + self.requests[name].shift().onSocket(socket) + } else if (self.sockets[name].length < self.minSockets) { + if (!self.freeSockets[name]) self.freeSockets[name] = [] + self.freeSockets[name].push(socket) + + // if an error happens while we don't use the socket anyway, meh, throw the socket away + var onIdleError = function() { + socket.destroy() + } + socket._onIdleError = onIdleError + socket.on('error', onIdleError) + } else { + // If there are no pending requests just destroy the + // socket and it will get removed from the pool. This + // gets us out of timeout issues and allows us to + // default to Connection:keep-alive. + socket.destroy() + } + }) - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; +} +util.inherits(ForeverAgent, Agent) - var N; +ForeverAgent.defaultMinSockets = 5 - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - N = []; +ForeverAgent.prototype.createConnection = net.createConnection +ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest +ForeverAgent.prototype.addRequest = function(req, host, port) { + var name = getConnectionName(host, port) + + if (typeof host !== 'string') { + var options = host + port = options.port + host = options.host + } + + if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { + var idleSocket = this.freeSockets[name].pop() + idleSocket.removeListener('error', idleSocket._onIdleError) + delete idleSocket._onIdleError + req._reusedSocket = true + req.onSocket(idleSocket) + } else { + this.addRequestNoreuse(req, host, port) + } +} - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } +ForeverAgent.prototype.removeSocket = function(s, name, host, port) { + if (this.sockets[name]) { + var index = this.sockets[name].indexOf(s) + if (index !== -1) { + this.sockets[name].splice(index, 1) + } + } else if (this.sockets[name] && this.sockets[name].length === 0) { + // don't leak + delete this.sockets[name] + delete this.requests[name] + } + + if (this.freeSockets[name]) { + var index = this.freeSockets[name].indexOf(s) + if (index !== -1) { + this.freeSockets[name].splice(index, 1) + if (this.freeSockets[name].length === 0) { + delete this.freeSockets[name] } - N.push(c); } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } + if (this.requests[name] && this.requests[name].length) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(name, host, port).emit('free') } +} - return expansions; +function ForeverAgentSSL (options) { + ForeverAgent.call(this, options) } +util.inherits(ForeverAgentSSL, ForeverAgent) + +ForeverAgentSSL.prototype.createConnection = createConnectionSSL +ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest + +function createConnectionSSL (port, host, options) { + if (typeof port === 'object') { + options = port; + } else if (typeof host === 'object') { + options = host; + } else if (typeof options === 'object') { + options = options; + } else { + options = {}; + } + if (typeof port === 'number') { + options.port = port; + } + + if (typeof host === 'string') { + options.host = host; + } + + return tls.connect(options); +} /***/ }), -/***/ 9239: +/***/ 64334: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -/*jshint node:true */ +var CombinedStream = __nccwpck_require__(85443); +var util = __nccwpck_require__(31669); +var path = __nccwpck_require__(85622); +var http = __nccwpck_require__(98605); +var https = __nccwpck_require__(57211); +var parseUrl = __nccwpck_require__(78835).parse; +var fs = __nccwpck_require__(35747); +var mime = __nccwpck_require__(43583); +var asynckit = __nccwpck_require__(14812); +var populate = __nccwpck_require__(17142); -var Buffer = __nccwpck_require__(64293).Buffer; // browserify -var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; +// Public API +module.exports = FormData; -module.exports = bufferEq; +// make it a Stream +util.inherits(FormData, CombinedStream); -function bufferEq(a, b) { +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(); + } - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { + this[option] = options[option]; } +} - // buffer sizes should be well-known information, so despite this - // shortcutting, it doesn't leak any information about the *contents* of the - // buffers. - if (a.length !== b.length) { - return false; +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function(field, value, options) { + + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; } - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; } - return c === 0; -} -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); }; +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; -/***/ }), + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } -/***/ 78818: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._valueLength += valueLength; -"use strict"; + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; -const ansiStyles = __nccwpck_require__(52068); -const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(59318); -const { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -} = __nccwpck_require__(82415); + // empty or either doesn't have path or not an http response + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { + return; + } -const {isArray} = Array; + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = [ - 'ansi', - 'ansi', - 'ansi256', - 'ansi16m' -]; +FormData.prototype._lengthRetriever = function(value, callback) { -const styles = Object.create(null); + if (value.hasOwnProperty('fd')) { -const applyOptions = (object, options = {}) => { - if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { - throw new Error('The `level` option should be an integer from 0 to 3'); - } + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); -class ChalkClass { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } -} + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { -const chalkFactory = options => { - const chalk = {}; - applyOptions(chalk, options); + var fileSize; - chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + if (err) { + callback(err); + return; + } - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } - chalk.template.constructor = () => { - throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); - }; + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - chalk.template.Instance = ChalkClass; + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); - return chalk.template; + // something else + } else { + callback('Unknown stream'); + } }; -function Chalk(options) { - return chalkFactory(options); -} +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } -for (const [styleName, style] of Object.entries(ansiStyles)) { - styles[styleName] = { - get() { - const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); - Object.defineProperty(this, styleName, {value: builder}); - return builder; - } - }; -} + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); -styles.visible = { - get() { - const builder = createBuilder(this, this._styler, true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - } -}; + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; -const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } -for (const model of usedModels) { - styles[model] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; -for (const model of usedModels) { - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} + // skip nullish headers. + if (header == null) { + continue; + } -const proto = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this._generator.level; - }, - set(level) { - this._generator.level = level; - } - } -}); + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } -const createStyler = (open, close, parent) => { - let openAll; - let closeAll; - if (parent === undefined) { - openAll = open; - closeAll = close; - } else { - openAll = parent.openAll + open; - closeAll = close + parent.closeAll; - } + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } - return { - open, - close, - openAll, - closeAll, - parent - }; + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; }; -const createBuilder = (self, _styler, _isEmpty) => { - const builder = (...arguments_) => { - if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { - // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` - return applyStyle(builder, chalkTag(builder, ...arguments_)); - } +FormData.prototype._getContentDisposition = function(value, options) { - // Single argument is hot path, implicit coercion is faster than anything - // eslint-disable-next-line no-implicit-coercion - return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); - }; + var filename + , contentDisposition + ; - // We alter the prototype because we must return a function, but there is - // no way to create a function with a different prototype - Object.setPrototypeOf(builder, proto); + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path); + } - builder._generator = self; - builder._styler = _styler; - builder._isEmpty = _isEmpty; + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } - return builder; + return contentDisposition; }; -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self._isEmpty ? '' : string; - } +FormData.prototype._getContentType = function(value, options) { - let styler = self._styler; + // use custom content-type above all + var contentType = options.contentType; - if (styler === undefined) { - return string; - } + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } - const {openAll, closeAll} = styler; - if (string.indexOf('\u001B') !== -1) { - while (styler !== undefined) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - string = stringReplaceAll(string, styler.close, styler.open); + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } - styler = styler.parent; - } - } + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } - // We can move both next actions out of loop, because remaining actions in loop won't have - // any/visible effect on parts we add here. Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 - const lfIndex = string.indexOf('\n'); - if (lfIndex !== -1) { - string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); - } + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } - return openAll + string + closeAll; + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } + + return contentType; }; -let template; -const chalkTag = (chalk, ...strings) => { - const [firstString] = strings; +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; - if (!isArray(firstString) || !isArray(firstString.raw)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return strings.join(' '); - } + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } - const arguments_ = strings.slice(1); - const parts = [firstString.raw[0]]; + next(footer); + }.bind(this); +}; - for (let i = 1; i < firstString.length; i++) { - parts.push( - String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), - String(firstString.raw[i]) - ); - } +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; - if (template === undefined) { - template = __nccwpck_require__(20500); - } +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; - return template(chalk, parts.join('')); + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + + return formHeaders; }; -Object.defineProperties(Chalk.prototype, styles); +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } -const chalk = Chalk(); // eslint-disable-line new-cap -chalk.supportsColor = stdoutColor; -chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap -chalk.stderr.supportsColor = stderrColor; + return this._boundary; +}; -module.exports = chalk; +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + this._boundary = boundary; +}; -/***/ }), +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; -/***/ 20500: -/***/ ((module) => { + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } -"use strict"; + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } -const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + return knownLength; +}; -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; -function unescape(c) { - const u = c[0] === 'u'; - const bracket = c[1] === '{'; + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } - if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } + return hasKnownLength; +}; - if (u && bracket) { - return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); - } +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - return ESCAPES.get(c) || c; -} + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } -function parseArguments(name, arguments_) { - const results = []; - const chunks = arguments_.trim().split(/\s*,\s*/g); - let matches; + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } - for (const chunk of chunks) { - const number = Number(chunk); - if (!Number.isNaN(number)) { - results.push(number); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } - return results; -} + values.forEach(function(length) { + knownLength += length; + }); -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; + cb(null, knownLength); + }); +}; - const results = []; - let matches; +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); - return results; -} + // use custom params + } else { -function buildStyle(chalk, styles) { - const enabled = {}; - - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - - let current = chalk; - for (const [styleName, styles] of Object.entries(enabled)) { - if (!Array.isArray(styles)) { - continue; - } - - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } - current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; - } + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); - return current; -} + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } -module.exports = (chalk, temporary) => { - const styles = []; - const chunks = []; - let chunk = []; + // get content length and fire away + this.getLength(function(err, length) { + if (err) { + this._error(err); + return; + } - // eslint-disable-next-line max-params - temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { - if (escapeCharacter) { - chunk.push(unescape(escapeCharacter)); - } else if (style) { - const string = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } + // add content length + request.setHeader('Content-Length', length); - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(character); - } - }); + this.pipe(request); + if (cb) { + request.on('error', cb); + request.on('response', cb.bind(this, null)); + } + }.bind(this)); - chunks.push(chunk.join('')); + return request; +}; - if (styles.length > 0) { - const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMessage); - } +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; - return chunks.join(''); +FormData.prototype.toString = function () { + return '[object FormData]'; }; /***/ }), -/***/ 82415: +/***/ 17142: /***/ ((module) => { -"use strict"; - - -const stringReplaceAll = (string, substring, replacer) => { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } - - const substringLength = substring.length; - let endIndex = 0; - let returnValue = ''; - do { - returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; - endIndex = index + substringLength; - index = string.indexOf(substring, endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { - let endIndex = 0; - let returnValue = ''; - do { - const gotCR = string[index - 1] === '\r'; - returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; - endIndex = index + 1; - index = string.indexOf('\n', endIndex); - } while (index !== -1); +// populates missing values +module.exports = function(dst, src) { - returnValue += string.substr(endIndex); - return returnValue; -}; + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); -module.exports = { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex + return dst; }; /***/ }), -/***/ 97074: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.supportsLanguage = exports.listLanguages = exports.highlight = void 0; -var hljs = __importStar(__nccwpck_require__(60082)); -var parse5 = __importStar(__nccwpck_require__(88933)); -var parse5_htmlparser2_tree_adapter_1 = __importDefault(__nccwpck_require__(9759)); -var theme_1 = __nccwpck_require__(81442); -function colorizeNode(node, theme, context) { - if (theme === void 0) { theme = {}; } - switch (node.type) { - case 'text': { - var text = node.data; - if (context === undefined) { - return (theme.default || theme_1.DEFAULT_THEME.default || theme_1.plain)(text); - } - return text; - } - case 'tag': { - var hljsClass = /hljs-(\w+)/.exec(node.attribs.class); - if (hljsClass) { - var token_1 = hljsClass[1]; - var nodeData = node.childNodes - .map(function (node) { return colorizeNode(node, theme, token_1); }) - .join(''); - return (theme[token_1] || theme_1.DEFAULT_THEME[token_1] || theme_1.plain)(nodeData); - } - // Return the data itself when the class name isn't prefixed with a highlight.js token prefix. - // This is common in instances of sublanguages (JSX, Markdown Code Blocks, etc.) - return node.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); - } - } - throw new Error('Invalid node type ' + node.type); -} -function colorize(code, theme) { - if (theme === void 0) { theme = {}; } - var fragment = parse5.parseFragment(code, { - treeAdapter: parse5_htmlparser2_tree_adapter_1.default, - }); - return fragment.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); -} -/** - * Apply syntax highlighting to `code` with ASCII color codes. The language is automatically - * detected if not set. - * - * ```ts - * import {highlight} from 'cli-highlight'; - * import * as fs from 'fs'; - * - * fs.readFile('package.json', 'utf8', (err: any, json: string) => { - * console.log('package.json:'); - * console.log(highlight(json)); - * }); - * ``` - * - * @param code The code to highlight - * @param options Optional options - */ -function highlight(code, options) { - if (options === void 0) { options = {}; } - var html; - if (options.language) { - html = hljs.highlight(code, { language: options.language, ignoreIllegals: options.ignoreIllegals }).value; - } - else { - html = hljs.highlightAuto(code, options.languageSubset).value; - } - return colorize(html, options.theme); -} -exports.highlight = highlight; -/** - * Returns all supported languages - */ -function listLanguages() { - return hljs.listLanguages(); -} -exports.listLanguages = listLanguages; -/** - * Returns true if the language is supported - * @param name A language name, alias or file extension - */ -function supportsLanguage(name) { - return !!hljs.getLanguage(name); -} -exports.supportsLanguage = supportsLanguage; -exports.default = highlight; -__exportStar(__nccwpck_require__(81442), exports); -//# sourceMappingURL=index.js.map +/***/ 46863: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch -/***/ 81442: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +var fs = __nccwpck_require__(35747) +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync -"use strict"; +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = __nccwpck_require__(71734) -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parse = exports.stringify = exports.toJson = exports.fromJson = exports.DEFAULT_THEME = exports.plain = void 0; -var chalk_1 = __importDefault(__nccwpck_require__(78818)); -/** - * Identity function for tokens that should not be styled (returns the input string as-is). - * See [[Theme]] for an example. - */ -var plain = function (codePart) { return codePart; }; -exports.plain = plain; -/** - * The default theme. It is possible to override just individual keys. - */ -exports.DEFAULT_THEME = { - /** - * keyword in a regular Algol-style language - */ - keyword: chalk_1.default.blue, - /** - * built-in or library object (constant, class, function) - */ - built_in: chalk_1.default.cyan, - /** - * user-defined type in a language with first-class syntactically significant types, like - * Haskell - */ - type: chalk_1.default.cyan.dim, - /** - * special identifier for a built-in value ("true", "false", "null") - */ - literal: chalk_1.default.blue, - /** - * number, including units and modifiers, if any. - */ - number: chalk_1.default.green, - /** - * literal regular expression - */ - regexp: chalk_1.default.red, - /** - * literal string, character - */ - string: chalk_1.default.red, - /** - * parsed section inside a literal string - */ - subst: exports.plain, - /** - * symbolic constant, interned string, goto label - */ - symbol: exports.plain, - /** - * class or class-level declaration (interfaces, traits, modules, etc) - */ - class: chalk_1.default.blue, - /** - * function or method declaration - */ - function: chalk_1.default.yellow, - /** - * name of a class or a function at the place of declaration - */ - title: exports.plain, - /** - * block of function arguments (parameters) at the place of declaration - */ - params: exports.plain, - /** - * comment - */ - comment: chalk_1.default.green, - /** - * documentation markup within comments - */ - doctag: chalk_1.default.green, - /** - * flags, modifiers, annotations, processing instructions, preprocessor directive, etc - */ - meta: chalk_1.default.grey, - /** - * keyword or built-in within meta construct - */ - 'meta-keyword': exports.plain, - /** - * string within meta construct - */ - 'meta-string': exports.plain, - /** - * heading of a section in a config file, heading in text markup - */ - section: exports.plain, - /** - * XML/HTML tag - */ - tag: chalk_1.default.grey, - /** - * name of an XML tag, the first word in an s-expression - */ - name: chalk_1.default.blue, - /** - * s-expression name from the language standard library - */ - 'builtin-name': exports.plain, - /** - * name of an attribute with no language defined semantics (keys in JSON, setting names in - * .ini), also sub-attribute within another highlighted object, like XML tag - */ - attr: chalk_1.default.cyan, - /** - * name of an attribute followed by a structured value part, like CSS properties - */ - attribute: exports.plain, - /** - * variable in a config or a template file, environment var expansion in a script - */ - variable: exports.plain, - /** - * list item bullet in text markup - */ - bullet: exports.plain, - /** - * code block in text markup - */ - code: exports.plain, - /** - * emphasis in text markup - */ - emphasis: chalk_1.default.italic, - /** - * strong emphasis in text markup - */ - strong: chalk_1.default.bold, - /** - * mathematical formula in text markup - */ - formula: exports.plain, - /** - * hyperlink in text markup - */ - link: chalk_1.default.underline, - /** - * quotation in text markup - */ - quote: exports.plain, - /** - * tag selector in CSS - */ - 'selector-tag': exports.plain, - /** - * #id selector in CSS - */ - 'selector-id': exports.plain, - /** - * .class selector in CSS - */ - 'selector-class': exports.plain, - /** - * [attr] selector in CSS - */ - 'selector-attr': exports.plain, - /** - * :pseudo selector in CSS - */ - 'selector-pseudo': exports.plain, - /** - * tag of a template language - */ - 'template-tag': exports.plain, - /** - * variable in a template language - */ - 'template-variable': exports.plain, - /** - * added or changed line in a diff - */ - addition: chalk_1.default.green, - /** - * deleted line in a diff - */ - deletion: chalk_1.default.red, - /** - * things not matched by any token - */ - default: exports.plain, -}; -/** - * Converts a [[JsonTheme]] with string values to a [[Theme]] with formatter functions. Used by [[parse]]. - */ -function fromJson(json) { - var theme = {}; - for (var _i = 0, _a = Object.keys(json); _i < _a.length; _i++) { - var key = _a[_i]; - var style = json[key]; - if (Array.isArray(style)) { - ; - theme[key] = style.reduce(function (previous, current) { return (current === 'plain' ? exports.plain : previous[current]); }, chalk_1.default); - } - else { - ; - theme[key] = chalk_1.default[style]; - } - } - return theme; -} -exports.fromJson = fromJson; -/** - * Converts a [[Theme]] with formatter functions to a [[JsonTheme]] with string values. Used by [[stringify]]. - */ -function toJson(theme) { - var jsonTheme = {}; - for (var _i = 0, _a = Object.keys(jsonTheme); _i < _a.length; _i++) { - var key = _a[_i]; - var style = jsonTheme[key]; - jsonTheme[key] = style._styles; - } - return jsonTheme; -} -exports.toJson = toJson; -/** - * Stringifies a [[Theme]] with formatter functions to a JSON string. - * - * ```ts - * import chalk = require('chalk'); - * import {stringify} from 'cli-highlight'; - * import * as fs from 'fs'; - * - * const myTheme: Theme = { - * keyword: chalk.red.bold, - * addition: chalk.green, - * deletion: chalk.red.strikethrough, - * number: plain - * } - * const json = stringify(myTheme); - * fs.writeFile('mytheme.json', json, (err: any) => { - * if (err) throw err; - * console.log('Theme saved'); - * }); - * ``` - */ -function stringify(theme) { - return JSON.stringify(toJson(theme)); -} -exports.stringify = stringify; -/** - * Parses a JSON string into a [[Theme]] with formatter functions. - * - * ```ts - * import * as fs from 'fs'; - * import {parse, highlight} from 'cli-highlight'; - * - * fs.readFile('mytheme.json', 'utf8', (err: any, json: string) => { - * if (err) throw err; - * const code = highlight('SELECT * FROM table', {theme: parse(json)}); - * console.log(code); - * }); - * ``` - */ -function parse(json) { - return fromJson(JSON.parse(json)); +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) } -exports.parse = parse; -//# sourceMappingURL=theme.js.map - -/***/ }), - -/***/ 94281: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -const { DOCUMENT_MODE } = __nccwpck_require__(49578); - -//Const -const VALID_DOCTYPE_NAME = 'html'; -const VALID_SYSTEM_ID = 'about:legacy-compat'; -const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd'; - -const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [ - '+//silmaril//dtd html pro v0r11 19970101//', - '-//as//dtd html 3.0 aswedit + extensions//', - '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', - '-//ietf//dtd html 2.0 level 1//', - '-//ietf//dtd html 2.0 level 2//', - '-//ietf//dtd html 2.0 strict level 1//', - '-//ietf//dtd html 2.0 strict level 2//', - '-//ietf//dtd html 2.0 strict//', - '-//ietf//dtd html 2.0//', - '-//ietf//dtd html 2.1e//', - '-//ietf//dtd html 3.0//', - '-//ietf//dtd html 3.2 final//', - '-//ietf//dtd html 3.2//', - '-//ietf//dtd html 3//', - '-//ietf//dtd html level 0//', - '-//ietf//dtd html level 1//', - '-//ietf//dtd html level 2//', - '-//ietf//dtd html level 3//', - '-//ietf//dtd html strict level 0//', - '-//ietf//dtd html strict level 1//', - '-//ietf//dtd html strict level 2//', - '-//ietf//dtd html strict level 3//', - '-//ietf//dtd html strict//', - '-//ietf//dtd html//', - '-//metrius//dtd metrius presentational//', - '-//microsoft//dtd internet explorer 2.0 html strict//', - '-//microsoft//dtd internet explorer 2.0 html//', - '-//microsoft//dtd internet explorer 2.0 tables//', - '-//microsoft//dtd internet explorer 3.0 html strict//', - '-//microsoft//dtd internet explorer 3.0 html//', - '-//microsoft//dtd internet explorer 3.0 tables//', - '-//netscape comm. corp.//dtd html//', - '-//netscape comm. corp.//dtd strict html//', - "-//o'reilly and associates//dtd html 2.0//", - "-//o'reilly and associates//dtd html extended 1.0//", - "-//o'reilly and associates//dtd html extended relaxed 1.0//", - '-//sq//dtd html 2.0 hotmetal + extensions//', - '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', - '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', - '-//spyglass//dtd html 2.0 extended//', - '-//sun microsystems corp.//dtd hotjava html//', - '-//sun microsystems corp.//dtd hotjava strict html//', - '-//w3c//dtd html 3 1995-03-24//', - '-//w3c//dtd html 3.2 draft//', - '-//w3c//dtd html 3.2 final//', - '-//w3c//dtd html 3.2//', - '-//w3c//dtd html 3.2s draft//', - '-//w3c//dtd html 4.0 frameset//', - '-//w3c//dtd html 4.0 transitional//', - '-//w3c//dtd html experimental 19960712//', - '-//w3c//dtd html experimental 970421//', - '-//w3c//dtd w3 html//', - '-//w3o//dtd w3 html 3.0//', - '-//webtechs//dtd mozilla html 2.0//', - '-//webtechs//dtd mozilla html//' -]; - -const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = QUIRKS_MODE_PUBLIC_ID_PREFIXES.concat([ - '-//w3c//dtd html 4.01 frameset//', - '-//w3c//dtd html 4.01 transitional//' -]); - -const QUIRKS_MODE_PUBLIC_IDS = ['-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html']; -const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//']; - -const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = LIMITED_QUIRKS_PUBLIC_ID_PREFIXES.concat([ - '-//w3c//dtd html 4.01 frameset//', - '-//w3c//dtd html 4.01 transitional//' -]); - -//Utils -function enquoteDoctypeId(id) { - const quote = id.indexOf('"') !== -1 ? "'" : '"'; - - return quote + id + quote; -} +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } -function hasPrefix(publicId, prefixes) { - for (let i = 0; i < prefixes.length; i++) { - if (publicId.indexOf(prefixes[i]) === 0) { - return true; - } + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) } - - return false; + }) } -//API -exports.isConforming = function(token) { - return ( - token.name === VALID_DOCTYPE_NAME && - token.publicId === null && - (token.systemId === null || token.systemId === VALID_SYSTEM_ID) - ); -}; - -exports.getDocumentMode = function(token) { - if (token.name !== VALID_DOCTYPE_NAME) { - return DOCUMENT_MODE.QUIRKS; - } - - const systemId = token.systemId; - - if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) { - return DOCUMENT_MODE.QUIRKS; - } - - let publicId = token.publicId; - - if (publicId !== null) { - publicId = publicId.toLowerCase(); - - if (QUIRKS_MODE_PUBLIC_IDS.indexOf(publicId) > -1) { - return DOCUMENT_MODE.QUIRKS; - } - - let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES; - - if (hasPrefix(publicId, prefixes)) { - return DOCUMENT_MODE.QUIRKS; - } - - prefixes = - systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES; - - if (hasPrefix(publicId, prefixes)) { - return DOCUMENT_MODE.LIMITED_QUIRKS; - } - } - - return DOCUMENT_MODE.NO_QUIRKS; -}; - -exports.serializeContent = function(name, publicId, systemId) { - let str = '!DOCTYPE '; - - if (name) { - str += name; - } +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } - if (publicId) { - str += ' PUBLIC ' + enquoteDoctypeId(publicId); - } else if (systemId) { - str += ' SYSTEM'; + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er } + } +} - if (systemId !== null) { - str += ' ' + enquoteDoctypeId(systemId); - } +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync +} - return str; -}; +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync +} /***/ }), -/***/ 65510: -/***/ ((module) => { - -"use strict"; - - -module.exports = { - controlCharacterInInputStream: 'control-character-in-input-stream', - noncharacterInInputStream: 'noncharacter-in-input-stream', - surrogateInInputStream: 'surrogate-in-input-stream', - nonVoidHtmlElementStartTagWithTrailingSolidus: 'non-void-html-element-start-tag-with-trailing-solidus', - endTagWithAttributes: 'end-tag-with-attributes', - endTagWithTrailingSolidus: 'end-tag-with-trailing-solidus', - unexpectedSolidusInTag: 'unexpected-solidus-in-tag', - unexpectedNullCharacter: 'unexpected-null-character', - unexpectedQuestionMarkInsteadOfTagName: 'unexpected-question-mark-instead-of-tag-name', - invalidFirstCharacterOfTagName: 'invalid-first-character-of-tag-name', - unexpectedEqualsSignBeforeAttributeName: 'unexpected-equals-sign-before-attribute-name', - missingEndTagName: 'missing-end-tag-name', - unexpectedCharacterInAttributeName: 'unexpected-character-in-attribute-name', - unknownNamedCharacterReference: 'unknown-named-character-reference', - missingSemicolonAfterCharacterReference: 'missing-semicolon-after-character-reference', - unexpectedCharacterAfterDoctypeSystemIdentifier: 'unexpected-character-after-doctype-system-identifier', - unexpectedCharacterInUnquotedAttributeValue: 'unexpected-character-in-unquoted-attribute-value', - eofBeforeTagName: 'eof-before-tag-name', - eofInTag: 'eof-in-tag', - missingAttributeValue: 'missing-attribute-value', - missingWhitespaceBetweenAttributes: 'missing-whitespace-between-attributes', - missingWhitespaceAfterDoctypePublicKeyword: 'missing-whitespace-after-doctype-public-keyword', - missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers: - 'missing-whitespace-between-doctype-public-and-system-identifiers', - missingWhitespaceAfterDoctypeSystemKeyword: 'missing-whitespace-after-doctype-system-keyword', - missingQuoteBeforeDoctypePublicIdentifier: 'missing-quote-before-doctype-public-identifier', - missingQuoteBeforeDoctypeSystemIdentifier: 'missing-quote-before-doctype-system-identifier', - missingDoctypePublicIdentifier: 'missing-doctype-public-identifier', - missingDoctypeSystemIdentifier: 'missing-doctype-system-identifier', - abruptDoctypePublicIdentifier: 'abrupt-doctype-public-identifier', - abruptDoctypeSystemIdentifier: 'abrupt-doctype-system-identifier', - cdataInHtmlContent: 'cdata-in-html-content', - incorrectlyOpenedComment: 'incorrectly-opened-comment', - eofInScriptHtmlCommentLikeText: 'eof-in-script-html-comment-like-text', - eofInDoctype: 'eof-in-doctype', - nestedComment: 'nested-comment', - abruptClosingOfEmptyComment: 'abrupt-closing-of-empty-comment', - eofInComment: 'eof-in-comment', - incorrectlyClosedComment: 'incorrectly-closed-comment', - eofInCdata: 'eof-in-cdata', - absenceOfDigitsInNumericCharacterReference: 'absence-of-digits-in-numeric-character-reference', - nullCharacterReference: 'null-character-reference', - surrogateCharacterReference: 'surrogate-character-reference', - characterReferenceOutsideUnicodeRange: 'character-reference-outside-unicode-range', - controlCharacterReference: 'control-character-reference', - noncharacterCharacterReference: 'noncharacter-character-reference', - missingWhitespaceBeforeDoctypeName: 'missing-whitespace-before-doctype-name', - missingDoctypeName: 'missing-doctype-name', - invalidCharacterSequenceAfterDoctypeName: 'invalid-character-sequence-after-doctype-name', - duplicateAttribute: 'duplicate-attribute', - nonConformingDoctype: 'non-conforming-doctype', - missingDoctype: 'missing-doctype', - misplacedDoctype: 'misplaced-doctype', - endTagWithoutMatchingOpenElement: 'end-tag-without-matching-open-element', - closingOfElementWithOpenChildElements: 'closing-of-element-with-open-child-elements', - disallowedContentInNoscriptInHead: 'disallowed-content-in-noscript-in-head', - openElementsLeftAfterEof: 'open-elements-left-after-eof', - abandonedHeadElementChild: 'abandoned-head-element-child', - misplacedStartTagForHeadElement: 'misplaced-start-tag-for-head-element', - nestedNoscriptInHead: 'nested-noscript-in-head', - eofInElementThatCanContainOnlyText: 'eof-in-element-that-can-contain-only-text' -}; - - -/***/ }), - -/***/ 24320: +/***/ 71734: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - +// 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. -const Tokenizer = __nccwpck_require__(66480); -const HTML = __nccwpck_require__(49578); - -//Aliases -const $ = HTML.TAG_NAMES; -const NS = HTML.NAMESPACES; -const ATTRS = HTML.ATTRS; - -//MIME types -const MIME_TYPES = { - TEXT_HTML: 'text/html', - APPLICATION_XML: 'application/xhtml+xml' -}; - -//Attributes -const DEFINITION_URL_ATTR = 'definitionurl'; -const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL'; -const SVG_ATTRS_ADJUSTMENT_MAP = { - attributename: 'attributeName', - attributetype: 'attributeType', - basefrequency: 'baseFrequency', - baseprofile: 'baseProfile', - calcmode: 'calcMode', - clippathunits: 'clipPathUnits', - diffuseconstant: 'diffuseConstant', - edgemode: 'edgeMode', - filterunits: 'filterUnits', - glyphref: 'glyphRef', - gradienttransform: 'gradientTransform', - gradientunits: 'gradientUnits', - kernelmatrix: 'kernelMatrix', - kernelunitlength: 'kernelUnitLength', - keypoints: 'keyPoints', - keysplines: 'keySplines', - keytimes: 'keyTimes', - lengthadjust: 'lengthAdjust', - limitingconeangle: 'limitingConeAngle', - markerheight: 'markerHeight', - markerunits: 'markerUnits', - markerwidth: 'markerWidth', - maskcontentunits: 'maskContentUnits', - maskunits: 'maskUnits', - numoctaves: 'numOctaves', - pathlength: 'pathLength', - patterncontentunits: 'patternContentUnits', - patterntransform: 'patternTransform', - patternunits: 'patternUnits', - pointsatx: 'pointsAtX', - pointsaty: 'pointsAtY', - pointsatz: 'pointsAtZ', - preservealpha: 'preserveAlpha', - preserveaspectratio: 'preserveAspectRatio', - primitiveunits: 'primitiveUnits', - refx: 'refX', - refy: 'refY', - repeatcount: 'repeatCount', - repeatdur: 'repeatDur', - requiredextensions: 'requiredExtensions', - requiredfeatures: 'requiredFeatures', - specularconstant: 'specularConstant', - specularexponent: 'specularExponent', - spreadmethod: 'spreadMethod', - startoffset: 'startOffset', - stddeviation: 'stdDeviation', - stitchtiles: 'stitchTiles', - surfacescale: 'surfaceScale', - systemlanguage: 'systemLanguage', - tablevalues: 'tableValues', - targetx: 'targetX', - targety: 'targetY', - textlength: 'textLength', - viewbox: 'viewBox', - viewtarget: 'viewTarget', - xchannelselector: 'xChannelSelector', - ychannelselector: 'yChannelSelector', - zoomandpan: 'zoomAndPan' -}; - -const XML_ATTRS_ADJUSTMENT_MAP = { - 'xlink:actuate': { prefix: 'xlink', name: 'actuate', namespace: NS.XLINK }, - 'xlink:arcrole': { prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK }, - 'xlink:href': { prefix: 'xlink', name: 'href', namespace: NS.XLINK }, - 'xlink:role': { prefix: 'xlink', name: 'role', namespace: NS.XLINK }, - 'xlink:show': { prefix: 'xlink', name: 'show', namespace: NS.XLINK }, - 'xlink:title': { prefix: 'xlink', name: 'title', namespace: NS.XLINK }, - 'xlink:type': { prefix: 'xlink', name: 'type', namespace: NS.XLINK }, - 'xml:base': { prefix: 'xml', name: 'base', namespace: NS.XML }, - 'xml:lang': { prefix: 'xml', name: 'lang', namespace: NS.XML }, - 'xml:space': { prefix: 'xml', name: 'space', namespace: NS.XML }, - xmlns: { prefix: '', name: 'xmlns', namespace: NS.XMLNS }, - 'xmlns:xlink': { prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS } -}; - -//SVG tag names adjustment map -const SVG_TAG_NAMES_ADJUSTMENT_MAP = (exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = { - altglyph: 'altGlyph', - altglyphdef: 'altGlyphDef', - altglyphitem: 'altGlyphItem', - animatecolor: 'animateColor', - animatemotion: 'animateMotion', - animatetransform: 'animateTransform', - clippath: 'clipPath', - feblend: 'feBlend', - fecolormatrix: 'feColorMatrix', - fecomponenttransfer: 'feComponentTransfer', - fecomposite: 'feComposite', - feconvolvematrix: 'feConvolveMatrix', - fediffuselighting: 'feDiffuseLighting', - fedisplacementmap: 'feDisplacementMap', - fedistantlight: 'feDistantLight', - feflood: 'feFlood', - fefunca: 'feFuncA', - fefuncb: 'feFuncB', - fefuncg: 'feFuncG', - fefuncr: 'feFuncR', - fegaussianblur: 'feGaussianBlur', - feimage: 'feImage', - femerge: 'feMerge', - femergenode: 'feMergeNode', - femorphology: 'feMorphology', - feoffset: 'feOffset', - fepointlight: 'fePointLight', - fespecularlighting: 'feSpecularLighting', - fespotlight: 'feSpotLight', - fetile: 'feTile', - feturbulence: 'feTurbulence', - foreignobject: 'foreignObject', - glyphref: 'glyphRef', - lineargradient: 'linearGradient', - radialgradient: 'radialGradient', - textpath: 'textPath' -}); +var pathModule = __nccwpck_require__(85622); +var isWindows = process.platform === 'win32'; +var fs = __nccwpck_require__(35747); -//Tags that causes exit from foreign content -const EXITS_FOREIGN_CONTENT = { - [$.B]: true, - [$.BIG]: true, - [$.BLOCKQUOTE]: true, - [$.BODY]: true, - [$.BR]: true, - [$.CENTER]: true, - [$.CODE]: true, - [$.DD]: true, - [$.DIV]: true, - [$.DL]: true, - [$.DT]: true, - [$.EM]: true, - [$.EMBED]: true, - [$.H1]: true, - [$.H2]: true, - [$.H3]: true, - [$.H4]: true, - [$.H5]: true, - [$.H6]: true, - [$.HEAD]: true, - [$.HR]: true, - [$.I]: true, - [$.IMG]: true, - [$.LI]: true, - [$.LISTING]: true, - [$.MENU]: true, - [$.META]: true, - [$.NOBR]: true, - [$.OL]: true, - [$.P]: true, - [$.PRE]: true, - [$.RUBY]: true, - [$.S]: true, - [$.SMALL]: true, - [$.SPAN]: true, - [$.STRONG]: true, - [$.STRIKE]: true, - [$.SUB]: true, - [$.SUP]: true, - [$.TABLE]: true, - [$.TT]: true, - [$.U]: true, - [$.UL]: true, - [$.VAR]: true -}; - -//Check exit from foreign content -exports.causesExit = function(startTagToken) { - const tn = startTagToken.tagName; - const isFontWithAttrs = - tn === $.FONT && - (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null || - Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null || - Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null); - - return isFontWithAttrs ? true : EXITS_FOREIGN_CONTENT[tn]; -}; - -//Token adjustments -exports.adjustTokenMathMLAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - if (token.attrs[i].name === DEFINITION_URL_ATTR) { - token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR; - break; - } - } -}; +// JavaScript implementation of realpath, ported from node pre-v6 -exports.adjustTokenSVGAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); - if (adjustedAttrName) { - token.attrs[i].name = adjustedAttrName; - } - } -}; +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; -exports.adjustTokenXMLAttrs = function(token) { - for (let i = 0; i < token.attrs.length; i++) { - const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name]; + return callback; - if (adjustedAttrEntry) { - token.attrs[i].prefix = adjustedAttrEntry.prefix; - token.attrs[i].name = adjustedAttrEntry.name; - token.attrs[i].namespace = adjustedAttrEntry.namespace; - } + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); } -}; - -exports.adjustTokenSVGTagName = function(token) { - const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName]; + } - if (adjustedTagName) { - token.tagName = adjustedTagName; + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } } -}; - -//Integration points -function isMathMLTextIntegrationPoint(tn, ns) { - return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT); + } } -function isHtmlIntegrationPoint(tn, ns, attrs) { - if (ns === NS.MATHML && tn === $.ANNOTATION_XML) { - for (let i = 0; i < attrs.length; i++) { - if (attrs[i].name === ATTRS.ENCODING) { - const value = attrs[i].value.toLowerCase(); - - return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML; - } - } - } - - return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE); +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); } -exports.isIntegrationPoint = function(tn, ns, attrs, foreignNS) { - if ((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) { - return true; - } - - if ((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns)) { - return true; - } +var normalize = pathModule.normalize; - return false; -}; +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} -/***/ }), +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); -/***/ 49578: -/***/ ((__unused_webpack_module, exports) => { + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } -"use strict"; + var original = p, + seenLinks = {}, + knownHard = {}; + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -const NS = (exports.NAMESPACES = { - HTML: 'http://www.w3.org/1999/xhtml', - MATHML: 'http://www.w3.org/1998/Math/MathML', - SVG: 'http://www.w3.org/2000/svg', - XLINK: 'http://www.w3.org/1999/xlink', - XML: 'http://www.w3.org/XML/1998/namespace', - XMLNS: 'http://www.w3.org/2000/xmlns/' -}); + start(); -exports.ATTRS = { - TYPE: 'type', - ACTION: 'action', - ENCODING: 'encoding', - PROMPT: 'prompt', - NAME: 'name', - COLOR: 'color', - FACE: 'face', - SIZE: 'size' -}; - -exports.DOCUMENT_MODE = { - NO_QUIRKS: 'no-quirks', - QUIRKS: 'quirks', - LIMITED_QUIRKS: 'limited-quirks' -}; - -const $ = (exports.TAG_NAMES = { - A: 'a', - ADDRESS: 'address', - ANNOTATION_XML: 'annotation-xml', - APPLET: 'applet', - AREA: 'area', - ARTICLE: 'article', - ASIDE: 'aside', - - B: 'b', - BASE: 'base', - BASEFONT: 'basefont', - BGSOUND: 'bgsound', - BIG: 'big', - BLOCKQUOTE: 'blockquote', - BODY: 'body', - BR: 'br', - BUTTON: 'button', - - CAPTION: 'caption', - CENTER: 'center', - CODE: 'code', - COL: 'col', - COLGROUP: 'colgroup', - - DD: 'dd', - DESC: 'desc', - DETAILS: 'details', - DIALOG: 'dialog', - DIR: 'dir', - DIV: 'div', - DL: 'dl', - DT: 'dt', - - EM: 'em', - EMBED: 'embed', - - FIELDSET: 'fieldset', - FIGCAPTION: 'figcaption', - FIGURE: 'figure', - FONT: 'font', - FOOTER: 'footer', - FOREIGN_OBJECT: 'foreignObject', - FORM: 'form', - FRAME: 'frame', - FRAMESET: 'frameset', - - H1: 'h1', - H2: 'h2', - H3: 'h3', - H4: 'h4', - H5: 'h5', - H6: 'h6', - HEAD: 'head', - HEADER: 'header', - HGROUP: 'hgroup', - HR: 'hr', - HTML: 'html', - - I: 'i', - IMG: 'img', - IMAGE: 'image', - INPUT: 'input', - IFRAME: 'iframe', - - KEYGEN: 'keygen', - - LABEL: 'label', - LI: 'li', - LINK: 'link', - LISTING: 'listing', - - MAIN: 'main', - MALIGNMARK: 'malignmark', - MARQUEE: 'marquee', - MATH: 'math', - MENU: 'menu', - META: 'meta', - MGLYPH: 'mglyph', - MI: 'mi', - MO: 'mo', - MN: 'mn', - MS: 'ms', - MTEXT: 'mtext', - - NAV: 'nav', - NOBR: 'nobr', - NOFRAMES: 'noframes', - NOEMBED: 'noembed', - NOSCRIPT: 'noscript', - - OBJECT: 'object', - OL: 'ol', - OPTGROUP: 'optgroup', - OPTION: 'option', - - P: 'p', - PARAM: 'param', - PLAINTEXT: 'plaintext', - PRE: 'pre', - - RB: 'rb', - RP: 'rp', - RT: 'rt', - RTC: 'rtc', - RUBY: 'ruby', - - S: 's', - SCRIPT: 'script', - SECTION: 'section', - SELECT: 'select', - SOURCE: 'source', - SMALL: 'small', - SPAN: 'span', - STRIKE: 'strike', - STRONG: 'strong', - STYLE: 'style', - SUB: 'sub', - SUMMARY: 'summary', - SUP: 'sup', - - TABLE: 'table', - TBODY: 'tbody', - TEMPLATE: 'template', - TEXTAREA: 'textarea', - TFOOT: 'tfoot', - TD: 'td', - TH: 'th', - THEAD: 'thead', - TITLE: 'title', - TR: 'tr', - TRACK: 'track', - TT: 'tt', - - U: 'u', - UL: 'ul', - - SVG: 'svg', - - VAR: 'var', - - WBR: 'wbr', - - XMP: 'xmp' -}); + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; -exports.SPECIAL_ELEMENTS = { - [NS.HTML]: { - [$.ADDRESS]: true, - [$.APPLET]: true, - [$.AREA]: true, - [$.ARTICLE]: true, - [$.ASIDE]: true, - [$.BASE]: true, - [$.BASEFONT]: true, - [$.BGSOUND]: true, - [$.BLOCKQUOTE]: true, - [$.BODY]: true, - [$.BR]: true, - [$.BUTTON]: true, - [$.CAPTION]: true, - [$.CENTER]: true, - [$.COL]: true, - [$.COLGROUP]: true, - [$.DD]: true, - [$.DETAILS]: true, - [$.DIR]: true, - [$.DIV]: true, - [$.DL]: true, - [$.DT]: true, - [$.EMBED]: true, - [$.FIELDSET]: true, - [$.FIGCAPTION]: true, - [$.FIGURE]: true, - [$.FOOTER]: true, - [$.FORM]: true, - [$.FRAME]: true, - [$.FRAMESET]: true, - [$.H1]: true, - [$.H2]: true, - [$.H3]: true, - [$.H4]: true, - [$.H5]: true, - [$.H6]: true, - [$.HEAD]: true, - [$.HEADER]: true, - [$.HGROUP]: true, - [$.HR]: true, - [$.HTML]: true, - [$.IFRAME]: true, - [$.IMG]: true, - [$.INPUT]: true, - [$.LI]: true, - [$.LINK]: true, - [$.LISTING]: true, - [$.MAIN]: true, - [$.MARQUEE]: true, - [$.MENU]: true, - [$.META]: true, - [$.NAV]: true, - [$.NOEMBED]: true, - [$.NOFRAMES]: true, - [$.NOSCRIPT]: true, - [$.OBJECT]: true, - [$.OL]: true, - [$.P]: true, - [$.PARAM]: true, - [$.PLAINTEXT]: true, - [$.PRE]: true, - [$.SCRIPT]: true, - [$.SECTION]: true, - [$.SELECT]: true, - [$.SOURCE]: true, - [$.STYLE]: true, - [$.SUMMARY]: true, - [$.TABLE]: true, - [$.TBODY]: true, - [$.TD]: true, - [$.TEMPLATE]: true, - [$.TEXTAREA]: true, - [$.TFOOT]: true, - [$.TH]: true, - [$.THEAD]: true, - [$.TITLE]: true, - [$.TR]: true, - [$.TRACK]: true, - [$.UL]: true, - [$.WBR]: true, - [$.XMP]: true - }, - [NS.MATHML]: { - [$.MI]: true, - [$.MO]: true, - [$.MN]: true, - [$.MS]: true, - [$.MTEXT]: true, - [$.ANNOTATION_XML]: true - }, - [NS.SVG]: { - [$.TITLE]: true, - [$.FOREIGN_OBJECT]: true, - [$.DESC]: true + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; } -}; + } + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; -/***/ }), + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } -/***/ 4736: -/***/ ((__unused_webpack_module, exports) => { + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } -"use strict"; + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } -const UNDEFINED_CODE_POINTS = [ - 0xfffe, - 0xffff, - 0x1fffe, - 0x1ffff, - 0x2fffe, - 0x2ffff, - 0x3fffe, - 0x3ffff, - 0x4fffe, - 0x4ffff, - 0x5fffe, - 0x5ffff, - 0x6fffe, - 0x6ffff, - 0x7fffe, - 0x7ffff, - 0x8fffe, - 0x8ffff, - 0x9fffe, - 0x9ffff, - 0xafffe, - 0xaffff, - 0xbfffe, - 0xbffff, - 0xcfffe, - 0xcffff, - 0xdfffe, - 0xdffff, - 0xefffe, - 0xeffff, - 0xffffe, - 0xfffff, - 0x10fffe, - 0x10ffff -]; + if (cache) cache[original] = p; -exports.REPLACEMENT_CHARACTER = '\uFFFD'; - -exports.CODE_POINTS = { - EOF: -1, - NULL: 0x00, - TABULATION: 0x09, - CARRIAGE_RETURN: 0x0d, - LINE_FEED: 0x0a, - FORM_FEED: 0x0c, - SPACE: 0x20, - EXCLAMATION_MARK: 0x21, - QUOTATION_MARK: 0x22, - NUMBER_SIGN: 0x23, - AMPERSAND: 0x26, - APOSTROPHE: 0x27, - HYPHEN_MINUS: 0x2d, - SOLIDUS: 0x2f, - DIGIT_0: 0x30, - DIGIT_9: 0x39, - SEMICOLON: 0x3b, - LESS_THAN_SIGN: 0x3c, - EQUALS_SIGN: 0x3d, - GREATER_THAN_SIGN: 0x3e, - QUESTION_MARK: 0x3f, - LATIN_CAPITAL_A: 0x41, - LATIN_CAPITAL_F: 0x46, - LATIN_CAPITAL_X: 0x58, - LATIN_CAPITAL_Z: 0x5a, - RIGHT_SQUARE_BRACKET: 0x5d, - GRAVE_ACCENT: 0x60, - LATIN_SMALL_A: 0x61, - LATIN_SMALL_F: 0x66, - LATIN_SMALL_X: 0x78, - LATIN_SMALL_Z: 0x7a, - REPLACEMENT_CHARACTER: 0xfffd -}; - -exports.CODE_POINT_SEQUENCES = { - DASH_DASH_STRING: [0x2d, 0x2d], //-- - DOCTYPE_STRING: [0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45], //DOCTYPE - CDATA_START_STRING: [0x5b, 0x43, 0x44, 0x41, 0x54, 0x41, 0x5b], //[CDATA[ - SCRIPT_STRING: [0x73, 0x63, 0x72, 0x69, 0x70, 0x74], //script - PUBLIC_STRING: [0x50, 0x55, 0x42, 0x4c, 0x49, 0x43], //PUBLIC - SYSTEM_STRING: [0x53, 0x59, 0x53, 0x54, 0x45, 0x4d] //SYSTEM -}; - -//Surrogates -exports.isSurrogate = function(cp) { - return cp >= 0xd800 && cp <= 0xdfff; -}; - -exports.isSurrogatePair = function(cp) { - return cp >= 0xdc00 && cp <= 0xdfff; -}; - -exports.getSurrogatePairCodePoint = function(cp1, cp2) { - return (cp1 - 0xd800) * 0x400 + 0x2400 + cp2; -}; - -//NOTE: excluding NULL and ASCII whitespace -exports.isControlCodePoint = function(cp) { - return ( - (cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) || - (cp >= 0x7f && cp <= 0x9f) - ); + return p; }; -exports.isUndefinedCodePoint = function(cp) { - return (cp >= 0xfdd0 && cp <= 0xfdef) || UNDEFINED_CODE_POINTS.indexOf(cp) > -1; -}; +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } -/***/ }), + // make p is absolute + p = pathModule.resolve(p); -/***/ 45686: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } -"use strict"; + var original = p, + seenLinks = {}, + knownHard = {}; + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -const Mixin = __nccwpck_require__(2830); + start(); -class ErrorReportingMixinBase extends Mixin { - constructor(host, opts) { - super(host); + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; - this.posTracker = null; - this.onParseError = opts.onParseError; + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); } + } - _setErrorLocation(err) { - err.startLine = err.endLine = this.posTracker.line; - err.startCol = err.endCol = this.posTracker.col; - err.startOffset = err.endOffset = this.posTracker.offset; + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); } - _reportError(code) { - const err = { - code: code, - startLine: -1, - startCol: -1, - startOffset: -1, - endLine: -1, - endCol: -1, - endOffset: -1 - }; + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; - this._setErrorLocation(err); - this.onParseError(err); + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); } - _getOverriddenMethods(mxn) { - return { - _err(code) { - mxn._reportError(code); - } - }; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); } -} - -module.exports = ErrorReportingMixinBase; - - -/***/ }), - -/***/ 60393: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -const ErrorReportingMixinBase = __nccwpck_require__(45686); -const ErrorReportingTokenizerMixin = __nccwpck_require__(14703); -const LocationInfoTokenizerMixin = __nccwpck_require__(29817); -const Mixin = __nccwpck_require__(2830); + return fs.lstat(base, gotStat); + } -class ErrorReportingParserMixin extends ErrorReportingMixinBase { - constructor(parser, opts) { - super(parser, opts); + function gotStat(err, stat) { + if (err) return cb(err); - this.opts = opts; - this.ctLoc = null; - this.locBeforeToken = false; + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); } - _setErrorLocation(err) { - if (this.ctLoc) { - err.startLine = this.ctLoc.startLine; - err.startCol = this.ctLoc.startCol; - err.startOffset = this.ctLoc.startOffset; - - err.endLine = this.locBeforeToken ? this.ctLoc.startLine : this.ctLoc.endLine; - err.endCol = this.locBeforeToken ? this.ctLoc.startCol : this.ctLoc.endCol; - err.endOffset = this.locBeforeToken ? this.ctLoc.startOffset : this.ctLoc.endOffset; - } + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } } + fs.stat(base, function(err) { + if (err) return cb(err); - _getOverriddenMethods(mxn, orig) { - return { - _bootstrap(document, fragmentContext) { - orig._bootstrap.call(this, document, fragmentContext); - - Mixin.install(this.tokenizer, ErrorReportingTokenizerMixin, mxn.opts); - Mixin.install(this.tokenizer, LocationInfoTokenizerMixin); - }, - - _processInputToken(token) { - mxn.ctLoc = token.location; + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } - orig._processInputToken.call(this, token); - }, + function gotTarget(err, target, base) { + if (err) return cb(err); - _err(code, options) { - mxn.locBeforeToken = options && options.beforeToken; - mxn._reportError(code); - } - }; - } -} + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } -module.exports = ErrorReportingParserMixin; + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; /***/ }), -/***/ 96573: +/***/ 64369: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var spin = __nccwpck_require__(25543) +var progressBar = __nccwpck_require__(46834) -const ErrorReportingMixinBase = __nccwpck_require__(45686); -const PositionTrackingPreprocessorMixin = __nccwpck_require__(3127); -const Mixin = __nccwpck_require__(2830); - -class ErrorReportingPreprocessorMixin extends ErrorReportingMixinBase { - constructor(preprocessor, opts) { - super(preprocessor, opts); - - this.posTracker = Mixin.install(preprocessor, PositionTrackingPreprocessorMixin); - this.lastErrOffset = -1; - } - - _reportError(code) { - //NOTE: avoid reporting error twice on advance/retreat - if (this.lastErrOffset !== this.posTracker.offset) { - this.lastErrOffset = this.posTracker.offset; - super._reportError(code); - } - } +module.exports = { + activityIndicator: function (values, theme, width) { + if (values.spun == null) return + return spin(theme, values.spun) + }, + progressbar: function (values, theme, width) { + if (values.completed == null) return + return progressBar(theme, width, values.completed) + } } -module.exports = ErrorReportingPreprocessorMixin; - /***/ }), -/***/ 14703: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 97291: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var util = __nccwpck_require__(31669) -const ErrorReportingMixinBase = __nccwpck_require__(45686); -const ErrorReportingPreprocessorMixin = __nccwpck_require__(96573); -const Mixin = __nccwpck_require__(2830); - -class ErrorReportingTokenizerMixin extends ErrorReportingMixinBase { - constructor(tokenizer, opts) { - super(tokenizer, opts); - - const preprocessorMixin = Mixin.install(tokenizer.preprocessor, ErrorReportingPreprocessorMixin, opts); +var User = exports.User = function User (msg) { + var err = new Error(msg) + Error.captureStackTrace(err, User) + err.code = 'EGAUGE' + return err +} - this.posTracker = preprocessorMixin.posTracker; - } +exports.MissingTemplateValue = function MissingTemplateValue (item, values) { + var err = new User(util.format('Missing template value "%s"', item.type)) + Error.captureStackTrace(err, MissingTemplateValue) + err.template = item + err.values = values + return err } -module.exports = ErrorReportingTokenizerMixin; +exports.Internal = function Internal (msg) { + var err = new Error(msg) + Error.captureStackTrace(err, Internal) + err.code = 'EGAUGEINTERNAL' + return err +} /***/ }), -/***/ 78020: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 95586: +/***/ ((module) => { "use strict"; -const Mixin = __nccwpck_require__(2830); - -class LocationInfoOpenElementStackMixin extends Mixin { - constructor(stack, opts) { - super(stack); - - this.onItemPop = opts.onItemPop; - } - - _getOverriddenMethods(mxn, orig) { - return { - pop() { - mxn.onItemPop(this.current); - orig.pop.call(this); - }, - - popAllUpToHtmlElement() { - for (let i = this.stackTop; i > 0; i--) { - mxn.onItemPop(this.items[i]); - } - - orig.popAllUpToHtmlElement.call(this); - }, +module.exports = isWin32() || isColorTerm() - remove(element) { - mxn.onItemPop(this.current); - orig.remove.call(this, element); - } - }; - } +function isWin32 () { + return process.platform === 'win32' } -module.exports = LocationInfoOpenElementStackMixin; +function isColorTerm () { + var termHasColor = /^screen|^xterm|^vt100|color|ansi|cygwin|linux/i + return !!process.env.COLORTERM || termHasColor.test(process.env.TERM) +} /***/ }), -/***/ 703: +/***/ 51800: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var Plumbing = __nccwpck_require__(17305) +var hasUnicode = __nccwpck_require__(15885) +var hasColor = __nccwpck_require__(95586) +var onExit = __nccwpck_require__(24931) +var defaultThemes = __nccwpck_require__(26605) +var setInterval = __nccwpck_require__(25121) +var process = __nccwpck_require__(19279) +var setImmediate = __nccwpck_require__(16806) -const Mixin = __nccwpck_require__(2830); -const Tokenizer = __nccwpck_require__(66480); -const LocationInfoTokenizerMixin = __nccwpck_require__(29817); -const LocationInfoOpenElementStackMixin = __nccwpck_require__(78020); -const HTML = __nccwpck_require__(49578); - -//Aliases -const $ = HTML.TAG_NAMES; - -class LocationInfoParserMixin extends Mixin { - constructor(parser) { - super(parser); +module.exports = Gauge - this.parser = parser; - this.treeAdapter = this.parser.treeAdapter; - this.posTracker = null; - this.lastStartTagToken = null; - this.lastFosterParentingLocation = null; - this.currentToken = null; - } +function callWith (obj, method) { + return function () { + return method.call(obj) + } +} - _setStartLocation(element) { - let loc = null; - - if (this.lastStartTagToken) { - loc = Object.assign({}, this.lastStartTagToken.location); - loc.startTag = this.lastStartTagToken.location; - } - - this.treeAdapter.setNodeSourceCodeLocation(element, loc); - } - - _setEndLocation(element, closingToken) { - const loc = this.treeAdapter.getNodeSourceCodeLocation(element); - - if (loc) { - if (closingToken.location) { - const ctLoc = closingToken.location; - const tn = this.treeAdapter.getTagName(element); - - // NOTE: For cases like

- First 'p' closes without a closing - // tag and for cases like

- 'p' closes without a closing tag. - const isClosingEndTag = closingToken.type === Tokenizer.END_TAG_TOKEN && tn === closingToken.tagName; - - if (isClosingEndTag) { - loc.endTag = Object.assign({}, ctLoc); - loc.endLine = ctLoc.endLine; - loc.endCol = ctLoc.endCol; - loc.endOffset = ctLoc.endOffset; - } else { - loc.endLine = ctLoc.startLine; - loc.endCol = ctLoc.startCol; - loc.endOffset = ctLoc.startOffset; - } - } - } - } - - _getOverriddenMethods(mxn, orig) { - return { - _bootstrap(document, fragmentContext) { - orig._bootstrap.call(this, document, fragmentContext); - - mxn.lastStartTagToken = null; - mxn.lastFosterParentingLocation = null; - mxn.currentToken = null; - - const tokenizerMixin = Mixin.install(this.tokenizer, LocationInfoTokenizerMixin); - - mxn.posTracker = tokenizerMixin.posTracker; - - Mixin.install(this.openElements, LocationInfoOpenElementStackMixin, { - onItemPop: function(element) { - mxn._setEndLocation(element, mxn.currentToken); - } - }); - }, - - _runParsingLoop(scriptHandler) { - orig._runParsingLoop.call(this, scriptHandler); - - // NOTE: generate location info for elements - // that remains on open element stack - for (let i = this.openElements.stackTop; i >= 0; i--) { - mxn._setEndLocation(this.openElements.items[i], mxn.currentToken); - } - }, - - //Token processing - _processTokenInForeignContent(token) { - mxn.currentToken = token; - orig._processTokenInForeignContent.call(this, token); - }, - - _processToken(token) { - mxn.currentToken = token; - orig._processToken.call(this, token); - - //NOTE: and are never popped from the stack, so we need to updated - //their end location explicitly. - const requireExplicitUpdate = - token.type === Tokenizer.END_TAG_TOKEN && - (token.tagName === $.HTML || (token.tagName === $.BODY && this.openElements.hasInScope($.BODY))); +function Gauge (arg1, arg2) { + var options, writeTo + if (arg1 && arg1.write) { + writeTo = arg1 + options = arg2 || {} + } else if (arg2 && arg2.write) { + writeTo = arg2 + options = arg1 || {} + } else { + writeTo = process.stderr + options = arg1 || arg2 || {} + } - if (requireExplicitUpdate) { - for (let i = this.openElements.stackTop; i >= 0; i--) { - const element = this.openElements.items[i]; + this._status = { + spun: 0, + section: '', + subsection: '' + } + this._paused = false // are we paused for back pressure? + this._disabled = true // are all progress bar updates disabled? + this._showing = false // do we WANT the progress bar on screen + this._onScreen = false // IS the progress bar on screen + this._needsRedraw = false // should we print something at next tick? + this._hideCursor = options.hideCursor == null ? true : options.hideCursor + this._fixedFramerate = options.fixedFramerate == null + ? !(/^v0\.8\./.test(process.version)) + : options.fixedFramerate + this._lastUpdateAt = null + this._updateInterval = options.updateInterval == null ? 50 : options.updateInterval - if (this.treeAdapter.getTagName(element) === token.tagName) { - mxn._setEndLocation(element, token); - break; - } - } - } - }, + this._themes = options.themes || defaultThemes + this._theme = options.theme + var theme = this._computeTheme(options.theme) + var template = options.template || [ + {type: 'progressbar', length: 20}, + {type: 'activityIndicator', kerning: 1, length: 1}, + {type: 'section', kerning: 1, default: ''}, + {type: 'subsection', kerning: 1, default: ''} + ] + this.setWriteTo(writeTo, options.tty) + var PlumbingClass = options.Plumbing || Plumbing + this._gauge = new PlumbingClass(theme, template, this.getWidth()) - //Doctype - _setDocumentType(token) { - orig._setDocumentType.call(this, token); + this._$$doRedraw = callWith(this, this._doRedraw) + this._$$handleSizeChange = callWith(this, this._handleSizeChange) - const documentChildren = this.treeAdapter.getChildNodes(this.document); - const cnLength = documentChildren.length; + this._cleanupOnExit = options.cleanupOnExit == null || options.cleanupOnExit + this._removeOnExit = null - for (let i = 0; i < cnLength; i++) { - const node = documentChildren[i]; + if (options.enabled || (options.enabled == null && this._tty && this._tty.isTTY)) { + this.enable() + } else { + this.disable() + } +} +Gauge.prototype = {} - if (this.treeAdapter.isDocumentTypeNode(node)) { - this.treeAdapter.setNodeSourceCodeLocation(node, token.location); - break; - } - } - }, +Gauge.prototype.isEnabled = function () { + return !this._disabled +} - //Elements - _attachElementToTree(element) { - //NOTE: _attachElementToTree is called from _appendElement, _insertElement and _insertTemplate methods. - //So we will use token location stored in this methods for the element. - mxn._setStartLocation(element); - mxn.lastStartTagToken = null; - orig._attachElementToTree.call(this, element); - }, +Gauge.prototype.setTemplate = function (template) { + this._gauge.setTemplate(template) + if (this._showing) this._requestRedraw() +} - _appendElement(token, namespaceURI) { - mxn.lastStartTagToken = token; - orig._appendElement.call(this, token, namespaceURI); - }, +Gauge.prototype._computeTheme = function (theme) { + if (!theme) theme = {} + if (typeof theme === 'string') { + theme = this._themes.getTheme(theme) + } else if (theme && (Object.keys(theme).length === 0 || theme.hasUnicode != null || theme.hasColor != null)) { + var useUnicode = theme.hasUnicode == null ? hasUnicode() : theme.hasUnicode + var useColor = theme.hasColor == null ? hasColor : theme.hasColor + theme = this._themes.getDefault({hasUnicode: useUnicode, hasColor: useColor, platform: theme.platform}) + } + return theme +} - _insertElement(token, namespaceURI) { - mxn.lastStartTagToken = token; - orig._insertElement.call(this, token, namespaceURI); - }, +Gauge.prototype.setThemeset = function (themes) { + this._themes = themes + this.setTheme(this._theme) +} - _insertTemplate(token) { - mxn.lastStartTagToken = token; - orig._insertTemplate.call(this, token); +Gauge.prototype.setTheme = function (theme) { + this._gauge.setTheme(this._computeTheme(theme)) + if (this._showing) this._requestRedraw() + this._theme = theme +} - const tmplContent = this.treeAdapter.getTemplateContent(this.openElements.current); +Gauge.prototype._requestRedraw = function () { + this._needsRedraw = true + if (!this._fixedFramerate) this._doRedraw() +} - this.treeAdapter.setNodeSourceCodeLocation(tmplContent, null); - }, +Gauge.prototype.getWidth = function () { + return ((this._tty && this._tty.columns) || 80) - 1 +} - _insertFakeRootElement() { - orig._insertFakeRootElement.call(this); - this.treeAdapter.setNodeSourceCodeLocation(this.openElements.current, null); - }, +Gauge.prototype.setWriteTo = function (writeTo, tty) { + var enabled = !this._disabled + if (enabled) this.disable() + this._writeTo = writeTo + this._tty = tty || + (writeTo === process.stderr && process.stdout.isTTY && process.stdout) || + (writeTo.isTTY && writeTo) || + this._tty + if (this._gauge) this._gauge.setWidth(this.getWidth()) + if (enabled) this.enable() +} - //Comments - _appendCommentNode(token, parent) { - orig._appendCommentNode.call(this, token, parent); +Gauge.prototype.enable = function () { + if (!this._disabled) return + this._disabled = false + if (this._tty) this._enableEvents() + if (this._showing) this.show() +} - const children = this.treeAdapter.getChildNodes(parent); - const commentNode = children[children.length - 1]; +Gauge.prototype.disable = function () { + if (this._disabled) return + if (this._showing) { + this._lastUpdateAt = null + this._showing = false + this._doRedraw() + this._showing = true + } + this._disabled = true + if (this._tty) this._disableEvents() +} - this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location); - }, +Gauge.prototype._enableEvents = function () { + if (this._cleanupOnExit) { + this._removeOnExit = onExit(callWith(this, this.disable)) + } + this._tty.on('resize', this._$$handleSizeChange) + if (this._fixedFramerate) { + this.redrawTracker = setInterval(this._$$doRedraw, this._updateInterval) + if (this.redrawTracker.unref) this.redrawTracker.unref() + } +} - //Text - _findFosterParentingLocation() { - //NOTE: store last foster parenting location, so we will be able to find inserted text - //in case of foster parenting - mxn.lastFosterParentingLocation = orig._findFosterParentingLocation.call(this); +Gauge.prototype._disableEvents = function () { + this._tty.removeListener('resize', this._$$handleSizeChange) + if (this._fixedFramerate) clearInterval(this.redrawTracker) + if (this._removeOnExit) this._removeOnExit() +} - return mxn.lastFosterParentingLocation; - }, +Gauge.prototype.hide = function (cb) { + if (this._disabled) return cb && process.nextTick(cb) + if (!this._showing) return cb && process.nextTick(cb) + this._showing = false + this._doRedraw() + cb && setImmediate(cb) +} - _insertCharacters(token) { - orig._insertCharacters.call(this, token); +Gauge.prototype.show = function (section, completed) { + this._showing = true + if (typeof section === 'string') { + this._status.section = section + } else if (typeof section === 'object') { + var sectionKeys = Object.keys(section) + for (var ii = 0; ii < sectionKeys.length; ++ii) { + var key = sectionKeys[ii] + this._status[key] = section[key] + } + } + if (completed != null) this._status.completed = completed + if (this._disabled) return + this._requestRedraw() +} - const hasFosterParent = this._shouldFosterParentOnInsertion(); +Gauge.prototype.pulse = function (subsection) { + this._status.subsection = subsection || '' + this._status.spun ++ + if (this._disabled) return + if (!this._showing) return + this._requestRedraw() +} - const parent = - (hasFosterParent && mxn.lastFosterParentingLocation.parent) || - this.openElements.currentTmplContent || - this.openElements.current; +Gauge.prototype._handleSizeChange = function () { + this._gauge.setWidth(this._tty.columns - 1) + this._requestRedraw() +} - const siblings = this.treeAdapter.getChildNodes(parent); +Gauge.prototype._doRedraw = function () { + if (this._disabled || this._paused) return + if (!this._fixedFramerate) { + var now = Date.now() + if (this._lastUpdateAt && now - this._lastUpdateAt < this._updateInterval) return + this._lastUpdateAt = now + } + if (!this._showing && this._onScreen) { + this._onScreen = false + var result = this._gauge.hide() + if (this._hideCursor) { + result += this._gauge.showCursor() + } + return this._writeTo.write(result) + } + if (!this._showing && !this._onScreen) return + if (this._showing && !this._onScreen) { + this._onScreen = true + this._needsRedraw = true + if (this._hideCursor) { + this._writeTo.write(this._gauge.hideCursor()) + } + } + if (!this._needsRedraw) return + if (!this._writeTo.write(this._gauge.show(this._status))) { + this._paused = true + this._writeTo.on('drain', callWith(this, function () { + this._paused = false + this._doRedraw() + })) + } +} - const textNodeIdx = - hasFosterParent && mxn.lastFosterParentingLocation.beforeElement - ? siblings.indexOf(mxn.lastFosterParentingLocation.beforeElement) - 1 - : siblings.length - 1; - const textNode = siblings[textNodeIdx]; +/***/ }), - //NOTE: if we have location assigned by another token, then just update end position - const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode); +/***/ 85899: +/***/ ((module) => { - if (tnLoc) { - tnLoc.endLine = token.location.endLine; - tnLoc.endCol = token.location.endCol; - tnLoc.endOffset = token.location.endOffset; - } else { - this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location); - } - } - }; - } -} +"use strict"; -module.exports = LocationInfoParserMixin; +module.exports = function () { + return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; +}; /***/ }), -/***/ 29817: +/***/ 41360: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var ansiRegex = __nccwpck_require__(85899)(); -const Mixin = __nccwpck_require__(2830); -const Tokenizer = __nccwpck_require__(66480); -const PositionTrackingPreprocessorMixin = __nccwpck_require__(3127); +module.exports = function (str) { + return typeof str === 'string' ? str.replace(ansiRegex, '') : str; +}; -class LocationInfoTokenizerMixin extends Mixin { - constructor(tokenizer) { - super(tokenizer); - this.tokenizer = tokenizer; - this.posTracker = Mixin.install(tokenizer.preprocessor, PositionTrackingPreprocessorMixin); - this.currentAttrLocation = null; - this.ctLoc = null; - } +/***/ }), - _getCurrentLocation() { - return { - startLine: this.posTracker.line, - startCol: this.posTracker.col, - startOffset: this.posTracker.offset, - endLine: -1, - endCol: -1, - endOffset: -1 - }; - } +/***/ 17305: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _attachCurrentAttrLocationInfo() { - this.currentAttrLocation.endLine = this.posTracker.line; - this.currentAttrLocation.endCol = this.posTracker.col; - this.currentAttrLocation.endOffset = this.posTracker.offset; +"use strict"; - const currentToken = this.tokenizer.currentToken; - const currentAttr = this.tokenizer.currentAttr; +var consoleControl = __nccwpck_require__(73645) +var renderTemplate = __nccwpck_require__(13444) +var validate = __nccwpck_require__(83278) - if (!currentToken.location.attrs) { - currentToken.location.attrs = Object.create(null); - } +var Plumbing = module.exports = function (theme, template, width) { + if (!width) width = 80 + validate('OAN', [theme, template, width]) + this.showing = false + this.theme = theme + this.width = width + this.template = template +} +Plumbing.prototype = {} - currentToken.location.attrs[currentAttr.name] = this.currentAttrLocation; - } +Plumbing.prototype.setTheme = function (theme) { + validate('O', [theme]) + this.theme = theme +} - _getOverriddenMethods(mxn, orig) { - const methods = { - _createStartTagToken() { - orig._createStartTagToken.call(this); - this.currentToken.location = mxn.ctLoc; - }, +Plumbing.prototype.setTemplate = function (template) { + validate('A', [template]) + this.template = template +} - _createEndTagToken() { - orig._createEndTagToken.call(this); - this.currentToken.location = mxn.ctLoc; - }, +Plumbing.prototype.setWidth = function (width) { + validate('N', [width]) + this.width = width +} - _createCommentToken() { - orig._createCommentToken.call(this); - this.currentToken.location = mxn.ctLoc; - }, +Plumbing.prototype.hide = function () { + return consoleControl.gotoSOL() + consoleControl.eraseLine() +} - _createDoctypeToken(initialName) { - orig._createDoctypeToken.call(this, initialName); - this.currentToken.location = mxn.ctLoc; - }, +Plumbing.prototype.hideCursor = consoleControl.hideCursor - _createCharacterToken(type, ch) { - orig._createCharacterToken.call(this, type, ch); - this.currentCharacterToken.location = mxn.ctLoc; - }, +Plumbing.prototype.showCursor = consoleControl.showCursor - _createEOFToken() { - orig._createEOFToken.call(this); - this.currentToken.location = mxn._getCurrentLocation(); - }, +Plumbing.prototype.show = function (status) { + var values = Object.create(this.theme) + for (var key in status) { + values[key] = status[key] + } - _createAttr(attrNameFirstCh) { - orig._createAttr.call(this, attrNameFirstCh); - mxn.currentAttrLocation = mxn._getCurrentLocation(); - }, + return renderTemplate(this.width, this.template, values).trim() + + consoleControl.color('reset') + + consoleControl.eraseLine() + consoleControl.gotoSOL() +} - _leaveAttrName(toState) { - orig._leaveAttrName.call(this, toState); - mxn._attachCurrentAttrLocationInfo(); - }, - _leaveAttrValue(toState) { - orig._leaveAttrValue.call(this, toState); - mxn._attachCurrentAttrLocationInfo(); - }, +/***/ }), - _emitCurrentToken() { - const ctLoc = this.currentToken.location; +/***/ 19279: +/***/ ((module) => { - //NOTE: if we have pending character token make it's end location equal to the - //current token's start location. - if (this.currentCharacterToken) { - this.currentCharacterToken.location.endLine = ctLoc.startLine; - this.currentCharacterToken.location.endCol = ctLoc.startCol; - this.currentCharacterToken.location.endOffset = ctLoc.startOffset; - } +"use strict"; - if (this.currentToken.type === Tokenizer.EOF_TOKEN) { - ctLoc.endLine = ctLoc.startLine; - ctLoc.endCol = ctLoc.startCol; - ctLoc.endOffset = ctLoc.startOffset; - } else { - ctLoc.endLine = mxn.posTracker.line; - ctLoc.endCol = mxn.posTracker.col + 1; - ctLoc.endOffset = mxn.posTracker.offset + 1; - } +// this exists so we can replace it during testing +module.exports = process - orig._emitCurrentToken.call(this); - }, - _emitCurrentCharacterToken() { - const ctLoc = this.currentCharacterToken && this.currentCharacterToken.location; +/***/ }), - //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(), - //then set it's location at the current preprocessor position. - //We don't need to increment preprocessor position, since character token - //emission is always forced by the start of the next character token here. - //So, we already have advanced position. - if (ctLoc && ctLoc.endOffset === -1) { - ctLoc.endLine = mxn.posTracker.line; - ctLoc.endCol = mxn.posTracker.col; - ctLoc.endOffset = mxn.posTracker.offset; - } +/***/ 46834: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - orig._emitCurrentCharacterToken.call(this); - } - }; +"use strict"; - //NOTE: patch initial states for each mode to obtain token start position - Object.keys(Tokenizer.MODE).forEach(modeName => { - const state = Tokenizer.MODE[modeName]; +var validate = __nccwpck_require__(83278) +var renderTemplate = __nccwpck_require__(13444) +var wideTruncate = __nccwpck_require__(8413) +var stringWidth = __nccwpck_require__(42577) - methods[state] = function(cp) { - mxn.ctLoc = mxn._getCurrentLocation(); - orig[state].call(this, cp); - }; - }); +module.exports = function (theme, width, completed) { + validate('ONN', [theme, width, completed]) + if (completed < 0) completed = 0 + if (completed > 1) completed = 1 + if (width <= 0) return '' + var sofar = Math.round(width * completed) + var rest = width - sofar + var template = [ + {type: 'complete', value: repeat(theme.complete, sofar), length: sofar}, + {type: 'remaining', value: repeat(theme.remaining, rest), length: rest} + ] + return renderTemplate(width, template, theme) +} - return methods; +// lodash's way of repeating +function repeat (string, width) { + var result = '' + var n = width + do { + if (n % 2) { + result += string } -} + n = Math.floor(n / 2) + /*eslint no-self-assign: 0*/ + string += string + } while (n && stringWidth(result) < width) -module.exports = LocationInfoTokenizerMixin; + return wideTruncate(result, width) +} /***/ }), -/***/ 3127: +/***/ 13444: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var align = __nccwpck_require__(28034) +var validate = __nccwpck_require__(83278) +var objectAssign = __nccwpck_require__(17426) +var wideTruncate = __nccwpck_require__(8413) +var error = __nccwpck_require__(97291) +var TemplateItem = __nccwpck_require__(52131) + +function renderValueWithValues (values) { + return function (item) { + return renderValue(item, values) + } +} + +var renderTemplate = module.exports = function (width, template, values) { + var items = prepareItems(width, template, values) + var rendered = items.map(renderValueWithValues(values)).join('') + return align.left(wideTruncate(rendered, width), width) +} + +function preType (item) { + var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1) + return 'pre' + cappedTypeName +} -const Mixin = __nccwpck_require__(2830); +function postType (item) { + var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1) + return 'post' + cappedTypeName +} -class PositionTrackingPreprocessorMixin extends Mixin { - constructor(preprocessor) { - super(preprocessor); +function hasPreOrPost (item, values) { + if (!item.type) return + return values[preType(item)] || values[postType(item)] +} - this.preprocessor = preprocessor; - this.isEol = false; - this.lineStartPos = 0; - this.droppedBufferSize = 0; +function generatePreAndPost (baseItem, parentValues) { + var item = objectAssign({}, baseItem) + var values = Object.create(parentValues) + var template = [] + var pre = preType(item) + var post = postType(item) + if (values[pre]) { + template.push({value: values[pre]}) + values[pre] = null + } + item.minLength = null + item.length = null + item.maxLength = null + template.push(item) + values[item.type] = values[item.type] + if (values[post]) { + template.push({value: values[post]}) + values[post] = null + } + return function ($1, $2, length) { + return renderTemplate(length, template, values) + } +} - this.offset = 0; - this.col = 0; - this.line = 1; +function prepareItems (width, template, values) { + function cloneAndObjectify (item, index, arr) { + var cloned = new TemplateItem(item, width) + var type = cloned.type + if (cloned.value == null) { + if (!(type in values)) { + if (cloned.default == null) { + throw new error.MissingTemplateValue(cloned, values) + } else { + cloned.value = cloned.default + } + } else { + cloned.value = values[type] + } } + if (cloned.value == null || cloned.value === '') return null + cloned.index = index + cloned.first = index === 0 + cloned.last = index === arr.length - 1 + if (hasPreOrPost(cloned, values)) cloned.value = generatePreAndPost(cloned, values) + return cloned + } - _getOverriddenMethods(mxn, orig) { - return { - advance() { - const pos = this.pos + 1; - const ch = this.html[pos]; + var output = template.map(cloneAndObjectify).filter(function (item) { return item != null }) - //NOTE: LF should be in the last column of the line - if (mxn.isEol) { - mxn.isEol = false; - mxn.line++; - mxn.lineStartPos = pos; - } + var outputLength = 0 + var remainingSpace = width + var variableCount = output.length - if (ch === '\n' || (ch === '\r' && this.html[pos + 1] !== '\n')) { - mxn.isEol = true; - } + function consumeSpace (length) { + if (length > remainingSpace) length = remainingSpace + outputLength += length + remainingSpace -= length + } - mxn.col = pos - mxn.lineStartPos + 1; - mxn.offset = mxn.droppedBufferSize + pos; + function finishSizing (item, length) { + if (item.finished) throw new error.Internal('Tried to finish template item that was already finished') + if (length === Infinity) throw new error.Internal('Length of template item cannot be infinity') + if (length != null) item.length = length + item.minLength = null + item.maxLength = null + --variableCount + item.finished = true + if (item.length == null) item.length = item.getBaseLength() + if (item.length == null) throw new error.Internal('Finished template items must have a length') + consumeSpace(item.getLength()) + } - return orig.advance.call(this); - }, + output.forEach(function (item) { + if (!item.kerning) return + var prevPadRight = item.first ? 0 : output[item.index - 1].padRight + if (!item.first && prevPadRight < item.kerning) item.padLeft = item.kerning - prevPadRight + if (!item.last) item.padRight = item.kerning + }) - retreat() { - orig.retreat.call(this); + // Finish any that have a fixed (literal or intuited) length + output.forEach(function (item) { + if (item.getBaseLength() == null) return + finishSizing(item) + }) - mxn.isEol = false; - mxn.col = this.pos - mxn.lineStartPos + 1; - }, + var resized = 0 + var resizing + var hunkSize + do { + resizing = false + hunkSize = Math.round(remainingSpace / variableCount) + output.forEach(function (item) { + if (item.finished) return + if (!item.maxLength) return + if (item.getMaxLength() < hunkSize) { + finishSizing(item, item.maxLength) + resizing = true + } + }) + } while (resizing && resized++ < output.length) + if (resizing) throw new error.Internal('Resize loop iterated too many times while determining maxLength') - dropParsedChunk() { - const prevPos = this.pos; + resized = 0 + do { + resizing = false + hunkSize = Math.round(remainingSpace / variableCount) + output.forEach(function (item) { + if (item.finished) return + if (!item.minLength) return + if (item.getMinLength() >= hunkSize) { + finishSizing(item, item.minLength) + resizing = true + } + }) + } while (resizing && resized++ < output.length) + if (resizing) throw new error.Internal('Resize loop iterated too many times while determining minLength') - orig.dropParsedChunk.call(this); + hunkSize = Math.round(remainingSpace / variableCount) + output.forEach(function (item) { + if (item.finished) return + finishSizing(item, hunkSize) + }) - const reduction = prevPos - this.pos; + return output +} - mxn.lineStartPos -= reduction; - mxn.droppedBufferSize += reduction; - mxn.offset = mxn.droppedBufferSize + this.pos; - } - }; - } +function renderFunction (item, values, length) { + validate('OON', arguments) + if (item.type) { + return item.value(values, values[item.type + 'Theme'] || {}, length) + } else { + return item.value(values, {}, length) + } } -module.exports = PositionTrackingPreprocessorMixin; +function renderValue (item, values) { + var length = item.getBaseLength() + var value = typeof item.value === 'function' ? renderFunction(item, values, length) : item.value + if (value == null || value === '') return '' + var alignWith = align[item.align] || align.left + var leftPadding = item.padLeft ? align.left('', item.padLeft) : '' + var rightPadding = item.padRight ? align.right('', item.padRight) : '' + var truncated = wideTruncate(String(value), length) + var aligned = alignWith(truncated, length) + return leftPadding + aligned + rightPadding +} /***/ }), -/***/ 88933: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 16806: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var process = __nccwpck_require__(19279) +try { + module.exports = setImmediate +} catch (ex) { + module.exports = process.nextTick +} -const Parser = __nccwpck_require__(66225); -const Serializer = __nccwpck_require__(14786); - -// Shorthands -exports.parse = function parse(html, options) { - const parser = new Parser(options); - - return parser.parse(html); -}; - -exports.parseFragment = function parseFragment(fragmentContext, html, options) { - if (typeof fragmentContext === 'string') { - options = html; - html = fragmentContext; - fragmentContext = null; - } - const parser = new Parser(options); +/***/ }), - return parser.parseFragment(html, fragmentContext); -}; +/***/ 25121: +/***/ ((module) => { -exports.serialize = function(node, options) { - const serializer = new Serializer(node, options); +"use strict"; - return serializer.serialize(); -}; +// this exists so we can replace it during testing +module.exports = setInterval /***/ }), -/***/ 9545: +/***/ 25543: /***/ ((module) => { "use strict"; -//Const -const NOAH_ARK_CAPACITY = 3; - -//List of formatting elements -class FormattingElementList { - constructor(treeAdapter) { - this.length = 0; - this.entries = []; - this.treeAdapter = treeAdapter; - this.bookmark = null; - } - - //Noah Ark's condition - //OPTIMIZATION: at first we try to find possible candidates for exclusion using - //lightweight heuristics without thorough attributes check. - _getNoahArkConditionCandidates(newElement) { - const candidates = []; - - if (this.length >= NOAH_ARK_CAPACITY) { - const neAttrsLength = this.treeAdapter.getAttrList(newElement).length; - const neTagName = this.treeAdapter.getTagName(newElement); - const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement); +module.exports = function spin (spinstr, spun) { + return spinstr[spun % spinstr.length] +} - for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; - if (entry.type === FormattingElementList.MARKER_ENTRY) { - break; - } +/***/ }), - const element = entry.element; - const elementAttrs = this.treeAdapter.getAttrList(element); +/***/ 52131: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const isCandidate = - this.treeAdapter.getTagName(element) === neTagName && - this.treeAdapter.getNamespaceURI(element) === neNamespaceURI && - elementAttrs.length === neAttrsLength; +"use strict"; - if (isCandidate) { - candidates.push({ idx: i, attrs: elementAttrs }); - } - } - } +var stringWidth = __nccwpck_require__(42577) - return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates; - } +module.exports = TemplateItem - _ensureNoahArkCondition(newElement) { - const candidates = this._getNoahArkConditionCandidates(newElement); - let cLength = candidates.length; +function isPercent (num) { + if (typeof num !== 'string') return false + return num.slice(-1) === '%' +} - if (cLength) { - const neAttrs = this.treeAdapter.getAttrList(newElement); - const neAttrsLength = neAttrs.length; - const neAttrsMap = Object.create(null); +function percent (num) { + return Number(num.slice(0, -1)) / 100 +} - //NOTE: build attrs map for the new element so we can perform fast lookups - for (let i = 0; i < neAttrsLength; i++) { - const neAttr = neAttrs[i]; +function TemplateItem (values, outputLength) { + this.overallOutputLength = outputLength + this.finished = false + this.type = null + this.value = null + this.length = null + this.maxLength = null + this.minLength = null + this.kerning = null + this.align = 'left' + this.padLeft = 0 + this.padRight = 0 + this.index = null + this.first = null + this.last = null + if (typeof values === 'string') { + this.value = values + } else { + for (var prop in values) this[prop] = values[prop] + } + // Realize percents + if (isPercent(this.length)) { + this.length = Math.round(this.overallOutputLength * percent(this.length)) + } + if (isPercent(this.minLength)) { + this.minLength = Math.round(this.overallOutputLength * percent(this.minLength)) + } + if (isPercent(this.maxLength)) { + this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength)) + } + return this +} - neAttrsMap[neAttr.name] = neAttr.value; - } +TemplateItem.prototype = {} - for (let i = 0; i < neAttrsLength; i++) { - for (let j = 0; j < cLength; j++) { - const cAttr = candidates[j].attrs[i]; +TemplateItem.prototype.getBaseLength = function () { + var length = this.length + if (length == null && typeof this.value === 'string' && this.maxLength == null && this.minLength == null) { + length = stringWidth(this.value) + } + return length +} - if (neAttrsMap[cAttr.name] !== cAttr.value) { - candidates.splice(j, 1); - cLength--; - } +TemplateItem.prototype.getLength = function () { + var length = this.getBaseLength() + if (length == null) return null + return length + this.padLeft + this.padRight +} - if (candidates.length < NOAH_ARK_CAPACITY) { - return; - } - } - } +TemplateItem.prototype.getMaxLength = function () { + if (this.maxLength == null) return null + return this.maxLength + this.padLeft + this.padRight +} - //NOTE: remove bottommost candidates until Noah's Ark condition will not be met - for (let i = cLength - 1; i >= NOAH_ARK_CAPACITY - 1; i--) { - this.entries.splice(candidates[i].idx, 1); - this.length--; - } - } - } +TemplateItem.prototype.getMinLength = function () { + if (this.minLength == null) return null + return this.minLength + this.padLeft + this.padRight +} - //Mutations - insertMarker() { - this.entries.push({ type: FormattingElementList.MARKER_ENTRY }); - this.length++; - } - pushElement(element, token) { - this._ensureNoahArkCondition(element); - this.entries.push({ - type: FormattingElementList.ELEMENT_ENTRY, - element: element, - token: token - }); +/***/ }), - this.length++; - } +/***/ 51519: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - insertElementAfterBookmark(element, token) { - let bookmarkIdx = this.length - 1; +"use strict"; - for (; bookmarkIdx >= 0; bookmarkIdx--) { - if (this.entries[bookmarkIdx] === this.bookmark) { - break; - } - } +var objectAssign = __nccwpck_require__(17426) - this.entries.splice(bookmarkIdx + 1, 0, { - type: FormattingElementList.ELEMENT_ENTRY, - element: element, - token: token - }); +module.exports = function () { + return ThemeSetProto.newThemeSet() +} - this.length++; - } +var ThemeSetProto = {} - removeEntry(entry) { - for (let i = this.length - 1; i >= 0; i--) { - if (this.entries[i] === entry) { - this.entries.splice(i, 1); - this.length--; - break; - } - } - } +ThemeSetProto.baseTheme = __nccwpck_require__(64369) - clearToLastMarker() { - while (this.length) { - const entry = this.entries.pop(); +ThemeSetProto.newTheme = function (parent, theme) { + if (!theme) { + theme = parent + parent = this.baseTheme + } + return objectAssign({}, parent, theme) +} - this.length--; +ThemeSetProto.getThemeNames = function () { + return Object.keys(this.themes) +} - if (entry.type === FormattingElementList.MARKER_ENTRY) { - break; - } - } - } +ThemeSetProto.addTheme = function (name, parent, theme) { + this.themes[name] = this.newTheme(parent, theme) +} - //Search - getElementEntryInScopeWithTagName(tagName) { - for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; +ThemeSetProto.addToAllThemes = function (theme) { + var themes = this.themes + Object.keys(themes).forEach(function (name) { + objectAssign(themes[name], theme) + }) + objectAssign(this.baseTheme, theme) +} - if (entry.type === FormattingElementList.MARKER_ENTRY) { - return null; - } +ThemeSetProto.getTheme = function (name) { + if (!this.themes[name]) throw this.newMissingThemeError(name) + return this.themes[name] +} - if (this.treeAdapter.getTagName(entry.element) === tagName) { - return entry; - } - } +ThemeSetProto.setDefault = function (opts, name) { + if (name == null) { + name = opts + opts = {} + } + var platform = opts.platform == null ? 'fallback' : opts.platform + var hasUnicode = !!opts.hasUnicode + var hasColor = !!opts.hasColor + if (!this.defaults[platform]) this.defaults[platform] = {true: {}, false: {}} + this.defaults[platform][hasUnicode][hasColor] = name +} - return null; +ThemeSetProto.getDefault = function (opts) { + if (!opts) opts = {} + var platformName = opts.platform || process.platform + var platform = this.defaults[platformName] || this.defaults.fallback + var hasUnicode = !!opts.hasUnicode + var hasColor = !!opts.hasColor + if (!platform) throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor) + if (!platform[hasUnicode][hasColor]) { + if (hasUnicode && hasColor && platform[!hasUnicode][hasColor]) { + hasUnicode = false + } else if (hasUnicode && hasColor && platform[hasUnicode][!hasColor]) { + hasColor = false + } else if (hasUnicode && hasColor && platform[!hasUnicode][!hasColor]) { + hasUnicode = false + hasColor = false + } else if (hasUnicode && !hasColor && platform[!hasUnicode][hasColor]) { + hasUnicode = false + } else if (!hasUnicode && hasColor && platform[hasUnicode][!hasColor]) { + hasColor = false + } else if (platform === this.defaults.fallback) { + throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor) } + } + if (platform[hasUnicode][hasColor]) { + return this.getTheme(platform[hasUnicode][hasColor]) + } else { + return this.getDefault(objectAssign({}, opts, {platform: 'fallback'})) + } +} - getElementEntry(element) { - for (let i = this.length - 1; i >= 0; i--) { - const entry = this.entries[i]; - - if (entry.type === FormattingElementList.ELEMENT_ENTRY && entry.element === element) { - return entry; - } - } +ThemeSetProto.newMissingThemeError = function newMissingThemeError (name) { + var err = new Error('Could not find a gauge theme named "' + name + '"') + Error.captureStackTrace.call(err, newMissingThemeError) + err.theme = name + err.code = 'EMISSINGTHEME' + return err +} - return null; - } +ThemeSetProto.newMissingDefaultThemeError = function newMissingDefaultThemeError (platformName, hasUnicode, hasColor) { + var err = new Error( + 'Could not find a gauge theme for your platform/unicode/color use combo:\n' + + ' platform = ' + platformName + '\n' + + ' hasUnicode = ' + hasUnicode + '\n' + + ' hasColor = ' + hasColor) + Error.captureStackTrace.call(err, newMissingDefaultThemeError) + err.platform = platformName + err.hasUnicode = hasUnicode + err.hasColor = hasColor + err.code = 'EMISSINGTHEME' + return err } -//Entry types -FormattingElementList.MARKER_ENTRY = 'MARKER_ENTRY'; -FormattingElementList.ELEMENT_ENTRY = 'ELEMENT_ENTRY'; +ThemeSetProto.newThemeSet = function () { + var themeset = function (opts) { + return themeset.getDefault(opts) + } + return objectAssign(themeset, ThemeSetProto, { + themes: objectAssign({}, this.themes), + baseTheme: objectAssign({}, this.baseTheme), + defaults: JSON.parse(JSON.stringify(this.defaults || {})) + }) +} -module.exports = FormattingElementList; /***/ }), -/***/ 66225: +/***/ 26605: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var consoleControl = __nccwpck_require__(73645) +var ThemeSet = __nccwpck_require__(51519) -const Tokenizer = __nccwpck_require__(66480); -const OpenElementStack = __nccwpck_require__(31827); -const FormattingElementList = __nccwpck_require__(9545); -const LocationInfoParserMixin = __nccwpck_require__(703); -const ErrorReportingParserMixin = __nccwpck_require__(60393); -const Mixin = __nccwpck_require__(2830); -const defaultTreeAdapter = __nccwpck_require__(37269); -const mergeOptions = __nccwpck_require__(57382); -const doctype = __nccwpck_require__(94281); -const foreignContent = __nccwpck_require__(24320); -const ERR = __nccwpck_require__(65510); -const unicode = __nccwpck_require__(4736); -const HTML = __nccwpck_require__(49578); - -//Aliases -const $ = HTML.TAG_NAMES; -const NS = HTML.NAMESPACES; -const ATTRS = HTML.ATTRS; - -const DEFAULT_OPTIONS = { - scriptingEnabled: true, - sourceCodeLocationInfo: false, - onParseError: null, - treeAdapter: defaultTreeAdapter -}; - -//Misc constants -const HIDDEN_INPUT_TYPE = 'hidden'; - -//Adoption agency loops iteration count -const AA_OUTER_LOOP_ITER = 8; -const AA_INNER_LOOP_ITER = 3; - -//Insertion modes -const INITIAL_MODE = 'INITIAL_MODE'; -const BEFORE_HTML_MODE = 'BEFORE_HTML_MODE'; -const BEFORE_HEAD_MODE = 'BEFORE_HEAD_MODE'; -const IN_HEAD_MODE = 'IN_HEAD_MODE'; -const IN_HEAD_NO_SCRIPT_MODE = 'IN_HEAD_NO_SCRIPT_MODE'; -const AFTER_HEAD_MODE = 'AFTER_HEAD_MODE'; -const IN_BODY_MODE = 'IN_BODY_MODE'; -const TEXT_MODE = 'TEXT_MODE'; -const IN_TABLE_MODE = 'IN_TABLE_MODE'; -const IN_TABLE_TEXT_MODE = 'IN_TABLE_TEXT_MODE'; -const IN_CAPTION_MODE = 'IN_CAPTION_MODE'; -const IN_COLUMN_GROUP_MODE = 'IN_COLUMN_GROUP_MODE'; -const IN_TABLE_BODY_MODE = 'IN_TABLE_BODY_MODE'; -const IN_ROW_MODE = 'IN_ROW_MODE'; -const IN_CELL_MODE = 'IN_CELL_MODE'; -const IN_SELECT_MODE = 'IN_SELECT_MODE'; -const IN_SELECT_IN_TABLE_MODE = 'IN_SELECT_IN_TABLE_MODE'; -const IN_TEMPLATE_MODE = 'IN_TEMPLATE_MODE'; -const AFTER_BODY_MODE = 'AFTER_BODY_MODE'; -const IN_FRAMESET_MODE = 'IN_FRAMESET_MODE'; -const AFTER_FRAMESET_MODE = 'AFTER_FRAMESET_MODE'; -const AFTER_AFTER_BODY_MODE = 'AFTER_AFTER_BODY_MODE'; -const AFTER_AFTER_FRAMESET_MODE = 'AFTER_AFTER_FRAMESET_MODE'; - -//Insertion mode reset map -const INSERTION_MODE_RESET_MAP = { - [$.TR]: IN_ROW_MODE, - [$.TBODY]: IN_TABLE_BODY_MODE, - [$.THEAD]: IN_TABLE_BODY_MODE, - [$.TFOOT]: IN_TABLE_BODY_MODE, - [$.CAPTION]: IN_CAPTION_MODE, - [$.COLGROUP]: IN_COLUMN_GROUP_MODE, - [$.TABLE]: IN_TABLE_MODE, - [$.BODY]: IN_BODY_MODE, - [$.FRAMESET]: IN_FRAMESET_MODE -}; - -//Template insertion mode switch map -const TEMPLATE_INSERTION_MODE_SWITCH_MAP = { - [$.CAPTION]: IN_TABLE_MODE, - [$.COLGROUP]: IN_TABLE_MODE, - [$.TBODY]: IN_TABLE_MODE, - [$.TFOOT]: IN_TABLE_MODE, - [$.THEAD]: IN_TABLE_MODE, - [$.COL]: IN_COLUMN_GROUP_MODE, - [$.TR]: IN_TABLE_BODY_MODE, - [$.TD]: IN_ROW_MODE, - [$.TH]: IN_ROW_MODE -}; - -//Token handlers map for insertion modes -const TOKEN_HANDLERS = { - [INITIAL_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInInitialMode, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInInitialMode, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: doctypeInInitialMode, - [Tokenizer.START_TAG_TOKEN]: tokenInInitialMode, - [Tokenizer.END_TAG_TOKEN]: tokenInInitialMode, - [Tokenizer.EOF_TOKEN]: tokenInInitialMode - }, - [BEFORE_HTML_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHtml, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHtml, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagBeforeHtml, - [Tokenizer.END_TAG_TOKEN]: endTagBeforeHtml, - [Tokenizer.EOF_TOKEN]: tokenBeforeHtml - }, - [BEFORE_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagBeforeHead, - [Tokenizer.END_TAG_TOKEN]: endTagBeforeHead, - [Tokenizer.EOF_TOKEN]: tokenBeforeHead - }, - [IN_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagInHead, - [Tokenizer.END_TAG_TOKEN]: endTagInHead, - [Tokenizer.EOF_TOKEN]: tokenInHead - }, - [IN_HEAD_NO_SCRIPT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInHeadNoScript, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHeadNoScript, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagInHeadNoScript, - [Tokenizer.END_TAG_TOKEN]: endTagInHeadNoScript, - [Tokenizer.EOF_TOKEN]: tokenInHeadNoScript - }, - [AFTER_HEAD_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterHead, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterHead, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype, - [Tokenizer.START_TAG_TOKEN]: startTagAfterHead, - [Tokenizer.END_TAG_TOKEN]: endTagAfterHead, - [Tokenizer.EOF_TOKEN]: tokenAfterHead - }, - [IN_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInBody, - [Tokenizer.END_TAG_TOKEN]: endTagInBody, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [TEXT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: ignoreToken, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: ignoreToken, - [Tokenizer.END_TAG_TOKEN]: endTagInText, - [Tokenizer.EOF_TOKEN]: eofInText - }, - [IN_TABLE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTable, - [Tokenizer.END_TAG_TOKEN]: endTagInTable, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TABLE_TEXT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTableText, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInTableText, - [Tokenizer.COMMENT_TOKEN]: tokenInTableText, - [Tokenizer.DOCTYPE_TOKEN]: tokenInTableText, - [Tokenizer.START_TAG_TOKEN]: tokenInTableText, - [Tokenizer.END_TAG_TOKEN]: tokenInTableText, - [Tokenizer.EOF_TOKEN]: tokenInTableText - }, - [IN_CAPTION_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInCaption, - [Tokenizer.END_TAG_TOKEN]: endTagInCaption, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_COLUMN_GROUP_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenInColumnGroup, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInColumnGroup, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInColumnGroup, - [Tokenizer.END_TAG_TOKEN]: endTagInColumnGroup, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TABLE_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTableBody, - [Tokenizer.END_TAG_TOKEN]: endTagInTableBody, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_ROW_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInTable, - [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInRow, - [Tokenizer.END_TAG_TOKEN]: endTagInRow, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_CELL_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInCell, - [Tokenizer.END_TAG_TOKEN]: endTagInCell, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_SELECT_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInSelect, - [Tokenizer.END_TAG_TOKEN]: endTagInSelect, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_SELECT_IN_TABLE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInSelectInTable, - [Tokenizer.END_TAG_TOKEN]: endTagInSelectInTable, - [Tokenizer.EOF_TOKEN]: eofInBody - }, - [IN_TEMPLATE_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: characterInBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInTemplate, - [Tokenizer.END_TAG_TOKEN]: endTagInTemplate, - [Tokenizer.EOF_TOKEN]: eofInTemplate - }, - [AFTER_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterBody, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToRootHtmlElement, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterBody, - [Tokenizer.END_TAG_TOKEN]: endTagAfterBody, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [IN_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagInFrameset, - [Tokenizer.END_TAG_TOKEN]: endTagInFrameset, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [AFTER_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters, - [Tokenizer.COMMENT_TOKEN]: appendComment, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterFrameset, - [Tokenizer.END_TAG_TOKEN]: endTagAfterFrameset, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [AFTER_AFTER_BODY_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: tokenAfterAfterBody, - [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterAfterBody, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterBody, - [Tokenizer.END_TAG_TOKEN]: tokenAfterAfterBody, - [Tokenizer.EOF_TOKEN]: stopParsing - }, - [AFTER_AFTER_FRAMESET_MODE]: { - [Tokenizer.CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken, - [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody, - [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument, - [Tokenizer.DOCTYPE_TOKEN]: ignoreToken, - [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterFrameset, - [Tokenizer.END_TAG_TOKEN]: ignoreToken, - [Tokenizer.EOF_TOKEN]: stopParsing - } -}; - -//Parser -class Parser { - constructor(options) { - this.options = mergeOptions(DEFAULT_OPTIONS, options); - - this.treeAdapter = this.options.treeAdapter; - this.pendingScript = null; - - if (this.options.sourceCodeLocationInfo) { - Mixin.install(this, LocationInfoParserMixin); - } - - if (this.options.onParseError) { - Mixin.install(this, ErrorReportingParserMixin, { onParseError: this.options.onParseError }); - } - } - - // API - parse(html) { - const document = this.treeAdapter.createDocument(); +var themes = module.exports = new ThemeSet() - this._bootstrap(document, null); - this.tokenizer.write(html, true); - this._runParsingLoop(null); +themes.addTheme('ASCII', { + preProgressbar: '[', + postProgressbar: ']', + progressbarTheme: { + complete: '#', + remaining: '.' + }, + activityIndicatorTheme: '-\\|/', + preSubsection: '>' +}) - return document; - } +themes.addTheme('colorASCII', themes.getTheme('ASCII'), { + progressbarTheme: { + preComplete: consoleControl.color('inverse'), + complete: ' ', + postComplete: consoleControl.color('stopInverse'), + preRemaining: consoleControl.color('brightBlack'), + remaining: '.', + postRemaining: consoleControl.color('reset') + } +}) - parseFragment(html, fragmentContext) { - //NOTE: use