diff --git a/action.yml b/action.yml index b93b311..0416e9f 100644 --- a/action.yml +++ b/action.yml @@ -34,7 +34,7 @@ outputs: delta_bytes: # size of changed data description: The overall number of bytes changed in the output data this run (current size - previous size) runs: - using: 'node12' + using: 'node16' main: 'dist/index.js' post: 'dist/post/index.js' branding: diff --git a/dist/LICENSE b/dist/LICENSE index 9915c7f..99beac1 100644 --- a/dist/LICENSE +++ b/dist/LICENSE @@ -15,15 +15,6 @@ MIT @actions/io MIT -The MIT License (MIT) - -Copyright 2019 GitHub - -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. @azure/ms-rest-azure-env MIT @@ -100,6 +91,37 @@ MIT SOFTWARE +@mapbox/node-pre-gyp +BSD-3-Clause +Copyright (c), Mapbox + +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 node-pre-gyp 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. + + @vercel/ncc MIT Copyright 2018 ZEIT, Inc. @@ -393,27 +415,15 @@ SOFTWARE. ansi-regex 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. ansi-styles @@ -474,11 +484,24 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. are-we-there-yet ISC -Copyright (c) 2015, Rebecca Turner +ISC License -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. +Copyright npm, Inc. -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. +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 NPM DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO +EVENT SHALL NPM 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 @@ -902,31 +925,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 @@ -963,6 +961,25 @@ 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. +color-support +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. + + combined-stream MIT Copyright (c) 2011 Debuggable Limited @@ -1103,21 +1120,22 @@ debug MIT (The MIT License) -Copyright (c) 2014 TJ Holowaychuk +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon -Permission is hereby granted, free of charge, to any person obtaining a copy of this software -and associated documentation files (the 'Software'), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +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 +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 +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. @@ -1656,6 +1674,30 @@ 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) @@ -2130,27 +2172,15 @@ PERFORMANCE OF THIS SOFTWARE. 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-typedarray @@ -2553,6 +2583,25 @@ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TOR ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +lru-cache +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. + + mime-db MIT @@ -2750,37 +2799,6 @@ SOFTWARE. -node-pre-gyp -BSD-3-Clause -Copyright (c), Mapbox - -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 node-pre-gyp 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. - - nopt ISC The ISC License @@ -2819,31 +2837,6 @@ 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) - -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. - - oauth-sign Apache-2.0 Apache License @@ -2946,75 +2939,6 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -os-homedir -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. - - -os-tmpdir -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. - - -osenv -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. - - parse5 MIT Copyright (c) 2013-2019 Ivan Nikulin (ifaaan@gmail.com, https://github.com/inikulin) @@ -3100,7 +3024,7 @@ pg MIT MIT License -Copyright (c) 2010 - 2021 Brian Carlson +Copyright (c) 2010 - 2020 Brian Carlson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -3191,7 +3115,7 @@ pg-protocol MIT MIT License -Copyright (c) 2010 - 2021 Brian Carlson +Copyright (c) 2010 - 2020 Brian Carlson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -3897,27 +3821,15 @@ 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 @@ -3974,27 +3886,15 @@ IN THE SOFTWARE. strip-ansi 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. supports-color @@ -4447,6 +4347,25 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +yallist +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. + + zod MIT MIT License diff --git a/dist/index.js b/dist/index.js index 744a241..252724b 100644 --- a/dist/index.js +++ b/dist/index.js @@ -2,6 +2,22 @@ require('./sourcemap-register.js');module.exports = /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ +/***/ 41427: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"0.1.14\":{\"node_abi\":null,\"v8\":\"1.3\"},\"0.1.15\":{\"node_abi\":null,\"v8\":\"1.3\"},\"0.1.16\":{\"node_abi\":null,\"v8\":\"1.3\"},\"0.1.17\":{\"node_abi\":null,\"v8\":\"1.3\"},\"0.1.18\":{\"node_abi\":null,\"v8\":\"1.3\"},\"0.1.19\":{\"node_abi\":null,\"v8\":\"2.0\"},\"0.1.20\":{\"node_abi\":null,\"v8\":\"2.0\"},\"0.1.21\":{\"node_abi\":null,\"v8\":\"2.0\"},\"0.1.22\":{\"node_abi\":null,\"v8\":\"2.0\"},\"0.1.23\":{\"node_abi\":null,\"v8\":\"2.0\"},\"0.1.24\":{\"node_abi\":null,\"v8\":\"2.0\"},\"0.1.25\":{\"node_abi\":null,\"v8\":\"2.0\"},\"0.1.26\":{\"node_abi\":null,\"v8\":\"2.0\"},\"0.1.27\":{\"node_abi\":null,\"v8\":\"2.1\"},\"0.1.28\":{\"node_abi\":null,\"v8\":\"2.1\"},\"0.1.29\":{\"node_abi\":null,\"v8\":\"2.1\"},\"0.1.30\":{\"node_abi\":null,\"v8\":\"2.1\"},\"0.1.31\":{\"node_abi\":null,\"v8\":\"2.1\"},\"0.1.32\":{\"node_abi\":null,\"v8\":\"2.1\"},\"0.1.33\":{\"node_abi\":null,\"v8\":\"2.1\"},\"0.1.90\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.91\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.92\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.93\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.94\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.95\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.96\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.97\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.98\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.99\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.100\":{\"node_abi\":null,\"v8\":\"2.2\"},\"0.1.101\":{\"node_abi\":null,\"v8\":\"2.3\"},\"0.1.102\":{\"node_abi\":null,\"v8\":\"2.3\"},\"0.1.103\":{\"node_abi\":null,\"v8\":\"2.3\"},\"0.1.104\":{\"node_abi\":null,\"v8\":\"2.3\"},\"0.2.0\":{\"node_abi\":1,\"v8\":\"2.3\"},\"0.2.1\":{\"node_abi\":1,\"v8\":\"2.3\"},\"0.2.2\":{\"node_abi\":1,\"v8\":\"2.3\"},\"0.2.3\":{\"node_abi\":1,\"v8\":\"2.3\"},\"0.2.4\":{\"node_abi\":1,\"v8\":\"2.3\"},\"0.2.5\":{\"node_abi\":1,\"v8\":\"2.3\"},\"0.2.6\":{\"node_abi\":1,\"v8\":\"2.3\"},\"0.3.0\":{\"node_abi\":1,\"v8\":\"2.5\"},\"0.3.1\":{\"node_abi\":1,\"v8\":\"2.5\"},\"0.3.2\":{\"node_abi\":1,\"v8\":\"3.0\"},\"0.3.3\":{\"node_abi\":1,\"v8\":\"3.0\"},\"0.3.4\":{\"node_abi\":1,\"v8\":\"3.0\"},\"0.3.5\":{\"node_abi\":1,\"v8\":\"3.0\"},\"0.3.6\":{\"node_abi\":1,\"v8\":\"3.0\"},\"0.3.7\":{\"node_abi\":1,\"v8\":\"3.0\"},\"0.3.8\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.0\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.1\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.2\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.3\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.4\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.5\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.6\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.7\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.8\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.9\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.10\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.11\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.4.12\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.5.0\":{\"node_abi\":1,\"v8\":\"3.1\"},\"0.5.1\":{\"node_abi\":1,\"v8\":\"3.4\"},\"0.5.2\":{\"node_abi\":1,\"v8\":\"3.4\"},\"0.5.3\":{\"node_abi\":1,\"v8\":\"3.4\"},\"0.5.4\":{\"node_abi\":1,\"v8\":\"3.5\"},\"0.5.5\":{\"node_abi\":1,\"v8\":\"3.5\"},\"0.5.6\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.5.7\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.5.8\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.5.9\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.5.10\":{\"node_abi\":1,\"v8\":\"3.7\"},\"0.6.0\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.1\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.2\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.3\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.4\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.5\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.6\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.7\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.8\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.9\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.10\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.11\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.12\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.13\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.14\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.15\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.16\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.17\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.18\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.19\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.20\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.6.21\":{\"node_abi\":1,\"v8\":\"3.6\"},\"0.7.0\":{\"node_abi\":1,\"v8\":\"3.8\"},\"0.7.1\":{\"node_abi\":1,\"v8\":\"3.8\"},\"0.7.2\":{\"node_abi\":1,\"v8\":\"3.8\"},\"0.7.3\":{\"node_abi\":1,\"v8\":\"3.9\"},\"0.7.4\":{\"node_abi\":1,\"v8\":\"3.9\"},\"0.7.5\":{\"node_abi\":1,\"v8\":\"3.9\"},\"0.7.6\":{\"node_abi\":1,\"v8\":\"3.9\"},\"0.7.7\":{\"node_abi\":1,\"v8\":\"3.9\"},\"0.7.8\":{\"node_abi\":1,\"v8\":\"3.9\"},\"0.7.9\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.7.10\":{\"node_abi\":1,\"v8\":\"3.9\"},\"0.7.11\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.7.12\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.0\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.1\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.2\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.3\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.4\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.5\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.6\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.7\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.8\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.9\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.10\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.11\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.12\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.13\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.14\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.15\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.16\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.17\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.18\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.19\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.20\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.21\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.22\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.23\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.24\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.25\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.26\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.27\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.8.28\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.9.0\":{\"node_abi\":1,\"v8\":\"3.11\"},\"0.9.1\":{\"node_abi\":10,\"v8\":\"3.11\"},\"0.9.2\":{\"node_abi\":10,\"v8\":\"3.11\"},\"0.9.3\":{\"node_abi\":10,\"v8\":\"3.13\"},\"0.9.4\":{\"node_abi\":10,\"v8\":\"3.13\"},\"0.9.5\":{\"node_abi\":10,\"v8\":\"3.13\"},\"0.9.6\":{\"node_abi\":10,\"v8\":\"3.15\"},\"0.9.7\":{\"node_abi\":10,\"v8\":\"3.15\"},\"0.9.8\":{\"node_abi\":10,\"v8\":\"3.15\"},\"0.9.9\":{\"node_abi\":11,\"v8\":\"3.15\"},\"0.9.10\":{\"node_abi\":11,\"v8\":\"3.15\"},\"0.9.11\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.9.12\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.0\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.1\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.2\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.3\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.4\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.5\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.6\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.7\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.8\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.9\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.10\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.11\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.12\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.13\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.14\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.15\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.16\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.17\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.18\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.19\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.20\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.21\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.22\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.23\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.24\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.25\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.26\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.27\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.28\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.29\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.30\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.31\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.32\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.33\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.34\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.35\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.36\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.37\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.38\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.39\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.40\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.41\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.42\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.43\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.44\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.45\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.46\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.47\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.10.48\":{\"node_abi\":11,\"v8\":\"3.14\"},\"0.11.0\":{\"node_abi\":12,\"v8\":\"3.17\"},\"0.11.1\":{\"node_abi\":12,\"v8\":\"3.18\"},\"0.11.2\":{\"node_abi\":12,\"v8\":\"3.19\"},\"0.11.3\":{\"node_abi\":12,\"v8\":\"3.19\"},\"0.11.4\":{\"node_abi\":12,\"v8\":\"3.20\"},\"0.11.5\":{\"node_abi\":12,\"v8\":\"3.20\"},\"0.11.6\":{\"node_abi\":12,\"v8\":\"3.20\"},\"0.11.7\":{\"node_abi\":12,\"v8\":\"3.20\"},\"0.11.8\":{\"node_abi\":13,\"v8\":\"3.21\"},\"0.11.9\":{\"node_abi\":13,\"v8\":\"3.22\"},\"0.11.10\":{\"node_abi\":13,\"v8\":\"3.22\"},\"0.11.11\":{\"node_abi\":14,\"v8\":\"3.22\"},\"0.11.12\":{\"node_abi\":14,\"v8\":\"3.22\"},\"0.11.13\":{\"node_abi\":14,\"v8\":\"3.25\"},\"0.11.14\":{\"node_abi\":14,\"v8\":\"3.26\"},\"0.11.15\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.11.16\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.0\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.1\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.2\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.3\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.4\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.5\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.6\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.7\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.8\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.9\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.10\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.11\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.12\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.13\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.14\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.15\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.16\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.17\":{\"node_abi\":14,\"v8\":\"3.28\"},\"0.12.18\":{\"node_abi\":14,\"v8\":\"3.28\"},\"1.0.0\":{\"node_abi\":42,\"v8\":\"3.31\"},\"1.0.1\":{\"node_abi\":42,\"v8\":\"3.31\"},\"1.0.2\":{\"node_abi\":42,\"v8\":\"3.31\"},\"1.0.3\":{\"node_abi\":42,\"v8\":\"4.1\"},\"1.0.4\":{\"node_abi\":42,\"v8\":\"4.1\"},\"1.1.0\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.2.0\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.3.0\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.4.1\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.4.2\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.4.3\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.5.0\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.5.1\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.6.0\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.6.1\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.6.2\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.6.3\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.6.4\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.7.1\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.8.1\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.8.2\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.8.3\":{\"node_abi\":43,\"v8\":\"4.1\"},\"1.8.4\":{\"node_abi\":43,\"v8\":\"4.1\"},\"2.0.0\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.0.1\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.0.2\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.1.0\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.2.0\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.2.1\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.3.0\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.3.1\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.3.2\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.3.3\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.3.4\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.4.0\":{\"node_abi\":44,\"v8\":\"4.2\"},\"2.5.0\":{\"node_abi\":44,\"v8\":\"4.2\"},\"3.0.0\":{\"node_abi\":45,\"v8\":\"4.4\"},\"3.1.0\":{\"node_abi\":45,\"v8\":\"4.4\"},\"3.2.0\":{\"node_abi\":45,\"v8\":\"4.4\"},\"3.3.0\":{\"node_abi\":45,\"v8\":\"4.4\"},\"3.3.1\":{\"node_abi\":45,\"v8\":\"4.4\"},\"4.0.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.1.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.1.1\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.1.2\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.2.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.2.1\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.2.2\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.2.3\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.2.4\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.2.5\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.2.6\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.3.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.3.1\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.3.2\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.4.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.4.1\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.4.2\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.4.3\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.4.4\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.4.5\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.4.6\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.4.7\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.5.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.6.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.6.1\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.6.2\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.7.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.7.1\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.7.2\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.7.3\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.8.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.8.1\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.8.2\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.8.3\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.8.4\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.8.5\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.8.6\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.8.7\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.9.0\":{\"node_abi\":46,\"v8\":\"4.5\"},\"4.9.1\":{\"node_abi\":46,\"v8\":\"4.5\"},\"5.0.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.1.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.1.1\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.2.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.3.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.4.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.4.1\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.5.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.6.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.7.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.7.1\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.8.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.9.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.9.1\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.10.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.10.1\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.11.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.11.1\":{\"node_abi\":47,\"v8\":\"4.6\"},\"5.12.0\":{\"node_abi\":47,\"v8\":\"4.6\"},\"6.0.0\":{\"node_abi\":48,\"v8\":\"5.0\"},\"6.1.0\":{\"node_abi\":48,\"v8\":\"5.0\"},\"6.2.0\":{\"node_abi\":48,\"v8\":\"5.0\"},\"6.2.1\":{\"node_abi\":48,\"v8\":\"5.0\"},\"6.2.2\":{\"node_abi\":48,\"v8\":\"5.0\"},\"6.3.0\":{\"node_abi\":48,\"v8\":\"5.0\"},\"6.3.1\":{\"node_abi\":48,\"v8\":\"5.0\"},\"6.4.0\":{\"node_abi\":48,\"v8\":\"5.0\"},\"6.5.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.6.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.7.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.8.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.8.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.9.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.9.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.9.2\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.9.3\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.9.4\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.9.5\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.10.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.10.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.10.2\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.10.3\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.11.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.11.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.11.2\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.11.3\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.11.4\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.11.5\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.12.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.12.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.12.2\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.12.3\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.13.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.13.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.14.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.14.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.14.2\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.14.3\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.14.4\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.15.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.15.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.16.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.17.0\":{\"node_abi\":48,\"v8\":\"5.1\"},\"6.17.1\":{\"node_abi\":48,\"v8\":\"5.1\"},\"7.0.0\":{\"node_abi\":51,\"v8\":\"5.4\"},\"7.1.0\":{\"node_abi\":51,\"v8\":\"5.4\"},\"7.2.0\":{\"node_abi\":51,\"v8\":\"5.4\"},\"7.2.1\":{\"node_abi\":51,\"v8\":\"5.4\"},\"7.3.0\":{\"node_abi\":51,\"v8\":\"5.4\"},\"7.4.0\":{\"node_abi\":51,\"v8\":\"5.4\"},\"7.5.0\":{\"node_abi\":51,\"v8\":\"5.4\"},\"7.6.0\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.7.0\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.7.1\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.7.2\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.7.3\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.7.4\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.8.0\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.9.0\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.10.0\":{\"node_abi\":51,\"v8\":\"5.5\"},\"7.10.1\":{\"node_abi\":51,\"v8\":\"5.5\"},\"8.0.0\":{\"node_abi\":57,\"v8\":\"5.8\"},\"8.1.0\":{\"node_abi\":57,\"v8\":\"5.8\"},\"8.1.1\":{\"node_abi\":57,\"v8\":\"5.8\"},\"8.1.2\":{\"node_abi\":57,\"v8\":\"5.8\"},\"8.1.3\":{\"node_abi\":57,\"v8\":\"5.8\"},\"8.1.4\":{\"node_abi\":57,\"v8\":\"5.8\"},\"8.2.0\":{\"node_abi\":57,\"v8\":\"5.8\"},\"8.2.1\":{\"node_abi\":57,\"v8\":\"5.8\"},\"8.3.0\":{\"node_abi\":57,\"v8\":\"6.0\"},\"8.4.0\":{\"node_abi\":57,\"v8\":\"6.0\"},\"8.5.0\":{\"node_abi\":57,\"v8\":\"6.0\"},\"8.6.0\":{\"node_abi\":57,\"v8\":\"6.0\"},\"8.7.0\":{\"node_abi\":57,\"v8\":\"6.1\"},\"8.8.0\":{\"node_abi\":57,\"v8\":\"6.1\"},\"8.8.1\":{\"node_abi\":57,\"v8\":\"6.1\"},\"8.9.0\":{\"node_abi\":57,\"v8\":\"6.1\"},\"8.9.1\":{\"node_abi\":57,\"v8\":\"6.1\"},\"8.9.2\":{\"node_abi\":57,\"v8\":\"6.1\"},\"8.9.3\":{\"node_abi\":57,\"v8\":\"6.1\"},\"8.9.4\":{\"node_abi\":57,\"v8\":\"6.1\"},\"8.10.0\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.11.0\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.11.1\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.11.2\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.11.3\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.11.4\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.12.0\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.13.0\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.14.0\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.14.1\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.15.0\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.15.1\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.16.0\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.16.1\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.16.2\":{\"node_abi\":57,\"v8\":\"6.2\"},\"8.17.0\":{\"node_abi\":57,\"v8\":\"6.2\"},\"9.0.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.1.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.2.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.2.1\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.3.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.4.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.5.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.6.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.6.1\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.7.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.7.1\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.8.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.9.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.10.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.10.1\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.11.0\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.11.1\":{\"node_abi\":59,\"v8\":\"6.2\"},\"9.11.2\":{\"node_abi\":59,\"v8\":\"6.2\"},\"10.0.0\":{\"node_abi\":64,\"v8\":\"6.6\"},\"10.1.0\":{\"node_abi\":64,\"v8\":\"6.6\"},\"10.2.0\":{\"node_abi\":64,\"v8\":\"6.6\"},\"10.2.1\":{\"node_abi\":64,\"v8\":\"6.6\"},\"10.3.0\":{\"node_abi\":64,\"v8\":\"6.6\"},\"10.4.0\":{\"node_abi\":64,\"v8\":\"6.7\"},\"10.4.1\":{\"node_abi\":64,\"v8\":\"6.7\"},\"10.5.0\":{\"node_abi\":64,\"v8\":\"6.7\"},\"10.6.0\":{\"node_abi\":64,\"v8\":\"6.7\"},\"10.7.0\":{\"node_abi\":64,\"v8\":\"6.7\"},\"10.8.0\":{\"node_abi\":64,\"v8\":\"6.7\"},\"10.9.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.10.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.11.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.12.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.13.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.14.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.14.1\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.14.2\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.15.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.15.1\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.15.2\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.15.3\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.16.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.16.1\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.16.2\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.16.3\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.17.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.18.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.18.1\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.19.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.20.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.20.1\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.21.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.22.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.22.1\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.23.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.23.1\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.23.2\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.23.3\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.24.0\":{\"node_abi\":64,\"v8\":\"6.8\"},\"10.24.1\":{\"node_abi\":64,\"v8\":\"6.8\"},\"11.0.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.1.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.2.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.3.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.4.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.5.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.6.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.7.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.8.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.9.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.10.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.10.1\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.11.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.12.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.13.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.14.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"11.15.0\":{\"node_abi\":67,\"v8\":\"7.0\"},\"12.0.0\":{\"node_abi\":72,\"v8\":\"7.4\"},\"12.1.0\":{\"node_abi\":72,\"v8\":\"7.4\"},\"12.2.0\":{\"node_abi\":72,\"v8\":\"7.4\"},\"12.3.0\":{\"node_abi\":72,\"v8\":\"7.4\"},\"12.3.1\":{\"node_abi\":72,\"v8\":\"7.4\"},\"12.4.0\":{\"node_abi\":72,\"v8\":\"7.4\"},\"12.5.0\":{\"node_abi\":72,\"v8\":\"7.5\"},\"12.6.0\":{\"node_abi\":72,\"v8\":\"7.5\"},\"12.7.0\":{\"node_abi\":72,\"v8\":\"7.5\"},\"12.8.0\":{\"node_abi\":72,\"v8\":\"7.5\"},\"12.8.1\":{\"node_abi\":72,\"v8\":\"7.5\"},\"12.9.0\":{\"node_abi\":72,\"v8\":\"7.6\"},\"12.9.1\":{\"node_abi\":72,\"v8\":\"7.6\"},\"12.10.0\":{\"node_abi\":72,\"v8\":\"7.6\"},\"12.11.0\":{\"node_abi\":72,\"v8\":\"7.7\"},\"12.11.1\":{\"node_abi\":72,\"v8\":\"7.7\"},\"12.12.0\":{\"node_abi\":72,\"v8\":\"7.7\"},\"12.13.0\":{\"node_abi\":72,\"v8\":\"7.7\"},\"12.13.1\":{\"node_abi\":72,\"v8\":\"7.7\"},\"12.14.0\":{\"node_abi\":72,\"v8\":\"7.7\"},\"12.14.1\":{\"node_abi\":72,\"v8\":\"7.7\"},\"12.15.0\":{\"node_abi\":72,\"v8\":\"7.7\"},\"12.16.0\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.16.1\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.16.2\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.16.3\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.17.0\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.18.0\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.18.1\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.18.2\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.18.3\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.18.4\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.19.0\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.19.1\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.20.0\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.20.1\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.20.2\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.21.0\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.22.0\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.22.1\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.22.2\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.22.3\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.22.4\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.22.5\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.22.6\":{\"node_abi\":72,\"v8\":\"7.8\"},\"12.22.7\":{\"node_abi\":72,\"v8\":\"7.8\"},\"13.0.0\":{\"node_abi\":79,\"v8\":\"7.8\"},\"13.0.1\":{\"node_abi\":79,\"v8\":\"7.8\"},\"13.1.0\":{\"node_abi\":79,\"v8\":\"7.8\"},\"13.2.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.3.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.4.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.5.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.6.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.7.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.8.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.9.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.10.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.10.1\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.11.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.12.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.13.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"13.14.0\":{\"node_abi\":79,\"v8\":\"7.9\"},\"14.0.0\":{\"node_abi\":83,\"v8\":\"8.1\"},\"14.1.0\":{\"node_abi\":83,\"v8\":\"8.1\"},\"14.2.0\":{\"node_abi\":83,\"v8\":\"8.1\"},\"14.3.0\":{\"node_abi\":83,\"v8\":\"8.1\"},\"14.4.0\":{\"node_abi\":83,\"v8\":\"8.1\"},\"14.5.0\":{\"node_abi\":83,\"v8\":\"8.3\"},\"14.6.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.7.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.8.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.9.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.10.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.10.1\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.11.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.12.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.13.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.13.1\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.14.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.15.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.15.1\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.15.2\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.15.3\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.15.4\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.15.5\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.16.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.16.1\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.17.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.17.1\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.17.2\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.17.3\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.17.4\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.17.5\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.17.6\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.18.0\":{\"node_abi\":83,\"v8\":\"8.4\"},\"14.18.1\":{\"node_abi\":83,\"v8\":\"8.4\"},\"15.0.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.0.1\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.1.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.2.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.2.1\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.3.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.4.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.5.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.5.1\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.6.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.7.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.8.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.9.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.10.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.11.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.12.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.13.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"15.14.0\":{\"node_abi\":88,\"v8\":\"8.6\"},\"16.0.0\":{\"node_abi\":93,\"v8\":\"9.0\"},\"16.1.0\":{\"node_abi\":93,\"v8\":\"9.0\"},\"16.2.0\":{\"node_abi\":93,\"v8\":\"9.0\"},\"16.3.0\":{\"node_abi\":93,\"v8\":\"9.0\"},\"16.4.0\":{\"node_abi\":93,\"v8\":\"9.1\"},\"16.4.1\":{\"node_abi\":93,\"v8\":\"9.1\"},\"16.4.2\":{\"node_abi\":93,\"v8\":\"9.1\"},\"16.5.0\":{\"node_abi\":93,\"v8\":\"9.1\"},\"16.6.0\":{\"node_abi\":93,\"v8\":\"9.2\"},\"16.6.1\":{\"node_abi\":93,\"v8\":\"9.2\"},\"16.6.2\":{\"node_abi\":93,\"v8\":\"9.2\"},\"16.7.0\":{\"node_abi\":93,\"v8\":\"9.2\"},\"16.8.0\":{\"node_abi\":93,\"v8\":\"9.2\"},\"16.9.0\":{\"node_abi\":93,\"v8\":\"9.3\"},\"16.9.1\":{\"node_abi\":93,\"v8\":\"9.3\"},\"16.10.0\":{\"node_abi\":93,\"v8\":\"9.3\"},\"16.11.0\":{\"node_abi\":93,\"v8\":\"9.4\"},\"16.11.1\":{\"node_abi\":93,\"v8\":\"9.4\"},\"16.12.0\":{\"node_abi\":93,\"v8\":\"9.4\"},\"16.13.0\":{\"node_abi\":93,\"v8\":\"9.4\"},\"17.0.0\":{\"node_abi\":102,\"v8\":\"9.5\"},\"17.0.1\":{\"node_abi\":102,\"v8\":\"9.5\"},\"17.1.0\":{\"node_abi\":102,\"v8\":\"9.5\"}}"); + +/***/ }), + +/***/ 56432: +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse("{\"name\":\"@mapbox/node-pre-gyp\",\"description\":\"Node.js native addon binary install tool\",\"version\":\"1.0.10\",\"keywords\":[\"native\",\"addon\",\"module\",\"c\",\"c++\",\"bindings\",\"binary\"],\"license\":\"BSD-3-Clause\",\"author\":\"Dane Springmeyer \",\"repository\":{\"type\":\"git\",\"url\":\"git://github.com/mapbox/node-pre-gyp.git\"},\"bin\":\"./bin/node-pre-gyp\",\"main\":\"./lib/node-pre-gyp.js\",\"dependencies\":{\"detect-libc\":\"^2.0.0\",\"https-proxy-agent\":\"^5.0.0\",\"make-dir\":\"^3.1.0\",\"node-fetch\":\"^2.6.7\",\"nopt\":\"^5.0.0\",\"npmlog\":\"^5.0.1\",\"rimraf\":\"^3.0.2\",\"semver\":\"^7.3.5\",\"tar\":\"^6.1.11\"},\"devDependencies\":{\"@mapbox/cloudfriend\":\"^5.1.0\",\"@mapbox/eslint-config-mapbox\":\"^3.0.0\",\"aws-sdk\":\"^2.1087.0\",\"codecov\":\"^3.8.3\",\"eslint\":\"^7.32.0\",\"eslint-plugin-node\":\"^11.1.0\",\"mock-aws-s3\":\"^4.0.2\",\"nock\":\"^12.0.3\",\"node-addon-api\":\"^4.3.0\",\"nyc\":\"^15.1.0\",\"tape\":\"^5.5.2\",\"tar-fs\":\"^2.1.1\"},\"nyc\":{\"all\":true,\"skip-full\":false,\"exclude\":[\"test/**\"]},\"scripts\":{\"coverage\":\"nyc --all --include index.js --include lib/ npm test\",\"upload-coverage\":\"nyc report --reporter json && codecov --clear --flags=unit --file=./coverage/coverage-final.json\",\"lint\":\"eslint bin/node-pre-gyp lib/*js lib/util/*js test/*js scripts/*js\",\"fix\":\"npm run lint -- --fix\",\"update-crosswalk\":\"node scripts/abi_crosswalk.js\",\"test\":\"tape test/*test.js\"}}"); + +/***/ }), + /***/ 53597: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -260,7 +276,7 @@ var __importStar = (this && this.__importStar) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isSQLConfig = exports.isHTTPConfig = exports.getConfig = void 0; const core = __importStar(__nccwpck_require__(42186)); -const z = __importStar(__nccwpck_require__(63301)); +const z = __importStar(__nccwpck_require__(30489)); const FormatEnum = z.enum(['csv', 'json']); const CommonConfigSchema = z.object({ downloaded_filename: z.string(), @@ -589,27 +605,14 @@ run().catch(error => { "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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; const os = __importStar(__nccwpck_require__(12087)); const utils_1 = __nccwpck_require__(5278); /** @@ -688,25 +691,6 @@ function escapeProperty(s) { "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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -716,8 +700,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = __nccwpck_require__(87351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); @@ -784,9 +774,7 @@ function addPath(inputPath) { } exports.addPath = addPath; /** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. + * Gets the value of an input. The value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. @@ -797,34 +785,9 @@ function getInput(name, options) { if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } - if (options && options.trimWhitespace === false) { - return val; - } return val.trim(); } exports.getInput = getInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; /** * Sets the value of an output. * @@ -833,7 +796,6 @@ exports.getBooleanInput = getBooleanInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { - process.stdout.write(os.EOL); command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; @@ -975,27 +937,14 @@ exports.getState = getState; "use strict"; // For internal use, subject to change. -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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__nccwpck_require__(35747)); @@ -1026,7 +975,6 @@ exports.issueCommand = issueCommand; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandValue = void 0; /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string @@ -1717,18 +1665,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); const assert_1 = __nccwpck_require__(42357); -const fs = __importStar(__nccwpck_require__(35747)); -const path = __importStar(__nccwpck_require__(85622)); +const fs = __nccwpck_require__(35747); +const path = __nccwpck_require__(85622); _a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; exports.IS_WINDOWS = process.platform === 'win32'; function exists(fsPath) { @@ -1926,18 +1867,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const childProcess = __importStar(__nccwpck_require__(63129)); -const path = __importStar(__nccwpck_require__(85622)); +const childProcess = __nccwpck_require__(63129); +const path = __nccwpck_require__(85622); const util_1 = __nccwpck_require__(31669); -const ioUtil = __importStar(__nccwpck_require__(81962)); +const ioUtil = __nccwpck_require__(81962); const exec = util_1.promisify(childProcess.exec); /** * Copies a file or folder. @@ -2105,73 +2039,58 @@ function which(tool, check) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } - return result; } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ''; - }); -} -exports.which = which; -/** - * Returns a list of all occurrences of the given tool on the system path. - * - * @returns Promise the paths of the tool - */ -function findInPath(tool) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // build the list of extensions to try - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { - for (const extension of process.env['PATHEXT'].split(path.delimiter)) { - if (extension) { - extensions.push(extension); + try { + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env.PATHEXT) { + for (const extension of process.env.PATHEXT.split(path.delimiter)) { + if (extension) { + extensions.push(extension); + } } } - } - // if it's rooted, return it if exists. otherwise return empty. - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return filePath; + } + return ''; } - return []; - } - // if any path separators, return empty - if (tool.includes(path.sep)) { - return []; - } - // build the list of directories - // - // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, - // it feels like we should not do this. Checking the current directory seems like more of a use - // case of a shell, and the which() function exposed by the toolkit should strive for consistency - // across platforms. - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path.delimiter)) { - if (p) { - directories.push(p); + // if any path separators, return empty + if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) { + return ''; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); + } } } - } - // find all matches - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); + // return the first match + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions); + if (filePath) { + return filePath; + } } + return ''; + } + catch (err) { + throw new Error(`which failed with message ${err.message}`); } - return matches; }); } -exports.findInPath = findInPath; +exports.which = which; function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); @@ -2423,17 +2342,17 @@ 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__(80824)); +var uuidv4 = _interopDefault(__nccwpck_require__(20621)); var axios = _interopDefault(__nccwpck_require__(96545)); var stream = __nccwpck_require__(92413); -var FormData = _interopDefault(__nccwpck_require__(69970)); -var tough = __nccwpck_require__(47372); +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 xml2js = __nccwpck_require__(66189); var os = __nccwpck_require__(12087); -var tslib = __nccwpck_require__(35390); +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. @@ -6548,1866 +6467,2047 @@ exports.DomainCredentials = DomainCredentials; /***/ }), -/***/ 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); +/***/ 68930: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + * 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. Neither the name of Salesforce.com 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 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. */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - CombinedStream.call(this); +var net = __nccwpck_require__(11631); +var urlParse = __nccwpck_require__(78835).parse; +var util = __nccwpck_require__(31669); +var pubsuffix = __nccwpck_require__(23005); +var Store = __nccwpck_require__(5340)/* .Store */ .y; +var MemoryCookieStore = __nccwpck_require__(96868)/* .MemoryCookieStore */ .m; +var pathMatch = __nccwpck_require__(55319)/* .pathMatch */ .U; +var VERSION = __nccwpck_require__(88263); - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } +var punycode; +try { + punycode = __nccwpck_require__(94213); +} catch(e) { + console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); } -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}; - } +// From RFC6265 S4.1.1 +// note that it excludes \x3B ";" +var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; - var append = CombinedStream.prototype.append.bind(this); +var CONTROL_CHARS = /[\x00-\x1F]/; - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } +// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in +// the "relaxed" mode, see: +// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 +var TERMINATORS = ['\n', '\r', '\0']; - // 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; - } +// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' +// Note ';' is \x3B +var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); +// date-time parsing constants (RFC6265 S5.1.1) - append(header); - append(value); - append(footer); +var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; - // pass along options.knownLength - this._trackLength(header, value, options); +var MONTH_TO_NUM = { + jan:0, feb:1, mar:2, apr:3, may:4, jun:5, + jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 }; +var NUM_TO_MONTH = [ + 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' +]; +var NUM_TO_DAY = [ + 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' +]; -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; +var MAX_TIME = 2147483647000; // 31-bit max +var MIN_TIME = 0; // 31-bit min - // 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); +/* + * Parses a Natural number (i.e., non-negative integer) with either the + * *DIGIT ( non-digit *OCTET ) + * or + * *DIGIT + * grammar (RFC6265 S5.1.1). + * + * The "trailingOK" boolean controls if the grammar accepts a + * "( non-digit *OCTET )" trailer. + */ +function parseDigits(token, minDigits, maxDigits, trailingOK) { + var count = 0; + while (count < token.length) { + var c = token.charCodeAt(count); + // "non-digit = %x00-2F / %x3A-FF" + if (c <= 0x2F || c >= 0x3A) { + break; + } + count++; } - 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; + // constrain to a minimum and maximum number of digits. + if (count < minDigits || count > maxDigits) { + return null; } - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); + if (!trailingOK && count != token.length) { + return null; } -}; - -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)); + return parseInt(token.substr(0,count), 10); +} - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { +function parseTime(token) { + var parts = token.split(':'); + var result = [0,0,0]; - var fileSize; + /* RF6256 S5.1.1: + * time = hms-time ( non-digit *OCTET ) + * hms-time = time-field ":" time-field ":" time-field + * time-field = 1*2DIGIT + */ - if (err) { - callback(err); - return; - } + if (parts.length !== 3) { + return null; + } - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); + for (var i = 0; i < 3; i++) { + // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be + // followed by "( non-digit *OCTET )" so therefore the last time-field can + // have a trailer + var trailingOK = (i == 2); + var num = parseDigits(parts[i], 1, 2, trailingOK); + if (num === null) { + return null; } + result[i] = num; + } - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); + return result; +} - // 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(); +function parseMonth(token) { + token = String(token).substr(0,3).toLowerCase(); + var num = MONTH_TO_NUM[token]; + return num >= 0 ? num : null; +} - // something else - } else { - callback('Unknown stream'); +/* + * RFC6265 S5.1.1 date parser (see RFC for full grammar) + */ +function parseDate(str) { + if (!str) { + return; } -}; -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; + /* RFC6265 S5.1.1: + * 2. Process each date-token sequentially in the order the date-tokens + * appear in the cookie-date + */ + var tokens = str.split(DATE_DELIM); + if (!tokens) { + return; } - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); + var hour = null; + var minute = null; + var second = null; + var dayOfMonth = null; + var month = null; + var year = null; - 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 || []) - }; + for (var i=0; i= 70 && year <= 99) { + year += 1900; + } else if (year >= 0 && year <= 69) { + year += 2000; + } + } } } - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; + /* RFC 6265 S5.1.1 + * "5. Abort these steps and fail to parse the cookie-date if: + * * at least one of the found-day-of-month, found-month, found- + * year, or found-time flags is not set, + * * the day-of-month-value is less than 1 or greater than 31, + * * the year-value is less than 1601, + * * the hour-value is greater than 23, + * * the minute-value is greater than 59, or + * * the second-value is greater than 59. + * (Note that leap seconds cannot be represented in this syntax.)" + * + * So, in order as above: + */ + if ( + dayOfMonth === null || month === null || year === null || second === null || + dayOfMonth < 1 || dayOfMonth > 31 || + year < 1601 || + hour > 23 || + minute > 59 || + second > 59 + ) { + return; + } -FormData.prototype._getContentDisposition = function(value, options) { + return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); +} - var filename - , contentDisposition - ; +function formatDate(date) { + var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; + var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; + var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; + var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; + return NUM_TO_DAY[date.getUTCDay()] + ', ' + + d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ + h+':'+m+':'+s+' GMT'; +} - 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 || ''); +// S5.1.2 Canonicalized Host Names +function canonicalDomain(str) { + if (str == null) { + return null; } + str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . - if (filename) { - contentDisposition = 'filename="' + filename + '"'; + // convert to IDN if any non-ASCII characters + if (punycode && /[^\u0001-\u007f]/.test(str)) { + str = punycode.toASCII(str); } - return contentDisposition; -}; - -FormData.prototype._getContentType = function(value, options) { - - // use custom content-type above all - var contentType = options.contentType; + return str.toLowerCase(); +} - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); +// S5.1.3 Domain Matching +function domainMatch(str, domStr, canonicalize) { + if (str == null || domStr == null) { + return null; } - - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); + if (canonicalize !== false) { + str = canonicalDomain(str); + domStr = canonicalDomain(domStr); } - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; + /* + * "The domain string and the string are identical. (Note that both the + * domain string and the string will have been canonicalized to lower case at + * this point)" + */ + if (str == domStr) { + return true; } - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } + /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; + /* "* The string is a host name (i.e., not an IP address)." */ + if (net.isIP(str)) { + return false; } - return contentType; -}; + /* "* The domain string is a suffix of the string" */ + var idx = str.indexOf(domStr); + if (idx <= 0) { + return false; // it's a non-match (-1) or prefix (0) + } -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; + // e.g "a.b.c".indexOf("b.c") === 2 + // 5 === 3+2 + if (str.length !== domStr.length + idx) { // it's not a suffix + return false; + } - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } + /* "* The last character of the string that is not included in the domain + * string is a %x2E (".") character." */ + if (str.substr(idx-1,1) !== '.') { + return false; + } - next(footer); - }.bind(this); -}; + return true; +} -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() - }; +// RFC6265 S5.1.4 Paths and Path-Match - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } +/* + * "The user agent MUST use an algorithm equivalent to the following algorithm + * to compute the default-path of a cookie:" + * + * Assumption: the path (and not query part or absolute uri) is passed in. + */ +function defaultPath(path) { + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (!path || path.substr(0,1) !== "/") { + return "/"; } - return formHeaders; -}; + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if (path === "/") { + return path; + } -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); + var rightSlash = path.lastIndexOf("/"); + if (rightSlash === 0) { + return "/"; } - return this._boundary; -}; + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return path.slice(0, rightSlash); +} -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); +function trimTerminator(str) { + for (var t = 0; t < TERMINATORS.length; t++) { + var terminatorIdx = str.indexOf(TERMINATORS[t]); + if (terminatorIdx !== -1) { + str = str.substr(0,terminatorIdx); + } + } - // 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') { + return str; +} - // 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])]); - } +function parseCookiePair(cookiePair, looseMode) { + cookiePair = trimTerminator(cookiePair); - // 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)] ); - } + var firstEq = cookiePair.indexOf('='); + if (looseMode) { + if (firstEq === 0) { // '=' is immediately at start + cookiePair = cookiePair.substr(1); + firstEq = cookiePair.indexOf('='); // might still need to split on '=' + } + } else { // non-loose mode + if (firstEq <= 0) { // no '=' or is at start + return; // needs to have non-empty "cookie-name" } } - // 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); + var cookieName, cookieValue; + if (firstEq <= 0) { + cookieName = ""; + cookieValue = cookiePair.trim(); + } else { + cookieName = cookiePair.substr(0, firstEq).trim(); + cookieValue = cookiePair.substr(firstEq+1).trim(); } - this._boundary = boundary; -}; + if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { + return; + } -// 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; + var c = new Cookie(); + c.key = cookieName; + c.value = cookieValue; + return c; +} - // 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; +function parse(str, options) { + if (!options || typeof options !== 'object') { + options = {}; } + str = str.trim(); - // 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.')); + // We use a regex to parse the "name-value-pair" part of S5.2 + var firstSemi = str.indexOf(';'); // S5.2 step 1 + var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi); + var c = parseCookiePair(cookiePair, !!options.loose); + if (!c) { + return; } - return knownLength; -}; + if (firstSemi === -1) { + return c; + } -// 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; + // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question)." plus later on in the same section + // "discard the first ";" and trim". + var unparsed = str.slice(firstSemi + 1).trim(); - if (this._valuesToMeasure.length) { - hasKnownLength = false; + // "If the unparsed-attributes string is empty, skip the rest of these + // steps." + if (unparsed.length === 0) { + return c; } - return hasKnownLength; -}; - -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; + /* + * S5.2 says that when looping over the items "[p]rocess the attribute-name + * and attribute-value according to the requirements in the following + * subsections" for every item. Plus, for many of the individual attributes + * in S5.3 it says to use the "attribute-value of the last attribute in the + * cookie-attribute-list". Therefore, in this implementation, we overwrite + * the previous value. + */ + var cookie_avs = unparsed.split(';'); + while (cookie_avs.length) { + var av = cookie_avs.shift().trim(); + if (av.length === 0) { // happens if ";;" appears + continue; + } + var av_sep = av.indexOf('='); + var av_key, av_value; - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } + if (av_sep === -1) { + av_key = av; + av_value = null; + } else { + av_key = av.substr(0,av_sep); + av_value = av.substr(av_sep+1); + } - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } + av_key = av_key.trim().toLowerCase(); - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; + if (av_value) { + av_value = av_value.trim(); } - values.forEach(function(length) { - knownLength += length; - }); + switch(av_key) { + case 'expires': // S5.2.1 + if (av_value) { + var exp = parseDate(av_value); + // "If the attribute-value failed to parse as a cookie date, ignore the + // cookie-av." + if (exp) { + // over and underflow not realistically a concern: V8's getTime() seems to + // store something larger than a 32-bit time_t (even with 32-bit node) + c.expires = exp; + } + } + break; - cb(null, knownLength); - }); -}; + case 'max-age': // S5.2.2 + if (av_value) { + // "If the first character of the attribute-value is not a DIGIT or a "-" + // character ...[or]... If the remainder of attribute-value contains a + // non-DIGIT character, ignore the cookie-av." + if (/^-?[0-9]+$/.test(av_value)) { + var delta = parseInt(av_value, 10); + // "If delta-seconds is less than or equal to zero (0), let expiry-time + // be the earliest representable date and time." + c.setMaxAge(delta); + } + } + break; -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; + case 'domain': // S5.2.3 + // "If the attribute-value is empty, the behavior is undefined. However, + // the user agent SHOULD ignore the cookie-av entirely." + if (av_value) { + // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E + // (".") character." + var domain = av_value.trim().replace(/^\./, ''); + if (domain) { + // "Convert the cookie-domain to lower case." + c.domain = domain.toLowerCase(); + } + } + break; - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { + case 'path': // S5.2.4 + /* + * "If the attribute-value is empty or if the first character of the + * attribute-value is not %x2F ("/"): + * Let cookie-path be the default-path. + * Otherwise: + * Let cookie-path be the attribute-value." + * + * We'll represent the default-path as null since it depends on the + * context of the parsing. + */ + c.path = av_value && av_value[0] === "/" ? av_value : null; + break; - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); + case 'secure': // S5.2.5 + /* + * "If the attribute-name case-insensitively matches the string "Secure", + * the user agent MUST append an attribute to the cookie-attribute-list + * with an attribute-name of Secure and an empty attribute-value." + */ + c.secure = true; + break; - // use custom params - } else { + case 'httponly': // S5.2.6 -- effectively the same as 'secure' + c.httpOnly = true; + break; - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; + default: + c.extensions = c.extensions || []; + c.extensions.push(av); + break; } } - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); + return c; +} - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); +// avoid the V8 deoptimization monster! +function jsonParse(str) { + var obj; + try { + obj = JSON.parse(str); + } catch (e) { + return e; } + return obj; +} - // 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); +function fromJSON(str) { + if (!str) { + return null; + } - this.pipe(request); - if (cb) { - request.on('error', cb); - request.on('response', cb.bind(this, null)); + var obj; + if (typeof str === 'string') { + obj = jsonParse(str); + if (obj instanceof Error) { + return null; } - }.bind(this)); - - return request; -}; - -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); + } else { + // assume it's an Object + obj = str; } -}; - -FormData.prototype.toString = function () { - return '[object FormData]'; -}; + var c = new Cookie(); + for (var i=0; i { + return c; +} -// populates missing values -module.exports = function(dst, src) { +/* Section 5.4 part 2: + * "* Cookies with longer paths are listed before cookies with + * shorter paths. + * + * * Among cookies that have equal-length path fields, cookies with + * earlier creation-times are listed before cookies with later + * creation-times." + */ - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); +function cookieCompare(a,b) { + var cmp = 0; - return dst; -}; + // descending for length: b CMP a + var aPathLen = a.path ? a.path.length : 0; + var bPathLen = b.path ? b.path.length : 0; + cmp = bPathLen - aPathLen; + if (cmp !== 0) { + return cmp; + } + // ascending for time: a CMP b + var aTime = a.creation ? a.creation.getTime() : MAX_TIME; + var bTime = b.creation ? b.creation.getTime() : MAX_TIME; + cmp = aTime - bTime; + if (cmp !== 0) { + return cmp; + } -/***/ }), + // break ties for the same millisecond (precision of JavaScript's clock) + cmp = a.creationIndex - b.creationIndex; -/***/ 35390: -/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => { - -"use strict"; -__nccwpck_require__.r(__webpack_exports__); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "__extends": () => /* binding */ __extends, -/* harmony export */ "__assign": () => /* binding */ __assign, -/* harmony export */ "__rest": () => /* binding */ __rest, -/* harmony export */ "__decorate": () => /* binding */ __decorate, -/* harmony export */ "__param": () => /* binding */ __param, -/* harmony export */ "__metadata": () => /* binding */ __metadata, -/* harmony export */ "__awaiter": () => /* binding */ __awaiter, -/* harmony export */ "__generator": () => /* binding */ __generator, -/* harmony export */ "__createBinding": () => /* binding */ __createBinding, -/* harmony export */ "__exportStar": () => /* binding */ __exportStar, -/* harmony export */ "__values": () => /* binding */ __values, -/* harmony export */ "__read": () => /* binding */ __read, -/* harmony export */ "__spread": () => /* binding */ __spread, -/* harmony export */ "__spreadArrays": () => /* binding */ __spreadArrays, -/* harmony export */ "__await": () => /* binding */ __await, -/* harmony export */ "__asyncGenerator": () => /* binding */ __asyncGenerator, -/* harmony export */ "__asyncDelegator": () => /* binding */ __asyncDelegator, -/* harmony export */ "__asyncValues": () => /* binding */ __asyncValues, -/* harmony export */ "__makeTemplateObject": () => /* binding */ __makeTemplateObject, -/* harmony export */ "__importStar": () => /* binding */ __importStar, -/* harmony export */ "__importDefault": () => /* binding */ __importDefault, -/* harmony export */ "__classPrivateFieldGet": () => /* binding */ __classPrivateFieldGet, -/* harmony export */ "__classPrivateFieldSet": () => /* binding */ __classPrivateFieldSet -/* harmony export */ }); -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - 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) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __createBinding(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -} - -function __exportStar(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; -} - -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - -function __classPrivateFieldGet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); -} - -function __classPrivateFieldSet(receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; -} + return cmp; +} +// Gives the permutation of all possible pathMatch()es of a given path. The +// array is in longest-to-shortest order. Handy for indexing. +function permutePath(path) { + if (path === '/') { + return ['/']; + } + if (path.lastIndexOf('/') === path.length-1) { + path = path.substr(0,path.length-1); + } + var permutations = [path]; + while (path.length > 1) { + var lindex = path.lastIndexOf('/'); + if (lindex === 0) { + break; + } + path = path.substr(0,lindex); + permutations.push(path); + } + permutations.push('/'); + return permutations; +} -/***/ }), +function getCookieContext(url) { + if (url instanceof Object) { + return url; + } + // NOTE: decodeURI will throw on malformed URIs (see GH-32). + // Therefore, we will just skip decoding for such URIs. + try { + url = decodeURI(url); + } + catch(err) { + // Silently swallow error + } -/***/ 2265: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + return urlParse(url); +} -"use strict"; +function Cookie(options) { + options = options || {}; -// 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. - * @constructor - * @param {string} clientId The active directory application client id. - * @param {string} domain The domain or tenant id containing this application. - * @param {string} certificate A PEM encoded certificate private key. - * @param {string} thumbprint A hex encoded thumbprint of the certificate. - * @param {string} [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} [environment] The azure environment to authenticate with. - * @param {object} [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 {Promise} A promise that resolves to TokenResponse and rejects with an Error. - */ - getToken() { - return __awaiter(this, void 0, void 0, function* () { - try { - const tokenResponse = yield this.getTokenFromCache(); - return tokenResponse; - } - catch (error) { - if (error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { - return Promise.reject(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 {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 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); + Object.keys(options).forEach(function(prop) { + if (Cookie.prototype.hasOwnProperty(prop) && + Cookie.prototype[prop] !== options[prop] && + prop.substr(0,1) !== '_') + { + this[prop] = options[prop]; } + }, this); + + this.creation = this.creation || new Date(); + + // used to break creation ties in cookieCompare(): + Object.defineProperty(this, 'creationIndex', { + configurable: false, + enumerable: false, // important for assert.deepEqual checks + writable: true, + value: ++Cookie.cookiesCreated + }); } -exports.ApplicationTokenCertificateCredentials = ApplicationTokenCertificateCredentials; -//# sourceMappingURL=applicationTokenCertificateCredentials.js.map -/***/ }), +Cookie.cookiesCreated = 0; // incremented each time a cookie is created -/***/ 35216: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +Cookie.parse = parse; +Cookie.fromJSON = fromJSON; -"use strict"; +Cookie.prototype.key = ""; +Cookie.prototype.value = ""; -// 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()); - }); +// the order in which the RFC has them: +Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity +Cookie.prototype.maxAge = null; // takes precedence over expires for TTL +Cookie.prototype.domain = null; +Cookie.prototype.path = null; +Cookie.prototype.secure = false; +Cookie.prototype.httpOnly = false; +Cookie.prototype.extensions = null; + +// set by the CookieJar: +Cookie.prototype.hostOnly = null; // boolean when set +Cookie.prototype.pathIsDefault = null; // boolean when set +Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse +Cookie.prototype.lastAccessed = null; // Date when set +Object.defineProperty(Cookie.prototype, 'creationIndex', { + configurable: true, + enumerable: false, + writable: true, + value: 0 +}); + +Cookie.serializableProperties = Object.keys(Cookie.prototype) + .filter(function(prop) { + return !( + Cookie.prototype[prop] instanceof Function || + prop === 'creationIndex' || + prop.substr(0,1) === '_' + ); + }); + +Cookie.prototype.inspect = function inspect() { + var now = Date.now(); + return 'Cookie="'+this.toString() + + '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + + '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + + '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + + '"'; }; -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. - * @constructor - * @param {string} clientId The active directory application client id. - * @param {string} domain The domain or tenant id containing this application. - * @param {string} secret The authentication secret for the application. - * @param {string} [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} [environment] The azure environment to authenticate with. - * @param {object} [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 {Promise} A promise that resolves to TokenResponse and rejects with an Error. - */ - getToken() { - return __awaiter(this, void 0, void 0, function* () { - try { - const tokenResponse = yield this.getTokenFromCache(); - return tokenResponse; - } - catch (error) { - if (error.message && - error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { - return Promise.reject(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); - }); - }); - } - }); - } + +// Use the new custom inspection symbol to add the custom inspect function if +// available. +if (util.inspect.custom) { + Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect; } -exports.ApplicationTokenCredentials = ApplicationTokenCredentials; -//# sourceMappingURL=applicationTokenCredentials.js.map -/***/ }), +Cookie.prototype.toJSON = function() { + var obj = {}; -/***/ 60968: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + var props = Cookie.serializableProperties; + for (var i=0; i super.getTokenFromCache } - }); - return __awaiter(this, void 0, void 0, function* () { - const self = this; - // a thin wrapper over the base implementation. try get token from cache, additionaly clean up cache if required. - try { - const tokenResponse = yield _super.getTokenFromCache.call(this, undefined); - return Promise.resolve(tokenResponse); - } - 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 self.removeInvalidItemsFromCache({ - _clientId: self.clientId - }); - if (status.result) { - return Promise.reject(error); - } - const message = status && status.details && status.details.message - ? status.details.message - : status.details; - return Promise.reject(new Error(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR + - " : " + - "critical failure while removing expired token for service principal from token cache. " + - message)); - } - }); + +Cookie.prototype.clone = function() { + return fromJSON(this.toJSON()); +}; + +Cookie.prototype.validate = function validate() { + if (!COOKIE_OCTETS.test(this.value)) { + return false; + } + if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) { + return false; + } + if (this.maxAge != null && this.maxAge <= 0) { + return false; // "Max-Age=" non-zero-digit *DIGIT + } + if (this.path != null && !PATH_VALUE.test(this.path)) { + return false; + } + + var cdomain = this.cdomain(); + if (cdomain) { + if (cdomain.match(/\.$/)) { + return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this } - /** - * 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 {object} query The query to be used for finding the token for service principal from the cache - * @returns {result: boolean, details?: Error} 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 new Promise(resolve => { - return self.tokenCache.remove(entries, (err) => { - if (err) { - return resolve({ result: false, details: err }); - } - return resolve({ result: true }); - }); - }); - } - else { - return resolve({ result: true }); - } - }); - }); + var suffix = pubsuffix.getPublicSuffix(cdomain); + if (suffix == null) { // it's a public suffix + return false; } -} -exports.ApplicationTokenCredentialsBase = ApplicationTokenCredentialsBase; -//# sourceMappingURL=applicationTokenCredentialsBase.js.map + } + return true; +}; -/***/ }), +Cookie.prototype.setExpires = function setExpires(exp) { + if (exp instanceof Date) { + this.expires = exp; + } else { + this.expires = parseDate(exp) || "Infinity"; + } +}; -/***/ 38909: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +Cookie.prototype.setMaxAge = function setMaxAge(age) { + if (age === Infinity || age === -Infinity) { + this.maxAge = age.toString(); // so JSON.stringify() works + } else { + this.maxAge = age; + } +}; -"use strict"; +// gives Cookie header format +Cookie.prototype.cookieString = function cookieString() { + var val = this.value; + if (val == null) { + val = ''; + } + if (this.key === '') { + return val; + } + return this.key+'='+val; +}; -// 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()); +// gives Set-Cookie header format +Cookie.prototype.toString = function toString() { + var str = this.cookieString(); + + if (this.expires != Infinity) { + if (this.expires instanceof Date) { + str += '; Expires='+formatDate(this.expires); + } else { + str += '; Expires='+this.expires; + } + } + + if (this.maxAge != null && this.maxAge != Infinity) { + str += '; Max-Age='+this.maxAge; + } + + if (this.domain && !this.hostOnly) { + str += '; Domain='+this.domain; + } + if (this.path) { + str += '; Path='+this.path; + } + + if (this.secure) { + str += '; Secure'; + } + if (this.httpOnly) { + str += '; HttpOnly'; + } + if (this.extensions) { + this.extensions.forEach(function(ext) { + str += '; '+ext; }); + } + + return str; }; -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; + +// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere) +// S5.3 says to give the "latest representable date" for which we use Infinity +// For "expired" we use 0 +Cookie.prototype.TTL = function TTL(now) { + /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires + * attribute, the Max-Age attribute has precedence and controls the + * expiration date of the cookie. + * (Concurs with S5.3 step 3) + */ + if (this.maxAge != null) { + return this.maxAge<=0 ? 0 : this.maxAge*1000; + } + + var expires = this.expires; + if (expires != Infinity) { + if (!(expires instanceof Date)) { + expires = parseDate(expires) || Infinity; } - /** - * Tries to get the new token from Azure CLI, if the token has expired or the subscription has - * changed else uses the cached accessToken. - * @return 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; - }); + + if (expires == Infinity) { + return Infinity; } - /** - * 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 Promise.resolve(webResource); - }); + + return expires.getTime() - (now || Date.now()); + } + + return Infinity; +}; + +// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere) +Cookie.prototype.expiryTime = function expiryTime(now) { + if (this.maxAge != null) { + var relativeTo = now || this.creation || new Date(); + var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000; + return relativeTo.getTime() + age; + } + + if (this.expires == Infinity) { + return Infinity; + } + return this.expires.getTime(); +}; + +// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere), except it returns a Date +Cookie.prototype.expiryDate = function expiryDate(now) { + var millisec = this.expiryTime(now); + if (millisec == Infinity) { + return new Date(MAX_TIME); + } else if (millisec == -Infinity) { + return new Date(MIN_TIME); + } else { + return new Date(millisec); + } +}; + +// This replaces the "persistent-flag" parts of S5.3 step 3 +Cookie.prototype.isPersistent = function isPersistent() { + return (this.maxAge != null || this.expires != Infinity); +}; + +// Mostly S5.1.2 and S5.2.3: +Cookie.prototype.cdomain = +Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() { + if (this.domain == null) { + return null; + } + return canonicalDomain(this.domain); +}; + +function CookieJar(store, options) { + if (typeof options === "boolean") { + options = {rejectPublicSuffixes: options}; + } else if (options == null) { + options = {}; + } + if (options.rejectPublicSuffixes != null) { + this.rejectPublicSuffixes = options.rejectPublicSuffixes; + } + if (options.looseMode != null) { + this.enableLooseMode = options.looseMode; + } + + if (!store) { + store = new MemoryCookieStore(); + } + this.store = store; +} +CookieJar.prototype.store = null; +CookieJar.prototype.rejectPublicSuffixes = true; +CookieJar.prototype.enableLooseMode = false; +var CAN_BE_SYNC = []; + +CAN_BE_SYNC.push('setCookie'); +CookieJar.prototype.setCookie = function(cookie, url, options, cb) { + var err; + var context = getCookieContext(url); + if (options instanceof Function) { + cb = options; + options = {}; + } + + var host = canonicalDomain(context.hostname); + var loose = this.enableLooseMode; + if (options.loose != null) { + loose = options.loose; + } + + // S5.3 step 1 + 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); + } + + // S5.3 step 2 + var now = options.now || new Date(); // will assign later to save effort in the face of errors + + // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() + + // S5.3 step 4: NOOP; domain is null by default + + // S5.3 step 5: public suffixes + if (this.rejectPublicSuffixes && cookie.domain) { + var suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); + if (suffix == null) { // e.g. "com" + err = new Error("Cookie has domain set to a public suffix"); + return cb(options.ignoreError ? null : err); } - _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; + } + + // S5.3 step 6: + if (cookie.domain) { + if (!domainMatch(host, cookie.cdomain(), false)) { + err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host); + return cb(options.ignoreError ? null : err); } - _hasSubscriptionChanged() { - return this.subscriptionInfo.id !== this.tokenInfo.subscription; + + if (cookie.hostOnly == null) { // don't reset if already set + cookie.hostOnly = false; } - _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); - } + + } else { + cookie.hostOnly = true; + cookie.domain = host; + } + + //S5.2.4 If the attribute-value is empty or if the first character of the + //attribute-value is not %x2F ("/"): + //Let cookie-path be the default-path. + if (!cookie.path || cookie.path[0] !== '/') { + cookie.path = defaultPath(context.pathname); + cookie.pathIsDefault = true; + } + + // S5.3 step 8: NOOP; secure attribute + // S5.3 step 9: NOOP; httpOnly attribute + + // S5.3 step 10 + if (options.http === false && cookie.httpOnly) { + err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + + var store = this.store; + + if (!store.updateCookie) { + store.updateCookie = function(oldCookie, newCookie, cb) { + this.putCookie(newCookie, cb); + }; + } + + function withCookie(err, oldCookie) { + if (err) { + return cb(err); } - _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"); + + var next = function(err) { + if (err) { + return cb(err); + } else { + cb(null, cookie); + } + }; + + if (oldCookie) { + // S5.3 step 11 - "If the cookie store contains a cookie with the same name, + // domain, and path as the newly created cookie:" + if (options.http === false && oldCookie.httpOnly) { // step 11.2 + err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + cookie.creation = oldCookie.creation; // step 11.3 + cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker + cookie.lastAccessed = now; + // Step 11.4 (delete cookie) is implied by just setting the new one: + store.updateCookie(oldCookie, cookie, next); // step 12 + + } else { + cookie.creation = cookie.lastAccessed = now; + store.putCookie(cookie, next); // step 12 } - _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; + } + + store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); +}; + +// RFC6365 S5.4 +CAN_BE_SYNC.push('getCookies'); +CookieJar.prototype.getCookies = function(url, options, cb) { + var context = getCookieContext(url); + if (options instanceof Function) { + cb = options; + options = {}; + } + + var host = canonicalDomain(context.hostname); + var path = context.pathname || '/'; + + var secure = options.secure; + if (secure == null && context.protocol && + (context.protocol == 'https:' || context.protocol == 'wss:')) + { + secure = true; + } + + var http = options.http; + if (http == null) { + http = true; + } + + var now = options.now || Date.now(); + var expireCheck = options.expire !== false; + var allPaths = !!options.allPaths; + var store = this.store; + + function matchingCookie(c) { + // "Either: + // The cookie's host-only-flag is true and the canonicalized + // request-host is identical to the cookie's domain. + // Or: + // The cookie's host-only-flag is false and the canonicalized + // request-host domain-matches the cookie's domain." + if (c.hostOnly) { + if (c.domain != host) { + return false; + } + } else { + if (!domainMatch(host, c.domain, false)) { + return false; + } } - /** - * 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 { - let cmd = "account get-access-token"; - if (options.subscriptionIdOrName) { - cmd += ` -s "${options.subscriptionIdOrName}"`; - } - if (options.resource) { - cmd += ` --resource ${options.resource}`; - } - const result = yield login_1.execAz(cmd); - 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); - } - }); + + // "The request-uri's path path-matches the cookie's path." + if (!allPaths && !pathMatch(path, c.path)) { + return false; } - /** - * 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 { - let cmd = "account show"; - if (subscriptionIdOrName) { - cmd += ` -s "${subscriptionIdOrName}"`; - } - const result = yield login_1.execAz(cmd); - 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); - } - }); + + // "If the cookie's secure-only-flag is true, then the request-uri's + // scheme must denote a "secure" protocol" + if (c.secure && !secure) { + return false; } - /** - * 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); - } - }); + + // "If the cookie's http-only-flag is true, then exclude the cookie if the + // cookie-string is being generated for a "non-HTTP" API" + if (c.httpOnly && !http) { + return false; } - /** - * 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 { - let cmd = "account list"; - if (options.all) { - cmd += " --all"; - } - if (options.refresh) { - cmd += "--refresh"; - } - subscriptionList = yield login_1.execAz(cmd); - 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); - } - }); + + // deferred from S5.3 + // non-RFC: allow retention of expired cookies by choice + if (expireCheck && c.expiryTime() <= now) { + store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored + return false; } - /** - * 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); - }); + + return true; + } + + store.findCookies(host, allPaths ? null : path, function(err,cookies) { + if (err) { + return cb(err); } -} -exports.AzureCliCredentials = AzureCliCredentials; -//# sourceMappingURL=azureCliCredentials.js.map -/***/ }), + cookies = cookies.filter(matchingCookie); -/***/ 80450: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // sorting of S5.4 part 2 + if (options.sort !== false) { + cookies = cookies.sort(cookieCompare); + } -"use strict"; + // S5.4 part 3 + var now = new Date(); + cookies.forEach(function(c) { + c.lastAccessed = now; + }); + // TODO persist lastAccessed -// 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. - * - * @constructor - * @param {string} [clientId] The active directory application client id. - * @param {string} [domain] The domain or tenant id containing this application. Default value is "common" - * @param {string} [username] The user name for account in the form: "user@example.com". - * @param {string} [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} [environment] The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud". - * @param {object} [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; + cb(null,cookies); + }); +}; + +CAN_BE_SYNC.push('getCookieString'); +CookieJar.prototype.getCookieString = function(/*..., cb*/) { + var args = Array.prototype.slice.call(arguments,0); + var cb = args.pop(); + var next = function(err,cookies) { + if (err) { + cb(err); + } else { + cb(null, cookies + .sort(cookieCompare) + .map(function(c){ + return c.cookieString(); + }) + .join('; ')); } - getToken() { - // For device auth, this is just getTokenFromCache. - return this.getTokenFromCache(this.username); + }; + args.push(next); + this.getCookies.apply(this,args); +}; + +CAN_BE_SYNC.push('getSetCookieStrings'); +CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) { + var args = Array.prototype.slice.call(arguments,0); + var cb = args.pop(); + var next = function(err,cookies) { + if (err) { + cb(err); + } else { + cb(null, cookies.map(function(c){ + return c.toString(); + })); } -} -exports.DeviceTokenCredentials = DeviceTokenCredentials; -//# sourceMappingURL=deviceTokenCredentials.js.map + }; + args.push(next); + this.getCookies.apply(this,args); +}; -/***/ }), +CAN_BE_SYNC.push('serialize'); +CookieJar.prototype.serialize = function(cb) { + var type = this.store.constructor.name; + if (type === 'Object') { + type = null; + } -/***/ 23699: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // update README.md "Serialization Format" if you change this, please! + var serialized = { + // The version of tough-cookie that serialized this jar. Generally a good + // practice since future versions can make data import decisions based on + // known past behavior. When/if this matters, use `semver`. + version: 'tough-cookie@'+VERSION, -"use strict"; + // add the store type, to make humans happy: + storeType: type, -// 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 + // CookieJar configuration: + rejectPublicSuffixes: !!this.rejectPublicSuffixes, -/***/ }), + // this gets filled from getAllCookies: + cookies: [] + }; -/***/ 68376: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + if (!(this.store.getAllCookies && + typeof this.store.getAllCookies === 'function')) + { + return cb(new Error('store does not support getAllCookies and cannot be serialized')); + } -"use strict"; + this.store.getAllCookies(function(err,cookies) { + if (err) { + return cb(err); + } -// 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()); + serialized.cookies = cookies.map(function(cookie) { + // convert to serialized 'raw' cookies + cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie; + + // Remove the index so new ones get assigned during deserialization + delete cookie.creationIndex; + + return cookie; }); + + return cb(null, serialized); + }); }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const msiTokenCredentials_1 = __nccwpck_require__(6182); -const ms_rest_js_1 = __nccwpck_require__(30812); -/** - * @class MSIAppServiceTokenCredentials - */ -class MSIAppServiceTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials { - /** - * Creates an instance of MSIAppServiceTokenCredentials. - * @param {string} [options.msiEndpoint] - The local URL from which your app can request tokens. - * Either provide this parameter or set the environment variable `MSI_ENDPOINT`. - * For example: `MSI_ENDPOINT="http://127.0.0.1:41741/MSI/token/"` - * @param {string} [options.msiSecret] - The secret used in communication between your code and the local MSI agent. - * Either provide this parameter or set the environment variable `MSI_SECRET`. - * For example: `MSI_SECRET="69418689F1E342DD946CB82994CDA3CB"` - * @param {string} [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 {string} [options.msiApiVersion] - The api-version of the local MSI agent. Default value is "2017-09-01". - */ - constructor(options) { - if (!options) - options = {}; - super(options); - options.msiEndpoint = options.msiEndpoint || process.env["MSI_ENDPOINT"]; - options.msiSecret = options.msiSecret || 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 "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 "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; - } - /** - * Prepares and sends a GET request to a service endpoint indicated by the app service, which responds with the access token. - * @return {Promise} 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(); - let opRes; - let result; - 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}`); - } - 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; - }); + +// well-known name that JSON.stringify calls +CookieJar.prototype.toJSON = function() { + return this.serializeSync(); +}; + +// use the class method CookieJar.deserialize instead of calling this directly +CAN_BE_SYNC.push('_importCookies'); +CookieJar.prototype._importCookies = function(serialized, cb) { + var jar = this; + var cookies = serialized.cookies; + if (!cookies || !Array.isArray(cookies)) { + return cb(new Error('serialized jar has no cookies array')); + } + cookies = cookies.slice(); // do not modify the original + + function putNext(err) { + if (err) { + return cb(err); } - prepareRequestOptions() { - const endpoint = this.msiEndpoint.endsWith("/") ? this.msiEndpoint : `${this.msiEndpoint}/`; - const resource = encodeURIComponent(this.resource); - const getUrl = `${endpoint}?resource=${resource}&api-version=${this.msiApiVersion}`; - const reqOptions = { - url: getUrl, - headers: { - "secret": this.msiSecret - }, - method: "GET" - }; - const webResource = new ms_rest_js_1.WebResource(); - return webResource.prepare(reqOptions); + + if (!cookies.length) { + return cb(err, jar); } -} -exports.MSIAppServiceTokenCredentials = MSIAppServiceTokenCredentials; -//# sourceMappingURL=msiAppServiceTokenCredentials.js.map -/***/ }), + var cookie; + try { + cookie = fromJSON(cookies.shift()); + } catch (e) { + return cb(e); + } -/***/ 6182: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + if (cookie === null) { + return putNext(null); // skip this cookie + } -"use strict"; + jar.store.putCookie(cookie, putNext); + } -// 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()); - }); + putNext(); }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const ms_rest_js_1 = __nccwpck_require__(30812); -const authConstants_1 = __nccwpck_require__(26700); -/** - * @class MSITokenCredentials - 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 {object} [options] - Optional parameters - * @param {string} [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 {string} body A json string - * @return {object} [tokenResponse] 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(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. - * @return {Promise} 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 Promise.resolve(webResource); - }); + +CookieJar.deserialize = function(strOrObj, store, cb) { + if (arguments.length !== 3) { + // store is optional + cb = store; + store = null; + } + + var serialized; + if (typeof strOrObj === 'string') { + serialized = jsonParse(strOrObj); + if (serialized instanceof Error) { + return cb(serialized); } -} -exports.MSITokenCredentials = MSITokenCredentials; -//# sourceMappingURL=msiTokenCredentials.js.map + } else { + serialized = strOrObj; + } -/***/ }), + var jar = new CookieJar(store, serialized.rejectPublicSuffixes); + jar._importCookies(serialized, function(err) { + if (err) { + return cb(err); + } + cb(null, jar); + }); +}; -/***/ 73287: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +CookieJar.deserializeSync = function(strOrObj, store) { + var serialized = typeof strOrObj === 'string' ? + JSON.parse(strOrObj) : strOrObj; + var jar = new CookieJar(store, serialized.rejectPublicSuffixes); -"use strict"; + // catch this mistake early: + if (!jar.store.synchronous) { + throw new Error('CookieJar store is not synchronous; use async API instead.'); + } -// 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()); - }); + jar._importCookiesSync(serialized); + return jar; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const msiTokenCredentials_1 = __nccwpck_require__(6182); -const ms_rest_js_1 = __nccwpck_require__(30812); -/** - * @class MSIVmTokenCredentials - */ -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; +CookieJar.fromJSON = CookieJar.deserializeSync; + +CookieJar.prototype.clone = function(newStore, cb) { + if (arguments.length === 1) { + cb = newStore; + newStore = null; + } + + this.serialize(function(err,serialized) { + if (err) { + return cb(err); } - /** - * Prepares and sends a POST request to a service endpoint hosted on the Azure VM, which responds with the access token. - * @return {Promise} 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(); - let opRes; - let result; - opRes = yield this._httpClient.sendRequest(reqOptions); - 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; - }); + CookieJar.deserialize(serialized, newStore, cb); + }); +}; + +CAN_BE_SYNC.push('removeAllCookies'); +CookieJar.prototype.removeAllCookies = function(cb) { + var store = this.store; + + // Check that the store implements its own removeAllCookies(). The default + // implementation in Store will immediately call the callback with a "not + // implemented" Error. + if (store.removeAllCookies instanceof Function && + store.removeAllCookies !== Store.prototype.removeAllCookies) + { + return store.removeAllCookies(cb); + } + + store.getAllCookies(function(err, cookies) { + if (err) { + return cb(err); } - 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); + + if (cookies.length === 0) { + return cb(null); } -} -exports.MSIVmTokenCredentials = MSIVmTokenCredentials; -//# sourceMappingURL=msiVmTokenCredentials.js.map -/***/ }), + var completedCount = 0; + var removeErrors = []; -/***/ 5558: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + function removeCookieCb(removeErr) { + if (removeErr) { + removeErrors.push(removeErr); + } -"use strict"; + completedCount++; -// 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()); + if (completedCount === cookies.length) { + return cb(removeErrors.length ? removeErrors[0] : null); + } + } + + cookies.forEach(function(cookie) { + store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb); }); + }); }; -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 \"commmon\" tenant.\ - It must be the actual tenant (preferrably 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); - } - 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); - }); - }); + +CookieJar.prototype._cloneSync = syncWrap('clone'); +CookieJar.prototype.cloneSync = function(newStore) { + if (!newStore.synchronous) { + throw new Error('CookieJar clone destination store is not synchronous; use async API instead.'); + } + return this._cloneSync(newStore); +}; + +// Use a closure to provide a true imperative API for synchronous stores. +function syncWrap(method) { + return function() { + if (!this.store.synchronous) { + throw new Error('CookieJar store is not synchronous; use async API instead.'); } - /** - * Signs a request with the Authentication header. - * - * @param {webResource} The WebResource to be signed. - * @param {function(error)} callback The callback function. - * @return {undefined} - */ - 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 Promise.resolve(webResource); - }); + + var args = Array.prototype.slice.call(arguments); + var syncErr, syncResult; + args.push(function syncCb(err, result) { + syncErr = err; + syncResult = result; + }); + this[method].apply(this, args); + + if (syncErr) { + throw syncErr; } + return syncResult; + }; } -exports.TokenCredentialsBase = TokenCredentialsBase; -//# sourceMappingURL=tokenCredentialsBase.js.map + +// wrap all declared CAN_BE_SYNC methods in the sync wrapper +CAN_BE_SYNC.forEach(function(method) { + CookieJar.prototype[method+'Sync'] = syncWrap(method); +}); + +exports.version = VERSION; +exports.CookieJar = CookieJar; +exports.Cookie = Cookie; +exports.Store = Store; +exports.MemoryCookieStore = MemoryCookieStore; +exports.parseDate = parseDate; +exports.formatDate = formatDate; +exports.parse = parse; +exports.fromJSON = fromJSON; +exports.domainMatch = domainMatch; +exports.defaultPath = defaultPath; +exports.pathMatch = pathMatch; +exports.getPublicSuffix = pubsuffix.getPublicSuffix; +exports.cookieCompare = cookieCompare; +exports.permuteDomain = __nccwpck_require__(91287).permuteDomain; +exports.permutePath = permutePath; +exports.canonicalDomain = canonicalDomain; + /***/ }), -/***/ 14502: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 96868: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 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. Neither the name of Salesforce.com 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 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. + */ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. +var Store = __nccwpck_require__(5340)/* .Store */ .y; +var permuteDomain = __nccwpck_require__(91287).permuteDomain; +var pathMatch = __nccwpck_require__(55319)/* .pathMatch */ .U; +var util = __nccwpck_require__(31669); + +function MemoryCookieStore() { + Store.call(this); + this.idx = {}; +} +util.inherits(MemoryCookieStore, Store); +exports.m = MemoryCookieStore; +MemoryCookieStore.prototype.idx = null; + +// Since it's just a struct in RAM, this Store is synchronous +MemoryCookieStore.prototype.synchronous = true; + +// force a default depth: +MemoryCookieStore.prototype.inspect = function() { + return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; +}; + +// Use the new custom inspection symbol to add the custom inspect function if +// available. +if (util.inspect.custom) { + MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect; +} + +MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) { + if (!this.idx[domain]) { + return cb(null,undefined); + } + if (!this.idx[domain][path]) { + return cb(null,undefined); + } + return cb(null,this.idx[domain][path][key]||null); +}; + +MemoryCookieStore.prototype.findCookies = function(domain, path, cb) { + var results = []; + if (!domain) { + return cb(null,[]); + } + + var pathMatcher; + if (!path) { + // null means "all paths" + pathMatcher = function matchAll(domainIndex) { + for (var curPath in domainIndex) { + var pathIndex = domainIndex[curPath]; + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + }; + + } else { + pathMatcher = function matchRFC(domainIndex) { + //NOTE: we should use path-match algorithm from S5.1.4 here + //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) + Object.keys(domainIndex).forEach(function (cookiePath) { + if (pathMatch(path, cookiePath)) { + var pathIndex = domainIndex[cookiePath]; + + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + }); + }; + } + + var domains = permuteDomain(domain) || [domain]; + var idx = this.idx; + domains.forEach(function(curDomain) { + var domainIndex = idx[curDomain]; + if (!domainIndex) { + return; + } + pathMatcher(domainIndex); + }); + + cb(null,results); +}; + +MemoryCookieStore.prototype.putCookie = function(cookie, cb) { + if (!this.idx[cookie.domain]) { + this.idx[cookie.domain] = {}; + } + if (!this.idx[cookie.domain][cookie.path]) { + this.idx[cookie.domain][cookie.path] = {}; + } + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); +}; + +MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie,cb); +}; + +MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) { + if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { + delete this.idx[domain][path][key]; + } + cb(null); +}; + +MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) { + if (this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); +}; + +MemoryCookieStore.prototype.removeAllCookies = function(cb) { + this.idx = {}; + return cb(null); +} + +MemoryCookieStore.prototype.getAllCookies = function(cb) { + var cookies = []; + var idx = this.idx; + + var domains = Object.keys(idx); + domains.forEach(function(domain) { + var paths = Object.keys(idx[domain]); + paths.forEach(function(path) { + var keys = Object.keys(idx[domain][path]); + keys.forEach(function(key) { + if (key !== null) { + cookies.push(idx[domain][path][key]); + } + }); + }); + }); + + // Sort by creationIndex so deserializing retains the creation order. + // When implementing your own store, this SHOULD retain the order too + cookies.sort(function(a,b) { + return (a.creationIndex||0) - (b.creationIndex||0); + }); + + cb(null, cookies); +}; + + +/***/ }), + +/***/ 55319: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 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. Neither the name of Salesforce.com 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 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. + */ + +/* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ +function pathMatch (reqPath, cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; + } + + var idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } + + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length, 1) === "/") { + return true; + } + } + + return false; +} + +exports.U = pathMatch; + + +/***/ }), + +/***/ 91287: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 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. Neither the name of Salesforce.com 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 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. + */ + +var pubsuffix = __nccwpck_require__(23005); + +// Gives the permutation of all possible domainMatch()es of a given domain. The +// array is in shortest-to-longest order. Handy for indexing. +function permuteDomain (domain) { + var pubSuf = pubsuffix.getPublicSuffix(domain); + if (!pubSuf) { + return null; + } + if (pubSuf == domain) { + return [domain]; + } + + var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" + var parts = prefix.split('.').reverse(); + var cur = pubSuf; + var permutations = [cur]; + while (parts.length) { + cur = parts.shift() + '.' + cur; + permutations.push(cur); + } + return permutations; +} + +exports.permuteDomain = permuteDomain; + + +/***/ }), + +/***/ 23005: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * Copyright (c) 2018, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 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. Neither the name of Salesforce.com 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 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. + */ + +var psl = __nccwpck_require__(29975); + +function getPublicSuffix(domain) { + return psl.get(domain); +} + +exports.getPublicSuffix = getPublicSuffix; + + +/***/ }), + +/***/ 5340: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 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. Neither the name of Salesforce.com 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 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. + */ + +/*jshint unused:false */ + +function Store() { +} +exports.y = Store; + +// Stores may be synchronous, but are still required to use a +// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync" +// API that converts from synchronous-callbacks to imperative style. +Store.prototype.synchronous = false; + +Store.prototype.findCookie = function(domain, path, key, cb) { + throw new Error('findCookie is not implemented'); +}; + +Store.prototype.findCookies = function(domain, path, cb) { + throw new Error('findCookies is not implemented'); +}; + +Store.prototype.putCookie = function(cookie, cb) { + throw new Error('putCookie is not implemented'); +}; + +Store.prototype.updateCookie = function(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error('updateCookie is not implemented'); +}; + +Store.prototype.removeCookie = function(domain, path, key, cb) { + throw new Error('removeCookie is not implemented'); +}; + +Store.prototype.removeCookies = function(domain, path, cb) { + throw new Error('removeCookies is not implemented'); +}; + +Store.prototype.removeAllCookies = function(cb) { + throw new Error('removeAllCookies is not implemented'); +} + +Store.prototype.getAllCookies = function(cb) { + throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)'); +}; + + +/***/ }), + +/***/ 88263: +/***/ ((module) => { + +// generated by genversion +module.exports = '2.5.0' + + +/***/ }), + +/***/ 64305: +/***/ ((module) => { + +/** + * 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); +} + +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(''); +} + +module.exports = bytesToUuid; + + +/***/ }), + +/***/ 7968: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// Unique ID creation requires a high quality random # generator. In node.js +// this is pretty straight-forward - we use the crypto API. + +var crypto = __nccwpck_require__(76417); + +module.exports = function nodeRNG() { + return crypto.randomBytes(16); +}; + + +/***/ }), + +/***/ 20621: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var rng = __nccwpck_require__(7968); +var bytesToUuid = __nccwpck_require__(64305); + +function v4(options, buf, offset) { + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options === 'binary' ? new Array(16) : null; + options = null; + } + 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]; + } + } + + return buf || bytesToUuid(rnds); +} + +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); } } @@ -8417,86 +8517,180 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const tokenCredentialsBase_1 = __nccwpck_require__(5558); -class UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase { +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 UserTokenCredentials object. - * + * 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. * @constructor * @param {string} 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 {string} domain The domain or tenant id containing this application. - * @param {string} username The user name for the Organization Id account. - * @param {string} password The password for the Organization Id account. + * @param {string} certificate A PEM encoded certificate private key. + * @param {string} thumbprint A hex encoded thumbprint of the certificate. * @param {string} [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} [environment] The azure environment to authenticate with. * @param {object} [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."); + 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 (!domain || typeof domain.valueOf() !== "string") { - throw new Error("domain must be a non empty string."); + if (!thumbprint || typeof thumbprint.valueOf() !== "string") { + throw new Error("thumbprint must be a non empty string."); } - if (!username || typeof username.valueOf() !== "string") { - throw new Error("username 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 {Promise} A promise that resolves to TokenResponse and rejects with an Error. + */ + getToken() { + return __awaiter(this, void 0, void 0, function* () { + try { + const tokenResponse = yield this.getTokenFromCache(); + return tokenResponse; + } + catch (error) { + if (error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { + return Promise.reject(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 {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 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 (!password || typeof password.valueOf() !== "string") { - throw new Error("password must be a non empty string."); + if (!certificateStringOrFilePath.startsWith("-----BEGIN")) { + certificateStringOrFilePath = fs_1.readFileSync(certificateStringOrFilePath, "utf8"); } - super(clientId, domain, tokenAudience, environment, tokenCache); - this.username = username; - this.password = password; + 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); } - 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()); +} +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. + * @constructor + * @param {string} clientId The active directory application client id. + * @param {string} domain The domain or tenant id containing this application. + * @param {string} secret The authentication secret for the application. + * @param {string} [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} [environment] The azure environment to authenticate with. + * @param {object} [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 unsuccessful then it tries to get the token from ADAL. - * @returns {Promise} - * {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties). - * @memberof UserTokenCredentials + * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL. + * @returns {Promise} 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(this.username); + const tokenResponse = yield this.getTokenFromCache(); + return tokenResponse; } catch (error) { - const self = this; + if (error.message && + error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) { + return Promise.reject(error); + } const resource = this.getActiveDirectoryResourceId(); return new Promise((resolve, reject) => { - self.authContext.acquireTokenWithUsernamePassword(resource, self.username, self.password, self.clientId, (error, tokenResponse) => { + this.authContext.acquireTokenWithClientCredentials(resource, this.clientId, this.secret, (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.`); - } + return resolve(tokenResponse); }); }); } }); } } -exports.UserTokenCredentials = UserTokenCredentials; -//# sourceMappingURL=userTokenCredentials.js.map +exports.ApplicationTokenCredentials = ApplicationTokenCredentials; +//# sourceMappingURL=applicationTokenCredentials.js.map /***/ }), -/***/ 29325: +/***/ 60968: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -8512,177 +8706,1177 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const adal = __nccwpck_require__(35894); -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 tokenCredentialsBase_1 = __nccwpck_require__(5558); const authConstants_1 = __nccwpck_require__(26700); -const subscriptionUtils_1 = __nccwpck_require__(47813); -const msiVmTokenCredentials_1 = __nccwpck_require__(73287); -const msiAppServiceTokenCredentials_1 = __nccwpck_require__(68376); -/** - * @constant {Array} managementPlaneTokenAudiences - Urls for management plane token - * audience across different azure environments. - */ -const managementPlaneTokenAudiences = [ - "https://management.core.windows.net/", - "https://management.core.chinacloudapi.cn/", - "https://management.core.usgovcloudapi.net/", - "https://management.core.cloudapi.de/", - "https://management.azure.com/", - "https://management.core.windows.net", - "https://management.core.chinacloudapi.cn", - "https://management.core.usgovcloudapi.net", - "https://management.core.cloudapi.de", - "https://management.azure.com" -]; -function turnOnLogging() { - const log = adal.Logging; - log.setLoggingOptions({ - level: 3, - log: function (level, message, error) { - level; - console.info(message); - if (error) { - console.error(error); +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. + * @constructor + * @param {string} clientId The active directory application client id. + * @param {string} domain The domain or tenant id containing this application. + * @param {string} [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} [environment] The azure environment to authenticate with. + * @param {object} [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* () { + const self = this; + // a thin wrapper over the base implementation. try get token from cache, additionaly clean up cache if required. + try { + const tokenResponse = yield _super.getTokenFromCache.call(this, undefined); + return Promise.resolve(tokenResponse); } - } - }); -} -if (process.env["AZURE_ADAL_LOGGING_ENABLED"]) { - turnOnLogging(); -} -/** - * 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. - * - * @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 {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 {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* () { - if (!options) { - options = {}; - } - if (!options.clientId) { - options.clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID; - } - if (!options.domain) { - options.domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT; - } - if (!options.environment) { - options.environment = ms_rest_azure_env_1.Environment.AzureCloud; - } - 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); - } - return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); - }); + 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 self.removeInvalidItemsFromCache({ + _clientId: self.clientId + }); + if (status.result) { + return Promise.reject(error); + } + const message = status && status.details && status.details.message + ? status.details.message + : status.details; + return Promise.reject(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 {object} query The query to be used for finding the token for service principal from the cache + * @returns {result: boolean, details?: Error} 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 new Promise(resolve => { + return self.tokenCache.remove(entries, (err) => { + if (err) { + return resolve({ result: false, details: err }); + } + return resolve({ result: true }); + }); + }); + } + else { + return resolve({ result: true }); + } + }); + }); + } } -exports.withUsernamePasswordWithAuthResponse = withUsernamePasswordWithAuthResponse; -/** - * Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants. - * - * @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 {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 {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* () { - if (!options) { - options = {}; - } - if (!options.environment) { - options.environment = ms_rest_azure_env_1.Environment.AzureCloud; - } - 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.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()); }); -} -exports.withServicePrincipalSecretWithAuthResponse = withServicePrincipalSecretWithAuthResponse; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const ms_rest_js_1 = __nccwpck_require__(30812); +const login_1 = __nccwpck_require__(29325); /** - * Provides an ApplicationTokenCertificateCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants. - * - * @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 {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 {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 {Promise} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error. + * Describes the credentials by retrieving token via Azure CLI. */ -function withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options) { - return __awaiter(this, void 0, void 0, function* () { - if (!options) { - options = {}; - } - if (!options.environment) { - options.environment = ms_rest_azure_env_1.Environment.AzureCloud; +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. + * @return 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 Promise.resolve(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; } - let creds; - let subscriptionList = []; + return result; + } + _hasSubscriptionChanged() { + return this.subscriptionInfo.id !== this.tokenInfo.subscription; + } + _parseToken() { try { - creds = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials.create(clientId, certificateStringOrFilePath, domain, options); - yield creds.getToken(); - subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience); + 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) { - return Promise.reject(err); + const msg = `An error occurred while parsing the access token: ${err.stack}`; + throw new Error(msg); } - return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); - }); -} + } + _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 { + let cmd = "account get-access-token"; + if (options.subscriptionIdOrName) { + cmd += ` -s "${options.subscriptionIdOrName}"`; + } + if (options.resource) { + cmd += ` --resource ${options.resource}`; + } + const result = yield login_1.execAz(cmd); + 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 { + let cmd = "account show"; + if (subscriptionIdOrName) { + cmd += ` -s "${subscriptionIdOrName}"`; + } + const result = yield login_1.execAz(cmd); + 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 { + let cmd = "account list"; + if (options.all) { + cmd += " --all"; + } + if (options.refresh) { + cmd += "--refresh"; + } + subscriptionList = yield login_1.execAz(cmd); + 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. + * + * @constructor + * @param {string} [clientId] The active directory application client id. + * @param {string} [domain] The domain or tenant id containing this application. Default value is "common" + * @param {string} [username] The user name for account in the form: "user@example.com". + * @param {string} [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} [environment] The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud". + * @param {object} [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); +/** + * @class MSIAppServiceTokenCredentials + */ +class MSIAppServiceTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials { + /** + * Creates an instance of MSIAppServiceTokenCredentials. + * @param {string} [options.msiEndpoint] - The local URL from which your app can request tokens. + * Either provide this parameter or set the environment variable `MSI_ENDPOINT`. + * For example: `MSI_ENDPOINT="http://127.0.0.1:41741/MSI/token/"` + * @param {string} [options.msiSecret] - The secret used in communication between your code and the local MSI agent. + * Either provide this parameter or set the environment variable `MSI_SECRET`. + * For example: `MSI_SECRET="69418689F1E342DD946CB82994CDA3CB"` + * @param {string} [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 {string} [options.msiApiVersion] - The api-version of the local MSI agent. Default value is "2017-09-01". + */ + constructor(options) { + if (!options) + options = {}; + super(options); + options.msiEndpoint = options.msiEndpoint || process.env["MSI_ENDPOINT"]; + options.msiSecret = options.msiSecret || 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 "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 "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; + } + /** + * Prepares and sends a GET request to a service endpoint indicated by the app service, which responds with the access token. + * @return {Promise} 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(); + let opRes; + let result; + 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}`); + } + 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 resource = encodeURIComponent(this.resource); + const getUrl = `${endpoint}?resource=${resource}&api-version=${this.msiApiVersion}`; + const reqOptions = { + url: getUrl, + headers: { + "secret": this.msiSecret + }, + 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); +/** + * @class MSITokenCredentials - 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 {object} [options] - Optional parameters + * @param {string} [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 {string} body A json string + * @return {object} [tokenResponse] 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(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. + * @return {Promise} 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 Promise.resolve(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); +/** + * @class MSIVmTokenCredentials + */ +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. + * @return {Promise} 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(); + let opRes; + let result; + opRes = yield this._httpClient.sendRequest(reqOptions); + 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 \"commmon\" tenant.\ + It must be the actual tenant (preferrably 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); + } + 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. + * @param {function(error)} callback The callback function. + * @return {undefined} + */ + 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 Promise.resolve(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. + * + * @constructor + * @param {string} 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 {string} domain The domain or tenant id containing this application. + * @param {string} username The user name for the Organization Id account. + * @param {string} password The password for the Organization Id account. + * @param {string} [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} [environment] The azure environment to authenticate with. + * @param {object} [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 {Promise} + * {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties). + * @memberof UserTokenCredentials + */ + 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: +/***/ (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 adal = __nccwpck_require__(35894); +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); +/** + * @constant {Array} managementPlaneTokenAudiences - Urls for management plane token + * audience across different azure environments. + */ +const managementPlaneTokenAudiences = [ + "https://management.core.windows.net/", + "https://management.core.chinacloudapi.cn/", + "https://management.core.usgovcloudapi.net/", + "https://management.core.cloudapi.de/", + "https://management.azure.com/", + "https://management.core.windows.net", + "https://management.core.chinacloudapi.cn", + "https://management.core.usgovcloudapi.net", + "https://management.core.cloudapi.de", + "https://management.azure.com" +]; +function turnOnLogging() { + const log = adal.Logging; + log.setLoggingOptions({ + level: 3, + log: function (level, message, error) { + level; + console.info(message); + if (error) { + console.error(error); + } + } + }); +} +if (process.env["AZURE_ADAL_LOGGING_ENABLED"]) { + turnOnLogging(); +} +/** + * 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. + * + * @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 {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 {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* () { + if (!options) { + options = {}; + } + if (!options.clientId) { + options.clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID; + } + if (!options.domain) { + options.domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT; + } + if (!options.environment) { + options.environment = ms_rest_azure_env_1.Environment.AzureCloud; + } + 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); + } + return Promise.resolve({ credentials: creds, subscriptions: subscriptionList }); + }); +} +exports.withUsernamePasswordWithAuthResponse = withUsernamePasswordWithAuthResponse; +/** + * Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants. + * + * @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 {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 {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* () { + if (!options) { + options = {}; + } + if (!options.environment) { + options.environment = ms_rest_azure_env_1.Environment.AzureCloud; + } + 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 servicePrinicpalId/clientId across all the applicable tenants. + * + * @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 {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 {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 {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* () { + if (!options) { + options = {}; + } + if (!options.environment) { + options.environment = ms_rest_azure_env_1.Environment.AzureCloud; + } + 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; function validateAuthFileContent(credsObj, filePath) { if (!credsObj) { @@ -9355,24934 +10549,28921 @@ exports.AuthConstants = { /***/ }), -/***/ 48566: -/***/ ((module, exports) => { +/***/ 5128: +/***/ ((module, exports, __nccwpck_require__) => { -module.exports = exports = abbrev.abbrev = abbrev +"use strict"; -abbrev.monkeyPatch = monkeyPatch -function monkeyPatch () { - Object.defineProperty(Array.prototype, 'abbrev', { - value: function () { return abbrev(this) }, - enumerable: false, configurable: true, writable: true - }) +/** + * Module exports. + */ - Object.defineProperty(Object.prototype, 'abbrev', { - value: function () { return abbrev(Object.keys(this)) }, - enumerable: false, configurable: true, writable: true - }) +module.exports = exports; + +/** + * Module dependencies. + */ + +// load mocking control function for accessing s3 via https. the function is a noop always returning +// false if not mocking. +exports.mockS3Http = __nccwpck_require__(89474).get_mockS3Http(); +exports.mockS3Http('on'); +const mocking = exports.mockS3Http('get'); + + +const fs = __nccwpck_require__(35747); +const path = __nccwpck_require__(85622); +const nopt = __nccwpck_require__(9087); +const log = __nccwpck_require__(64314); +log.disableProgress(); +const napi = __nccwpck_require__(80942); + +const EE = __nccwpck_require__(28614).EventEmitter; +const inherits = __nccwpck_require__(31669).inherits; +const cli_commands = [ + 'clean', + 'install', + 'reinstall', + 'build', + 'rebuild', + 'package', + 'testpackage', + 'publish', + 'unpublish', + 'info', + 'testbinary', + 'reveal', + 'configure' +]; +const aliases = {}; + +// differentiate node-pre-gyp's logs from npm's +log.heading = 'node-pre-gyp'; + +if (mocking) { + log.warn(`mocking s3 to ${process.env.node_pre_gyp_mock_s3}`); } -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]) - } +// this is a getter to avoid circular reference warnings with node v14. +Object.defineProperty(exports, "find", ({ + get: function() { + return __nccwpck_require__(10813).find; + }, + enumerable: true +})); - // sort them lexicographically, so that they're next to their nearest kin - args = args.sort(lexSort) +// in the following, "my_module" is using node-pre-gyp to +// prebuild and install pre-built binaries. "main_module" +// is using "my_module". +// +// "bin/node-pre-gyp" invokes Run() without a path. the +// expectation is that the working directory is the package +// root "my_module". this is true because in all cases npm is +// executing a script in the context of "my_module". +// +// "pre-binding.find()" is executed by "my_module" but in the +// context of "main_module". this is because "main_module" is +// executing and requires "my_module" which is then executing +// "pre-binding.find()" via "node-pre-gyp.find()", so the working +// directory is that of "main_module". +// +// that's why "find()" must pass the path to package.json. +// +function Run({ package_json_path = './package.json', argv }) { + this.package_json_path = package_json_path; + this.commands = {}; - // 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 - } + const self = this; + cli_commands.forEach((command) => { + self.commands[command] = function(argvx, callback) { + log.verbose('command', command, argvx); + return require('./' + command)(self, argvx, callback); + }; + }); + + this.parseArgv(argv); + + // this is set to true after the binary.host property was set to + // either staging_host or production_host. + this.binaryHostSet = false; +} +inherits(Run, EE); +exports.Run = Run; +const proto = Run.prototype; + +/** + * Export the contents of the package.json. + */ + +proto.package = __nccwpck_require__(56432); + +/** + * nopt configuration definitions + */ + +proto.configDefs = { + help: Boolean, // everywhere + arch: String, // 'configure' + debug: Boolean, // 'build' + directory: String, // bin + proxy: String, // 'install' + loglevel: String // everywhere +}; + +/** + * nopt shorthands + */ + +proto.shorthands = { + release: '--no-debug', + C: '--directory', + debug: '--debug', + j: '--jobs', + silent: '--loglevel=silent', + silly: '--loglevel=silly', + verbose: '--loglevel=verbose' +}; + +/** + * expose the command aliases for the bin file to use. + */ + +proto.aliases = aliases; + +/** + * Parses the given argv array and sets the 'opts', 'argv', + * 'command', and 'package_json' properties. + */ + +proto.parseArgv = function parseOpts(argv) { + this.opts = nopt(this.configDefs, this.shorthands, argv); + this.argv = this.opts.argv.remain.slice(); + const commands = this.todo = []; + + // create a copy of the argv array with aliases mapped + argv = this.argv.map((arg) => { + // is this an alias? + if (arg in this.aliases) { + arg = this.aliases[arg]; } - prev = current - if (j === cl) { - abbrevs[current] = current - continue + return arg; + }); + + // process the mapped args into "command" objects ("name" and "args" props) + argv.slice().forEach((arg) => { + if (arg in this.commands) { + const args = argv.splice(0, argv.indexOf(arg)); + argv.shift(); + if (commands.length > 0) { + commands[commands.length - 1].args = args; + } + commands.push({ name: arg, args: [] }); } - for (var a = current.substr(0, j) ; j <= cl ; j ++) { - abbrevs[a] = current - a += current.charAt(j) + }); + if (commands.length > 0) { + commands[commands.length - 1].args = argv.splice(0); + } + + + // if a directory was specified package.json is assumed to be relative + // to it. + let package_json_path = this.package_json_path; + if (this.opts.directory) { + package_json_path = path.join(this.opts.directory, package_json_path); + } + + this.package_json = JSON.parse(fs.readFileSync(package_json_path)); + + // expand commands entries for multiple napi builds + this.todo = napi.expand_commands(this.package_json, this.opts, commands); + + // support for inheriting config env variables from npm + const npm_config_prefix = 'npm_config_'; + Object.keys(process.env).forEach((name) => { + if (name.indexOf(npm_config_prefix) !== 0) return; + const val = process.env[name]; + if (name === npm_config_prefix + 'loglevel') { + log.level = val; + } else { + // add the user-defined options to the config + name = name.substring(npm_config_prefix.length); + // avoid npm argv clobber already present args + // which avoids problem of 'npm test' calling + // script that runs unique npm install commands + if (name === 'argv') { + if (this.opts.argv && + this.opts.argv.remain && + this.opts.argv.remain.length) { + // do nothing + } else { + this.opts[name] = val; + } + } else { + this.opts[name] = val; + } } + }); + + if (this.opts.loglevel) { + log.level = this.opts.loglevel; } - return abbrevs -} + log.resume(); +}; -function lexSort (a, b) { - return a === b ? 0 : a > b ? 1 : -1 -} +/** + * allow the binary.host property to be set at execution time. + * + * for this to take effect requires all the following to be true. + * - binary is a property in package.json + * - binary.host is falsey + * - binary.staging_host is not empty + * - binary.production_host is not empty + * + * if any of the previous checks fail then the function returns an empty string + * and makes no changes to package.json's binary property. + * + * + * if command is "publish" then the default is set to "binary.staging_host" + * if command is not "publish" the the default is set to "binary.production_host" + * + * if the command-line option '--s3_host' is set to "staging" or "production" then + * "binary.host" is set to the specified "staging_host" or "production_host". if + * '--s3_host' is any other value an exception is thrown. + * + * if '--s3_host' is not present then "binary.host" is set to the default as above. + * + * this strategy was chosen so that any command other than "publish" or "unpublish" uses "production" + * as the default without requiring any command-line options but that "publish" and "unpublish" require + * '--s3_host production_host' to be specified in order to *really* publish (or unpublish). publishing + * to staging can be done freely without worrying about disturbing any production releases. + */ +proto.setBinaryHostProperty = function(command) { + if (this.binaryHostSet) { + return this.package_json.binary.host; + } + const p = this.package_json; + // don't set anything if host is present. it must be left blank to trigger this. + if (!p || !p.binary || p.binary.host) { + return ''; + } + // and both staging and production must be present. errors will be reported later. + if (!p.binary.staging_host || !p.binary.production_host) { + return ''; + } + let target = 'production_host'; + if (command === 'publish' || command === 'unpublish') { + target = 'staging_host'; + } + // the environment variable has priority over the default or the command line. if + // either the env var or the command line option are invalid throw an error. + const npg_s3_host = process.env.node_pre_gyp_s3_host; + if (npg_s3_host === 'staging' || npg_s3_host === 'production') { + target = `${npg_s3_host}_host`; + } else if (this.opts['s3_host'] === 'staging' || this.opts['s3_host'] === 'production') { + target = `${this.opts['s3_host']}_host`; + } else if (this.opts['s3_host'] || npg_s3_host) { + throw new Error(`invalid s3_host ${this.opts['s3_host'] || npg_s3_host}`); + } + + p.binary.host = p.binary[target]; + this.binaryHostSet = true; + + return p.binary.host; +}; + +/** + * Returns the usage instructions for node-pre-gyp. + */ + +proto.usage = function usage() { + const str = [ + '', + ' Usage: node-pre-gyp [options]', + '', + ' where is one of:', + cli_commands.map((c) => { + return ' - ' + c + ' - ' + require('./' + c).usage; + }).join('\n'), + '', + 'node-pre-gyp@' + this.version + ' ' + path.resolve(__dirname, '..'), + 'node@' + process.versions.node + ].join('\n'); + return str; +}; + +/** + * Version number getter. + */ + +Object.defineProperty(proto, 'version', { + get: function() { + return this.package.version; + }, + enumerable: true +}); /***/ }), -/***/ 35894: +/***/ 10813: /***/ ((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; + + +const npg = __nccwpck_require__(5128); +const versioning = __nccwpck_require__(42704); +const napi = __nccwpck_require__(80942); +const existsSync = __nccwpck_require__(35747).existsSync || __nccwpck_require__(85622).existsSync; +const path = __nccwpck_require__(85622); + +module.exports = exports; + +exports.usage = 'Finds the require path for the node-pre-gyp installed module'; + +exports.validate = function(package_json, opts) { + versioning.validate_config(package_json, opts); +}; + +exports.find = function(package_json_path, opts) { + if (!existsSync(package_json_path)) { + throw new Error(package_json_path + 'does not exist'); + } + const prog = new npg.Run({ package_json_path, argv: process.argv }); + prog.setBinaryHostProperty(); + const package_json = prog.package_json; + + versioning.validate_config(package_json, opts); + let napi_build_version; + if (napi.get_napi_build_versions(package_json, opts)) { + napi_build_version = napi.get_best_napi_build_version(package_json, opts); + } + opts = opts || {}; + if (!opts.module_root) opts.module_root = path.dirname(package_json_path); + const meta = versioning.evaluate(package_json, opts, napi_build_version); + return meta.module; +}; /***/ }), -/***/ 62432: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 80942: +/***/ ((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 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; + + +const fs = __nccwpck_require__(35747); + +module.exports = exports; + +const versionArray = process.version + .substr(1) + .replace(/-.*$/, '') + .split('.') + .map((item) => { + return +item; + }); + +const napi_multiple_commands = [ + 'build', + 'clean', + 'configure', + 'package', + 'publish', + 'reveal', + 'testbinary', + 'testpackage', + 'unpublish' +]; + +const napi_build_version_tag = 'napi_build_version='; + +module.exports.get_napi_version = function() { + // returns the non-zero numeric napi version or undefined if napi is not supported. + // correctly supporting target requires an updated cross-walk + let version = process.versions.napi; // can be undefined + if (!version) { // this code should never need to be updated + if (versionArray[0] === 9 && versionArray[1] >= 3) version = 2; // 9.3.0+ + else if (versionArray[0] === 8) version = 1; // 8.0.0+ + } + return version; +}; + +module.exports.get_napi_version_as_string = function(target) { + // returns the napi version as a string or an empty string if napi is not supported. + const version = module.exports.get_napi_version(target); + return version ? '' + version : ''; +}; + +module.exports.validate_package_json = function(package_json, opts) { // throws Error + + const binary = package_json.binary; + const module_path_ok = pathOK(binary.module_path); + const remote_path_ok = pathOK(binary.remote_path); + const package_name_ok = pathOK(binary.package_name); + const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts, true); + const napi_build_versions_raw = module.exports.get_napi_build_versions_raw(package_json); + + if (napi_build_versions) { + napi_build_versions.forEach((napi_build_version)=> { + if (!(parseInt(napi_build_version, 10) === napi_build_version && napi_build_version > 0)) { + throw new Error('All values specified in napi_versions must be positive integers.'); + } + }); + } + + if (napi_build_versions && (!module_path_ok || (!remote_path_ok && !package_name_ok))) { + throw new Error('When napi_versions is specified; module_path and either remote_path or ' + + "package_name must contain the substitution string '{napi_build_version}`."); + } + + if ((module_path_ok || remote_path_ok || package_name_ok) && !napi_build_versions_raw) { + throw new Error("When the substitution string '{napi_build_version}` is specified in " + + 'module_path, remote_path, or package_name; napi_versions must also be specified.'); + } + + if (napi_build_versions && !module.exports.get_best_napi_build_version(package_json, opts) && + module.exports.build_napi_only(package_json)) { + throw new Error( + 'The Node-API version of this Node instance is ' + module.exports.get_napi_version(opts ? opts.target : undefined) + '. ' + + 'This module supports Node-API version(s) ' + module.exports.get_napi_build_versions_raw(package_json) + '. ' + + 'This Node instance cannot run this module.'); + } + + if (napi_build_versions_raw && !napi_build_versions && module.exports.build_napi_only(package_json)) { + throw new Error( + 'The Node-API version of this Node instance is ' + module.exports.get_napi_version(opts ? opts.target : undefined) + '. ' + + 'This module supports Node-API version(s) ' + module.exports.get_napi_build_versions_raw(package_json) + '. ' + + 'This Node instance cannot run this module.'); + } + +}; + +function pathOK(path) { + return path && (path.indexOf('{napi_build_version}') !== -1 || path.indexOf('{node_napi_label}') !== -1); +} + +module.exports.expand_commands = function(package_json, opts, commands) { + const expanded_commands = []; + const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts); + commands.forEach((command)=> { + if (napi_build_versions && command.name === 'install') { + const napi_build_version = module.exports.get_best_napi_build_version(package_json, opts); + const args = napi_build_version ? [napi_build_version_tag + napi_build_version] : []; + expanded_commands.push({ name: command.name, args: args }); + } else if (napi_build_versions && napi_multiple_commands.indexOf(command.name) !== -1) { + napi_build_versions.forEach((napi_build_version)=> { + const args = command.args.slice(); + args.push(napi_build_version_tag + napi_build_version); + expanded_commands.push({ name: command.name, args: args }); + }); + } else { + expanded_commands.push(command); + } + }); + return expanded_commands; +}; + +module.exports.get_napi_build_versions = function(package_json, opts, warnings) { // opts may be undefined + const log = __nccwpck_require__(64314); + let napi_build_versions = []; + const supported_napi_version = module.exports.get_napi_version(opts ? opts.target : undefined); + // remove duplicates, verify each napi version can actaully be built + if (package_json.binary && package_json.binary.napi_versions) { + package_json.binary.napi_versions.forEach((napi_version) => { + const duplicated = napi_build_versions.indexOf(napi_version) !== -1; + if (!duplicated && supported_napi_version && napi_version <= supported_napi_version) { + napi_build_versions.push(napi_version); + } else if (warnings && !duplicated && supported_napi_version) { + log.info('This Node instance does not support builds for Node-API version', napi_version); + } + }); + } + if (opts && opts['build-latest-napi-version-only']) { + let latest_version = 0; + napi_build_versions.forEach((napi_version) => { + if (napi_version > latest_version) latest_version = napi_version; + }); + napi_build_versions = latest_version ? [latest_version] : []; + } + return napi_build_versions.length ? napi_build_versions : undefined; +}; + +module.exports.get_napi_build_versions_raw = function(package_json) { + const napi_build_versions = []; + // remove duplicates + if (package_json.binary && package_json.binary.napi_versions) { + package_json.binary.napi_versions.forEach((napi_version) => { + if (napi_build_versions.indexOf(napi_version) === -1) { + napi_build_versions.push(napi_version); + } + }); + } + return napi_build_versions.length ? napi_build_versions : undefined; +}; + +module.exports.get_command_arg = function(napi_build_version) { + return napi_build_version_tag + napi_build_version; +}; + +module.exports.get_napi_build_version_from_command_args = function(command_args) { + for (let i = 0; i < command_args.length; i++) { + const arg = command_args[i]; + if (arg.indexOf(napi_build_version_tag) === 0) { + return parseInt(arg.substr(napi_build_version_tag.length), 10); + } + } + return undefined; +}; + +module.exports.swap_build_dir_out = function(napi_build_version) { + if (napi_build_version) { + const rm = __nccwpck_require__(14959); + rm.sync(module.exports.get_build_dir(napi_build_version)); + fs.renameSync('build', module.exports.get_build_dir(napi_build_version)); + } +}; + +module.exports.swap_build_dir_in = function(napi_build_version) { + if (napi_build_version) { + const rm = __nccwpck_require__(14959); + rm.sync('build'); + fs.renameSync(module.exports.get_build_dir(napi_build_version), 'build'); + } +}; + +module.exports.get_build_dir = function(napi_build_version) { + return 'build-tmp-napi-v' + napi_build_version; +}; + +module.exports.get_best_napi_build_version = function(package_json, opts) { + let best_napi_build_version = 0; + const napi_build_versions = module.exports.get_napi_build_versions(package_json, opts); + if (napi_build_versions) { + const our_napi_version = module.exports.get_napi_version(opts ? opts.target : undefined); + napi_build_versions.forEach((napi_build_version)=> { + if (napi_build_version > best_napi_build_version && + napi_build_version <= our_napi_version) { + best_napi_build_version = napi_build_version; + } + }); + } + return best_napi_build_version === 0 ? undefined : best_napi_build_version; +}; + +module.exports.build_napi_only = function(package_json) { + return package_json.binary && package_json.binary.package_name && + package_json.binary.package_name.indexOf('{node_napi_label}') === -1; +}; /***/ }), -/***/ 69775: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 89474: +/***/ ((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 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; + + +module.exports = exports; + +const url = __nccwpck_require__(78835); +const fs = __nccwpck_require__(35747); +const path = __nccwpck_require__(85622); + +module.exports.detect = function(opts, config) { + const to = opts.hosted_path; + const uri = url.parse(to); + config.prefix = (!uri.pathname || uri.pathname === '/') ? '' : uri.pathname.replace('/', ''); + if (opts.bucket && opts.region) { + config.bucket = opts.bucket; + config.region = opts.region; + config.endpoint = opts.host; + config.s3ForcePathStyle = opts.s3ForcePathStyle; + } else { + const parts = uri.hostname.split('.s3'); + const bucket = parts[0]; + if (!bucket) { + return; + } + if (!config.bucket) { + config.bucket = bucket; + } + if (!config.region) { + const region = parts[1].slice(1).split('.')[0]; + if (region === 'amazonaws') { + config.region = 'us-east-1'; + } else { + config.region = region; + } + } + } +}; + +module.exports.get_s3 = function(config) { + + if (process.env.node_pre_gyp_mock_s3) { + // here we're mocking. node_pre_gyp_mock_s3 is the scratch directory + // for the mock code. + const AWSMock = __nccwpck_require__(68263); + const os = __nccwpck_require__(12087); + + AWSMock.config.basePath = `${os.tmpdir()}/mock`; + + const s3 = AWSMock.S3(); + + // wrapped callback maker. fs calls return code of ENOENT but AWS.S3 returns + // NotFound. + const wcb = (fn) => (err, ...args) => { + if (err && err.code === 'ENOENT') { + err.code = 'NotFound'; + } + return fn(err, ...args); + }; + + return { + listObjects(params, callback) { + return s3.listObjects(params, wcb(callback)); + }, + headObject(params, callback) { + return s3.headObject(params, wcb(callback)); + }, + deleteObject(params, callback) { + return s3.deleteObject(params, wcb(callback)); + }, + putObject(params, callback) { + return s3.putObject(params, wcb(callback)); + } + }; + } + + // if not mocking then setup real s3. + const AWS = __nccwpck_require__(20159); + + AWS.config.update(config); + const s3 = new AWS.S3(); + + // need to change if additional options need to be specified. + return { + listObjects(params, callback) { + return s3.listObjects(params, callback); + }, + headObject(params, callback) { + return s3.headObject(params, callback); + }, + deleteObject(params, callback) { + return s3.deleteObject(params, callback); + }, + putObject(params, callback) { + return s3.putObject(params, callback); + } + }; + + + +}; + +// +// function to get the mocking control function. if not mocking it returns a no-op. +// +// if mocking it sets up the mock http interceptors that use the mocked s3 file system +// to fulfill reponses. +module.exports.get_mockS3Http = function() { + let mock_s3 = false; + if (!process.env.node_pre_gyp_mock_s3) { + return () => mock_s3; + } + + const nock = __nccwpck_require__(21301); + // the bucket used for testing, as addressed by https. + const host = 'https://mapbox-node-pre-gyp-public-testing-bucket.s3.us-east-1.amazonaws.com'; + const mockDir = process.env.node_pre_gyp_mock_s3 + '/mapbox-node-pre-gyp-public-testing-bucket'; + + // function to setup interceptors. they are "turned off" by setting mock_s3 to false. + const mock_http = () => { + // eslint-disable-next-line no-unused-vars + function get(uri, requestBody) { + const filepath = path.join(mockDir, uri.replace('%2B', '+')); + + try { + fs.accessSync(filepath, fs.constants.R_OK); + } catch (e) { + return [404, 'not found\n']; + } + + // the mock s3 functions just write to disk, so just read from it. + return [200, fs.createReadStream(filepath)]; + } + + // eslint-disable-next-line no-unused-vars + return nock(host) + .persist() + .get(() => mock_s3) // mock any uri for s3 when true + .reply(get); + }; + + // setup interceptors. they check the mock_s3 flag to determine whether to intercept. + mock_http(nock, host, mockDir); + // function to turn matching all requests to s3 on/off. + const mockS3Http = (action) => { + const previous = mock_s3; + if (action === 'off') { + mock_s3 = false; + } else if (action === 'on') { + mock_s3 = true; + } else if (action !== 'get') { + throw new Error(`illegal action for setMockHttp ${action}`); + } + return previous; + }; + + // call mockS3Http with the argument + // - 'on' - turn it on + // - 'off' - turn it off (used by fetch.test.js so it doesn't interfere with redirects) + // - 'get' - return true or false for 'on' or 'off' + return mockS3Http; +}; + + + /***/ }), -/***/ 74854: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 42704: +/***/ ((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 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; +const path = __nccwpck_require__(85622); +const semver = __nccwpck_require__(73027); +const url = __nccwpck_require__(78835); +const detect_libc = __nccwpck_require__(34889); +const napi = __nccwpck_require__(80942); + +let abi_crosswalk; + +// This is used for unit testing to provide a fake +// ABI crosswalk that emulates one that is not updated +// for the current version +if (process.env.NODE_PRE_GYP_ABI_CROSSWALK) { + abi_crosswalk = require(process.env.NODE_PRE_GYP_ABI_CROSSWALK); +} else { + abi_crosswalk = __nccwpck_require__(41427); +} + +const major_versions = {}; +Object.keys(abi_crosswalk).forEach((v) => { + const major = v.split('.')[0]; + if (!major_versions[major]) { + major_versions[major] = v; + } +}); + +function get_electron_abi(runtime, target_version) { + if (!runtime) { + throw new Error('get_electron_abi requires valid runtime arg'); + } + if (typeof target_version === 'undefined') { + // erroneous CLI call + throw new Error('Empty target version is not supported if electron is the target.'); + } + // Electron guarantees that patch version update won't break native modules. + const sem_ver = semver.parse(target_version); + return runtime + '-v' + sem_ver.major + '.' + sem_ver.minor; +} +module.exports.get_electron_abi = get_electron_abi; + +function get_node_webkit_abi(runtime, target_version) { + if (!runtime) { + throw new Error('get_node_webkit_abi requires valid runtime arg'); + } + if (typeof target_version === 'undefined') { + // erroneous CLI call + throw new Error('Empty target version is not supported if node-webkit is the target.'); + } + return runtime + '-v' + target_version; +} +module.exports.get_node_webkit_abi = get_node_webkit_abi; + +function get_node_abi(runtime, versions) { + if (!runtime) { + throw new Error('get_node_abi requires valid runtime arg'); + } + if (!versions) { + throw new Error('get_node_abi requires valid process.versions object'); + } + const sem_ver = semver.parse(versions.node); + if (sem_ver.major === 0 && sem_ver.minor % 2) { // odd series + // https://github.com/mapbox/node-pre-gyp/issues/124 + return runtime + '-v' + versions.node; + } else { + // process.versions.modules added in >= v0.10.4 and v0.11.7 + // https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e + return versions.modules ? runtime + '-v' + (+versions.modules) : + 'v8-' + versions.v8.split('.').slice(0, 2).join('.'); + } +} +module.exports.get_node_abi = get_node_abi; + +function get_runtime_abi(runtime, target_version) { + if (!runtime) { + throw new Error('get_runtime_abi requires valid runtime arg'); + } + if (runtime === 'node-webkit') { + return get_node_webkit_abi(runtime, target_version || process.versions['node-webkit']); + } else if (runtime === 'electron') { + return get_electron_abi(runtime, target_version || process.versions.electron); + } else { + if (runtime !== 'node') { + throw new Error("Unknown Runtime: '" + runtime + "'"); + } + if (!target_version) { + return get_node_abi(runtime, process.versions); + } else { + let cross_obj; + // abi_crosswalk generated with ./scripts/abi_crosswalk.js + if (abi_crosswalk[target_version]) { + cross_obj = abi_crosswalk[target_version]; + } else { + const target_parts = target_version.split('.').map((i) => { return +i; }); + if (target_parts.length !== 3) { // parse failed + throw new Error('Unknown target version: ' + target_version); + } + /* + The below code tries to infer the last known ABI compatible version + that we have recorded in the abi_crosswalk.json when an exact match + is not possible. The reasons for this to exist are complicated: + + - We support passing --target to be able to allow developers to package binaries for versions of node + that are not the same one as they are running. This might also be used in combination with the + --target_arch or --target_platform flags to also package binaries for alternative platforms + - When --target is passed we can't therefore determine the ABI (process.versions.modules) from the node + version that is running in memory + - So, therefore node-pre-gyp keeps an "ABI crosswalk" (lib/util/abi_crosswalk.json) to be able to look + this info up for all versions + - But we cannot easily predict what the future ABI will be for released versions + - And node-pre-gyp needs to be a `bundledDependency` in apps that depend on it in order to work correctly + by being fully available at install time. + - So, the speed of node releases and the bundled nature of node-pre-gyp mean that a new node-pre-gyp release + need to happen for every node.js/io.js/node-webkit/nw.js/atom-shell/etc release that might come online if + you want the `--target` flag to keep working for the latest version + - Which is impractical ^^ + - Hence the below code guesses about future ABI to make the need to update node-pre-gyp less demanding. + + In practice then you can have a dependency of your app like `node-sqlite3` that bundles a `node-pre-gyp` that + only knows about node v0.10.33 in the `abi_crosswalk.json` but target node v0.10.34 (which is assumed to be + ABI compatible with v0.10.33). + + TODO: use semver module instead of custom version parsing + */ + const major = target_parts[0]; + let minor = target_parts[1]; + let patch = target_parts[2]; + // io.js: yeah if node.js ever releases 1.x this will break + // but that is unlikely to happen: https://github.com/iojs/io.js/pull/253#issuecomment-69432616 + if (major === 1) { + // look for last release that is the same major version + // e.g. we assume io.js 1.x is ABI compatible with >= 1.0.0 + while (true) { + if (minor > 0) --minor; + if (patch > 0) --patch; + const new_iojs_target = '' + major + '.' + minor + '.' + patch; + if (abi_crosswalk[new_iojs_target]) { + cross_obj = abi_crosswalk[new_iojs_target]; + console.log('Warning: node-pre-gyp could not find exact match for ' + target_version); + console.log('Warning: but node-pre-gyp successfully choose ' + new_iojs_target + ' as ABI compatible target'); + break; + } + if (minor === 0 && patch === 0) { + break; + } + } + } else if (major >= 2) { + // look for last release that is the same major version + if (major_versions[major]) { + cross_obj = abi_crosswalk[major_versions[major]]; + console.log('Warning: node-pre-gyp could not find exact match for ' + target_version); + console.log('Warning: but node-pre-gyp successfully choose ' + major_versions[major] + ' as ABI compatible target'); + } + } else if (major === 0) { // node.js + if (target_parts[1] % 2 === 0) { // for stable/even node.js series + // look for the last release that is the same minor release + // e.g. we assume node 0.10.x is ABI compatible with >= 0.10.0 + while (--patch > 0) { + const new_node_target = '' + major + '.' + minor + '.' + patch; + if (abi_crosswalk[new_node_target]) { + cross_obj = abi_crosswalk[new_node_target]; + console.log('Warning: node-pre-gyp could not find exact match for ' + target_version); + console.log('Warning: but node-pre-gyp successfully choose ' + new_node_target + ' as ABI compatible target'); + break; + } + } + } + } + } + if (!cross_obj) { + throw new Error('Unsupported target version: ' + target_version); + } + // emulate process.versions + const versions_obj = { + node: target_version, + v8: cross_obj.v8 + '.0', + // abi_crosswalk uses 1 for node versions lacking process.versions.modules + // process.versions.modules added in >= v0.10.4 and v0.11.7 + modules: cross_obj.node_abi > 1 ? cross_obj.node_abi : undefined + }; + return get_node_abi(runtime, versions_obj); + } + } +} +module.exports.get_runtime_abi = get_runtime_abi; + +const required_parameters = [ + 'module_name', + 'module_path', + 'host' +]; + +function validate_config(package_json, opts) { + const msg = package_json.name + ' package.json is not node-pre-gyp ready:\n'; + const missing = []; + if (!package_json.main) { + missing.push('main'); + } + if (!package_json.version) { + missing.push('version'); + } + if (!package_json.name) { + missing.push('name'); + } + if (!package_json.binary) { + missing.push('binary'); + } + const o = package_json.binary; + if (o) { + required_parameters.forEach((p) => { + if (!o[p] || typeof o[p] !== 'string') { + missing.push('binary.' + p); + } + }); + } + + if (missing.length >= 1) { + throw new Error(msg + 'package.json must declare these properties: \n' + missing.join('\n')); + } + if (o) { + // enforce https over http + const protocol = url.parse(o.host).protocol; + if (protocol === 'http:') { + throw new Error("'host' protocol (" + protocol + ") is invalid - only 'https:' is accepted"); + } + } + napi.validate_package_json(package_json, opts); +} + +module.exports.validate_config = validate_config; + +function eval_template(template, opts) { + Object.keys(opts).forEach((key) => { + const pattern = '{' + key + '}'; + while (template.indexOf(pattern) > -1) { + template = template.replace(pattern, opts[key]); + } + }); + return template; +} + +// url.resolve needs single trailing slash +// to behave correctly, otherwise a double slash +// may end up in the url which breaks requests +// and a lacking slash may not lead to proper joining +function fix_slashes(pathname) { + if (pathname.slice(-1) !== '/') { + return pathname + '/'; + } + return pathname; +} + +// remove double slashes +// note: path.normalize will not work because +// it will convert forward to back slashes +function drop_double_slashes(pathname) { + return pathname.replace(/\/\//g, '/'); +} + +function get_process_runtime(versions) { + let runtime = 'node'; + if (versions['node-webkit']) { + runtime = 'node-webkit'; + } else if (versions.electron) { + runtime = 'electron'; + } + return runtime; +} + +module.exports.get_process_runtime = get_process_runtime; + +const default_package_name = '{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz'; +const default_remote_path = ''; + +module.exports.evaluate = function(package_json, options, napi_build_version) { + options = options || {}; + validate_config(package_json, options); // options is a suitable substitute for opts in this case + const v = package_json.version; + const module_version = semver.parse(v); + const runtime = options.runtime || get_process_runtime(process.versions); + const opts = { + name: package_json.name, + configuration: options.debug ? 'Debug' : 'Release', + debug: options.debug, + module_name: package_json.binary.module_name, + version: module_version.version, + prerelease: module_version.prerelease.length ? module_version.prerelease.join('.') : '', + build: module_version.build.length ? module_version.build.join('.') : '', + major: module_version.major, + minor: module_version.minor, + patch: module_version.patch, + runtime: runtime, + node_abi: get_runtime_abi(runtime, options.target), + node_abi_napi: napi.get_napi_version(options.target) ? 'napi' : get_runtime_abi(runtime, options.target), + napi_version: napi.get_napi_version(options.target), // non-zero numeric, undefined if unsupported + napi_build_version: napi_build_version || '', + node_napi_label: napi_build_version ? 'napi-v' + napi_build_version : get_runtime_abi(runtime, options.target), + target: options.target || '', + platform: options.target_platform || process.platform, + target_platform: options.target_platform || process.platform, + arch: options.target_arch || process.arch, + target_arch: options.target_arch || process.arch, + libc: options.target_libc || detect_libc.familySync() || 'unknown', + module_main: package_json.main, + toolset: options.toolset || '', // address https://github.com/mapbox/node-pre-gyp/issues/119 + bucket: package_json.binary.bucket, + region: package_json.binary.region, + s3ForcePathStyle: package_json.binary.s3ForcePathStyle || false + }; + // support host mirror with npm config `--{module_name}_binary_host_mirror` + // e.g.: https://github.com/node-inspector/v8-profiler/blob/master/package.json#L25 + // > npm install v8-profiler --profiler_binary_host_mirror=https://npm.taobao.org/mirrors/node-inspector/ + const validModuleName = opts.module_name.replace('-', '_'); + const host = process.env['npm_config_' + validModuleName + '_binary_host_mirror'] || package_json.binary.host; + opts.host = fix_slashes(eval_template(host, opts)); + opts.module_path = eval_template(package_json.binary.module_path, opts); + // now we resolve the module_path to ensure it is absolute so that binding.gyp variables work predictably + if (options.module_root) { + // resolve relative to known module root: works for pre-binding require + opts.module_path = path.join(options.module_root, opts.module_path); + } else { + // resolve relative to current working directory: works for node-pre-gyp commands + opts.module_path = path.resolve(opts.module_path); + } + opts.module = path.join(opts.module_path, opts.module_name + '.node'); + opts.remote_path = package_json.binary.remote_path ? drop_double_slashes(fix_slashes(eval_template(package_json.binary.remote_path, opts))) : default_remote_path; + const package_name = package_json.binary.package_name ? package_json.binary.package_name : default_package_name; + opts.package_name = eval_template(package_name, opts); + opts.staged_tarball = path.join('build/stage', opts.remote_path, opts.package_name); + opts.hosted_path = url.resolve(opts.host, opts.remote_path); + opts.hosted_tarball = url.resolve(opts.hosted_path, opts.package_name); + return opts; +}; + + /***/ }), -/***/ 19270: +/***/ 44035: /***/ ((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 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; +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + options = parseOptions(options) + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} + +module.exports = Comparator + +const parseOptions = __nccwpck_require__(63659) +const { re, t } = __nccwpck_require__(7162) +const cmp = __nccwpck_require__(92325) +const debug = __nccwpck_require__(61745) +const SemVer = __nccwpck_require__(39077) +const Range = __nccwpck_require__(27426) /***/ }), -/***/ 38289: +/***/ 27426: /***/ ((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; +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } -/***/ }), + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } -/***/ 66576: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + 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 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; + this.format() + } -/***/ }), + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim() + return this.range + } -/***/ 10282: -/***/ ((module) => { + toString () { + return this.range + } -"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; + parseRange (range) { + range = range.trim() + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } -/***/ }), + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) -/***/ 92288: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) -"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__(2155); // 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; + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) -/***/ }), + // normalize spaces + range = range.split(/\s+/).join(' ') -/***/ 92474: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // At this point, the range is completely trimmed and + // ready to be split into comparators. -"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; + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) -/***/ }), + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } -/***/ 27078: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } -"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; + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } -/***/ }), + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } -/***/ 41602: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } -"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__(2155); -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; + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} -/***/ }), +module.exports = Range -/***/ 60772: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const LRU = __nccwpck_require__(7129) +const cache = new LRU({ max: 1000 }) -"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__(2155); - -/** - * 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; +const parseOptions = __nccwpck_require__(63659) +const Comparator = __nccwpck_require__(44035) +const debug = __nccwpck_require__(61745) +const SemVer = __nccwpck_require__(39077) +const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = __nccwpck_require__(7162) +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(72054) + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) -/***/ }), + testComparator = remainingComparators.pop() + } -/***/ 21178: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return result +} -"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; +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' -/***/ }), +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((c) => { + return replaceTilde(c, options) + }).join(' ') -/***/ 58663: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret -"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 (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } -/***/ }), + debug('tilde return', ret) + return ret + }) +} -/***/ 5336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((c) => { + return replaceCaret(c, options) + }).join(' ') -"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; +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret -/***/ }), + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } -/***/ 39035: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + debug('caret return', ret) + return ret + }) +} -"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__(2155); - -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; +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map((c) => { + return replaceXRange(c, options) + }).join(' ') +} +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp -/***/ }), + if (gtlt === '=' && anyX) { + gtlt = '' + } -/***/ 55927: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-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 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; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 -/***/ }), + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } -/***/ 27387: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (gtlt === '<') { + pr = '-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 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; + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } -/***/ }), + debug('xRange return', ret) -/***/ 64941: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return ret + }) +} -"use strict"; +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp.trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} -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); +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } -module.exports = Ajv; + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } -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; + return (`${from} ${to}`).trim() +} -Ajv.prototype._addSchema = _addSchema; -Ajv.prototype._compile = _compile; +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } -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; + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } -var errorClasses = __nccwpck_require__(25726); -Ajv.ValidationError = errorClasses.Validation; -Ajv.MissingRefError = errorClasses.MissingRef; -Ajv.$dataMetaSchema = $dataMetaSchema; + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } -var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + // Version has a -pre, but it's not one of the ones we like. + return false + } -var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; -var META_SUPPORT_DATA = ['/properties']; + return true +} -/** - * 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); - this._cache = opts.cache || new Cache; - this._loadingSchemas = {}; - this._compilations = []; - this.RULES = rules(); - this._getId = chooseGetId(opts); +/***/ }), - opts.loopRequired = opts.loopRequired || Infinity; - if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; - if (opts.serialize === undefined) opts.serialize = stableStringify; - this._metaOpts = getMetaSchemaOptions(this); +/***/ 39077: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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); -} +const debug = __nccwpck_require__(61745) +const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(72054) +const { re, t } = __nccwpck_require__(7162) +const parseOptions = __nccwpck_require__(63659) +const { compareIdentifiers } = __nccwpck_require__(74077) +class SemVer { + constructor (version, options) { + options = parseOptions(options) + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) + } -/** - * 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); - } + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } - var valid = v(data); - if (v.$async !== true) this.errors = v.errors; - return valid; -} + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) -/** - * 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); -} + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + this.raw = version -/** - * 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 MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } -/** - * Add schema that will be used to validate other schemas - * options in META_IGNORE_OPTIONS are alway set to false - * @this Ajv - * @param {Object} schema schema object - * @param {String} key optional schema key - * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema - * @return {Ajv} this for method chaining - */ -function addMetaSchema(schema, key, skipValidation) { - this.addSchema(schema, key, skipValidation, true); - return this; -} + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } -/** - * 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; + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() } - 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); + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version } - return valid; -} + toString () { + return this.version + } -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; -} + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + if (other.version === this.version) { + return 0 + } -/** - * 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); + return this.compareMain(other) || this.comparePre(other) } -} + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -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 ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) } -} + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -function _getSchemaObj(self, keyRef) { - keyRef = resolve.normalizeId(keyRef); - return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; -} + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } -/** - * 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; + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) } - 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]; + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format() + this.raw = this.version + return this } - return this; } +module.exports = SemVer -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]; - } - } + +/***/ }), + +/***/ 34365: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const parse = __nccwpck_require__(37942) +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null } +module.exports = clean -/* @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; +/***/ }), - shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; +/***/ 92325: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var id = resolve.normalizeId(this._getId(schema)); - if (id && shouldAddSchema) checkUnique(this, id); +const eq = __nccwpck_require__(12052) +const neq = __nccwpck_require__(1052) +const gt = __nccwpck_require__(62975) +const gte = __nccwpck_require__(83332) +const lt = __nccwpck_require__(95125) +const lte = __nccwpck_require__(44958) - var willValidate = this._opts.validateSchema !== false && !skipValidation; - var recursiveMeta; - if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) - this.validateSchema(schema, true); +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b - var localRefs = resolve.ids.call(this, schema); + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b - var schemaObj = new SchemaObject({ - id: id, - schema: schema, - localRefs: localRefs, - cacheKey: cacheKey, - meta: meta - }); + case '': + case '=': + case '==': + return eq(a, b, loose) - if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; - this._cache.put(cacheKey, schemaObj); + case '!=': + return neq(a, b, loose) - if (willValidate && recursiveMeta) this.validateSchema(schema, true); + case '>': + return gt(a, b, loose) - return schemaObj; -} + case '>=': + return gte(a, b, loose) + case '<': + return lt(a, b, loose) -/* @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; + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) } - schemaObj.compiling = true; +} +module.exports = cmp - var currentOpts; - if (schemaObj.meta) { - currentOpts = this._opts; - this._opts = this._metaOpts; + +/***/ }), + +/***/ 97029: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(39077) +const parse = __nccwpck_require__(37942) +const { re, t } = __nccwpck_require__(7162) + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version } - var v; - try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); } - catch(e) { - delete schemaObj.validate; - throw e; + if (typeof version === 'number') { + version = String(version) } - finally { - schemaObj.compiling = false; - if (schemaObj.meta) this._opts = currentOpts; + + if (typeof version !== 'string') { + return null } - schemaObj.validate = v; - schemaObj.refs = v.refs; - schemaObj.refVal = v.refVal; - schemaObj.root = v.root; - return v; + options = options || {} + let match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } - /* @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; + if (match === null) { + return null } + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } +module.exports = coerce -function chooseGetId(opts) { - switch (opts.schemaId) { - case 'auto': return _get$IdOrId; - case 'id': return _getId; - default: return _get$Id; - } -} +/***/ }), -/* @this Ajv */ -function _getId(schema) { - if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); - return schema.id; -} +/***/ 35072: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* @this Ajv */ -function _get$Id(schema) { - if (schema.id) this.logger.warn('schema id ignored', schema.id); - return schema.$id; +const SemVer = __nccwpck_require__(39077) +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) } +module.exports = compareBuild -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; -} +/***/ }), +/***/ 97594: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * 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; +const compare = __nccwpck_require__(7345) +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose - var text = ''; - for (var i=0; i { +const SemVer = __nccwpck_require__(39077) +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) -function addDefaultMetaSchema(self) { - var $dataSchema; - if (self._opts.$data) { - $dataSchema = __nccwpck_require__(66835); - self.addMetaSchema($dataSchema, $dataSchema.$id, true); - } - if (self._opts.meta === false) return; - var metaSchema = __nccwpck_require__(40038); - if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); - self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); - self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; -} +module.exports = compare -function addInitialSchemas(self) { - var optsSchemas = self._opts.schemas; - if (!optsSchemas) return; - if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas); - else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key); -} +/***/ }), +/***/ 29371: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function addInitialFormats(self) { - for (var name in self._opts.formats) { - var format = self._opts.formats[name]; - self.addFormat(name, format); +const parse = __nccwpck_require__(37942) + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null } -} + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length -function addInitialKeywords(self) { - for (var name in self._opts.keywords) { - var keyword = self._opts.keywords[name]; - self.addKeyword(name, keyword); + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' } -} + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } -function checkUnique(self, id) { - if (self._schemas[id] || self._refs[id]) - throw new Error('schema with key or id "' + id + '" already exists'); -} + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + // at this point we know stable versions match but overall versions are not equal, + // so either they are both prereleases, or the lower version is a prerelease -function getMetaSchemaOptions(self) { - var metaOpts = util.copy(self._opts); - for (var i=0; i { +/***/ 12052: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const compare = __nccwpck_require__(7345) +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq +/***/ }), -var Cache = module.exports = function Cache() { - this._cache = {}; -}; +/***/ 62975: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const compare = __nccwpck_require__(7345) +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt -Cache.prototype.put = function Cache_put(key, value) { - this._cache[key] = value; -}; +/***/ }), -Cache.prototype.get = function Cache_get(key) { - return this._cache[key]; -}; +/***/ 83332: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const compare = __nccwpck_require__(7345) +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte -Cache.prototype.del = function Cache_del(key) { - delete this._cache[key]; -}; +/***/ }), -Cache.prototype.clear = function Cache_clear() { - this._cache = {}; -}; +/***/ 17438: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(39077) + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc /***/ }), -/***/ 80890: +/***/ 95125: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const compare = __nccwpck_require__(7345) +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt -var MissingRefError = __nccwpck_require__(25726).MissingRef; +/***/ }), -module.exports = compileAsync; +/***/ 44958: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const compare = __nccwpck_require__(7345) +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte -/** - * 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 (typeof meta == 'function') { - callback = meta; - meta = undefined; - } +/***/ }), - var p = loadMetaSchemaOf(schema).then(function () { - var schemaObj = self._addSchema(schema, undefined, meta); - return schemaObj.validate || _compileAsync(schemaObj); - }); +/***/ 80959: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (callback) { - p.then( - function(v) { callback(null, v); }, - callback - ); - } +const SemVer = __nccwpck_require__(39077) +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major - return p; +/***/ }), - function loadMetaSchemaOf(sch) { - var $schema = sch.$schema; - return $schema && !self.getSchema($schema) - ? compileAsync.call(self, { $ref: $schema }, true) - : Promise.resolve(); - } +/***/ 12608: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const SemVer = __nccwpck_require__(39077) +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor - function _compileAsync(schemaObj) { - try { return self._compile(schemaObj); } - catch(e) { - if (e instanceof MissingRefError) return loadMissingSchema(e); - throw e; - } +/***/ }), - function loadMissingSchema(e) { - var ref = e.missingSchema; - if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); +/***/ 1052: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var schemaPromise = self._loadingSchemas[ref]; - if (!schemaPromise) { - schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); - schemaPromise.then(removePromise, removePromise); - } +const compare = __nccwpck_require__(7345) +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq - 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); - }); - function removePromise() { - delete self._loadingSchemas[ref]; - } +/***/ }), - function added(ref) { - return self._refs[ref] || self._schemas[ref]; - } +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(39077) +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null } + throw er } } +module.exports = parse + /***/ }), -/***/ 25726: +/***/ 32412: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +const SemVer = __nccwpck_require__(39077) +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch -var resolve = __nccwpck_require__(63896); -module.exports = { - Validation: errorSubclass(ValidationError), - MissingRef: errorSubclass(MissingRefError) -}; +/***/ }), +/***/ 20148: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function ValidationError(errors) { - this.message = 'validation failed'; - this.errors = errors; - this.ajv = this.validation = true; +const parse = __nccwpck_require__(37942) +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } +module.exports = prerelease -MissingRefError.message = function (baseId, ref) { - return 'can\'t resolve reference ' + ref + ' from id ' + baseId; -}; +/***/ }), +/***/ 3267: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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)); -} +const compare = __nccwpck_require__(7345) +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare -function errorSubclass(Subclass) { - Subclass.prototype = Object.create(Error.prototype); - Subclass.prototype.constructor = Subclass; - return Subclass; -} +/***/ }), + +/***/ 73842: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compareBuild = __nccwpck_require__(35072) +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort /***/ }), -/***/ 66627: +/***/ 92867: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const Range = __nccwpck_require__(27426) +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies -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)*)*)$/; +/***/ 34997: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const compareBuild = __nccwpck_require__(35072) +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort -module.exports = formats; -function formats(mode) { - mode = mode == 'full' ? 'full' : 'fast'; - return util.copy(formats[mode]); +/***/ }), + +/***/ 58141: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const parse = __nccwpck_require__(37942) +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null } +module.exports = valid -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 -}; +/***/ }), +/***/ 73027: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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 -}; +// just pre-load all the stuff that index.js lazily exports +const internalRe = __nccwpck_require__(7162) +const constants = __nccwpck_require__(72054) +const SemVer = __nccwpck_require__(39077) +const identifiers = __nccwpck_require__(74077) +const parse = __nccwpck_require__(37942) +const valid = __nccwpck_require__(58141) +const clean = __nccwpck_require__(34365) +const inc = __nccwpck_require__(17438) +const diff = __nccwpck_require__(29371) +const major = __nccwpck_require__(80959) +const minor = __nccwpck_require__(12608) +const patch = __nccwpck_require__(32412) +const prerelease = __nccwpck_require__(20148) +const compare = __nccwpck_require__(7345) +const rcompare = __nccwpck_require__(3267) +const compareLoose = __nccwpck_require__(97594) +const compareBuild = __nccwpck_require__(35072) +const sort = __nccwpck_require__(34997) +const rsort = __nccwpck_require__(73842) +const gt = __nccwpck_require__(62975) +const lt = __nccwpck_require__(95125) +const eq = __nccwpck_require__(12052) +const neq = __nccwpck_require__(1052) +const gte = __nccwpck_require__(83332) +const lte = __nccwpck_require__(44958) +const cmp = __nccwpck_require__(92325) +const coerce = __nccwpck_require__(97029) +const Comparator = __nccwpck_require__(44035) +const Range = __nccwpck_require__(27426) +const satisfies = __nccwpck_require__(92867) +const toComparators = __nccwpck_require__(57343) +const maxSatisfying = __nccwpck_require__(72381) +const minSatisfying = __nccwpck_require__(2040) +const minVersion = __nccwpck_require__(95263) +const validRange = __nccwpck_require__(31524) +const outside = __nccwpck_require__(44295) +const gtr = __nccwpck_require__(55447) +const ltr = __nccwpck_require__(31681) +const intersects = __nccwpck_require__(66370) +const simplifyRange = __nccwpck_require__(99939) +const subset = __nccwpck_require__(68299) +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} + + +/***/ }), + +/***/ 72054: +/***/ ((module) => { + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 -function isLeapYear(year) { - // https://tools.ietf.org/html/rfc3339#appendix-C - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] + +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, } -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 year = +matches[1]; - var month = +matches[2]; - var day = +matches[3]; +/***/ 61745: +/***/ ((module) => { - return month >= 1 && month <= 12 && day >= 1 && - day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); -} +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} +module.exports = debug -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); -} +/***/ }), +/***/ 74077: +/***/ ((module) => { -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); -} +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + if (anum && bnum) { + a = +a + b = +b + } -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); + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 } +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) -var Z_ANCHOR = /[^\\]\\Z/; -function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch(e) { - return false; - } +module.exports = { + compareIdentifiers, + rcompareIdentifiers, } /***/ }), -/***/ 875: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 63659: +/***/ ((module) => { +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } -var resolve = __nccwpck_require__(63896) - , util = __nccwpck_require__(76578) - , errorClasses = __nccwpck_require__(25726) - , stableStringify = __nccwpck_require__(30969); + if (typeof options !== 'object') { + return looseOption + } -var validateGenerator = __nccwpck_require__(49585); + return options +} +module.exports = parseOptions -/** - * Functions below are used inside compiled validations function - */ -var ucs2length = util.ucs2length; -var equal = __nccwpck_require__(28206); +/***/ }), -// this error is thrown by async schemas to return validation errors via exception -var ValidationError = errorClasses.Validation; +/***/ 7162: +/***/ ((module, exports, __nccwpck_require__) => { -module.exports = compile; +const { MAX_SAFE_COMPONENT_LENGTH } = __nccwpck_require__(72054) +const debug = __nccwpck_require__(61745) +exports = module.exports = {} +// The actual regexps go on exports.re +const re = exports.re = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 -/** - * 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 = []; +const createToken = (name, value, isGlobal) => { + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) +} - root = root || { schema: schema, refVal: refVal, refs: refs }; +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. - var c = checkCompiling.call(this, schema, root, baseId); - var compilation = this._compilations[c.index]; - if (c.compiling) return (compilation.callValidate = callValidate); +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. - var formats = this._formats; - var RULES = this.RULES; +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') - 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); - } +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. - /* @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; - } +createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') - 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); +// ## Main Version +// Three dot-separated numeric identifiers. - var $async = _schema.$async === true; +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) - 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 - }); +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) - sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) - + vars(defaults, defaultCode) + vars(customRules, customRuleCode) - + sourceCode; +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. - 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 - ); +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) - validate = makeValidate( - self, - RULES, - formats, - root, - refVal, - defaults, - customRules, - equal, - ucs2length, - ValidationError - ); +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) - refVal[0] = validate; - } catch(e) { - self.logger.error('Error compiling schema, function code:', sourceCode); - throw e; - } +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. - 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 - }; - } +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) - return validate; - } +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) - 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); - } - } +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. - 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); - } - } +createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') - if (v === undefined) { - removeLocalRef(ref); - } else { - replaceLocalRef(ref, v); - return resolvedRef(v, refCode); - } - } +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. - function addLocalRef(ref, v) { - var refId = refVal.length; - refVal[refId] = v; - refs[ref] = refId; - return 'refVal' + refId; - } +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) - function removeLocalRef(ref) { - delete refs[ref]; - } +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. - function replaceLocalRef(ref, v) { - var refId = refs[ref]; - refVal[refId] = v; - } +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. - function resolvedRef(refVal, code) { - return typeof refVal == 'object' || typeof refVal == 'boolean' - ? { code: code, schema: refVal, inline: true } - : { code: code, $async: refVal && !!refVal.$async }; - } +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) - function usePattern(regexStr) { - var index = patternsHash[regexStr]; - if (index === undefined) { - index = patternsHash[regexStr] = patterns.length; - patterns[index] = regexStr; - } - return 'pattern' + index; - } +createToken('FULL', `^${src[t.FULLPLAIN]}$`) - 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; - } - } +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) - 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(',')); +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) - 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); - } - } - } +createToken('GTLT', '((?:<|>)?=?)') - var compile = rule.definition.compile - , inline = rule.definition.inline - , macro = rule.definition.macro; +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) - 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; - } +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) - if (validate === undefined) - throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') - var index = customRules.length; - customRules[index] = validate; +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' - return { - code: 'customRule' + index, - validate: validate - }; - } -} +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') -/** - * 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 }; -} +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) -/** - * 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); -} +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' -/** - * 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)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') -function defaultCode(i) { - return 'var default' + i + ' = defaults[' + i + '];'; -} +/***/ }), +/***/ 55447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function refValCode(i, refVal) { - return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];'; -} +// Determine if version is greater than all the versions possible in the range. +const outside = __nccwpck_require__(44295) +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr -function customRuleCode(i) { - return 'var customRule' + i + ' = customRules[' + i + '];'; -} +/***/ }), +/***/ 66370: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function vars(arr, statement) { - if (!arr.length) return ''; - var code = ''; - for (var i=0; i { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) } +module.exports = intersects /***/ }), -/***/ 63896: +/***/ 31681: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const outside = __nccwpck_require__(44295) +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr -var URI = __nccwpck_require__(70020) - , equal = __nccwpck_require__(28206) - , util = __nccwpck_require__(76578) - , SchemaObject = __nccwpck_require__(37605) - , traverse = __nccwpck_require__(52533); +/***/ }), -module.exports = resolve; +/***/ 72381: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -resolve.normalizeId = normalizeId; -resolve.fullPath = getFullPath; -resolve.url = resolveUrl; -resolve.ids = resolveIds; -resolve.inlineRef = inlineRef; -resolve.schema = resolveSchema; +const SemVer = __nccwpck_require__(39077) +const Range = __nccwpck_require__(27426) -/** - * [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); - } - - refVal = refVal || this._schemas[ref]; - if (refVal instanceof SchemaObject) { - return inlineRef(refVal.schema, this._opts.inlineRefs) - ? refVal.schema - : refVal.validate || this._compile(refVal); - } - - var res = resolveSchema.call(this, root, ref); - var schema, v, baseId; - if (res) { - schema = res.schema; - root = res.root; - baseId = res.baseId; - } - - 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); +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null } - - return v; -} - - -/** - * 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; + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) } } - if (!root.schema) return; - baseId = getFullPath(this._getId(root.schema)); - } - return getJsonPointer.call(this, p, baseId, root.schema, root); + }) + return max } +module.exports = maxSatisfying -/* @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); - } -} - +/***/ }), -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('/'); +/***/ 2040: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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; - } - } +const SemVer = __nccwpck_require__(39077) +const Range = __nccwpck_require__(27426) +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) } } - } - if (schema !== undefined && schema !== root.schema) - return { schema: schema, root: root, baseId: baseId }; + }) + return min } +module.exports = minSatisfying -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; -} +/***/ }), +/***/ 95263: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function checkNoRef(schema) { - var item; - if (Array.isArray(schema)) { - for (var i=0; i { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver } - return true; -} + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } -function countKeys(schema) { - var count = 0, item; - if (Array.isArray(schema)) { - for (var i=0; i { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin } } - return count; -} + if (minver && range.test(minver)) { + return minver + } -function getFullPath(id, normalize) { - if (normalize !== false) id = normalizeId(id); - var p = URI.parse(id); - return _getFullPath(p); + return null } +module.exports = minVersion -function _getFullPath(p) { - return URI.serialize(p).split('#')[0] + '#'; -} - +/***/ }), -var TRAILING_SLASH_HASH = /#\/?$/; -function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; -} +/***/ 44295: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const SemVer = __nccwpck_require__(39077) +const Comparator = __nccwpck_require__(44035) +const { ANY } = Comparator +const Range = __nccwpck_require__(27426) +const satisfies = __nccwpck_require__(92867) +const gt = __nccwpck_require__(62975) +const lt = __nccwpck_require__(95125) +const lte = __nccwpck_require__(44958) +const gte = __nccwpck_require__(83332) + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) -function resolveUrl(baseId, id) { - id = normalizeId(id); - return URI.resolve(baseId, id); -} + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } -/* @this Ajv */ -function resolveIds(schema) { - var schemaId = normalizeId(this._getId(schema)); - var baseIds = {'': schemaId}; - var fullPaths = {'': getFullPath(schemaId, false)}; - var localRefs = {}; - var self = this; + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. - 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)); + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] - if (typeof id == 'string') { - id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); + let high = null + let low = null - 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; - } + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false } - baseIds[jsonPtr] = baseId; - fullPaths[jsonPtr] = fullPath; - }); - return localRefs; + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true } +module.exports = outside + /***/ }), -/***/ 68561: +/***/ 99939: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -var ruleModules = __nccwpck_require__(85810) - , toHash = __nccwpck_require__(76578).toHash; - -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' ] } - ]; - - 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; - }); +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = __nccwpck_require__(92867) +const compare = __nccwpck_require__(7345) +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version } - ALL.push(keyword); - var rule = RULES.all[keyword] = { - keyword: keyword, - code: ruleModules[keyword], - implements: implKeywords - }; - return rule; - }); - - RULES.all.$comment = { - keyword: '$comment', - code: ruleModules.$comment - }; - - if (group.type) RULES.types[group.type] = group; - }); - - RULES.keywords = toHash(ALL.concat(KEYWORDS)); - RULES.custom = {}; + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } - return RULES; -}; + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} /***/ }), -/***/ 37605: +/***/ 68299: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +const Range = __nccwpck_require__(27426) +const Comparator = __nccwpck_require__(44035) +const { ANY } = Comparator +const satisfies = __nccwpck_require__(92867) +const compare = __nccwpck_require__(7345) -var util = __nccwpck_require__(76578); +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } -module.exports = SchemaObject; + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false -function SchemaObject(obj) { - util.copy(obj, this); + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true } +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] -/***/ }), - -/***/ 64580: -/***/ ((module) => { - -"use strict"; - +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } -// 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 + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion } } - return length; -}; + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } -/***/ }), + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } -/***/ 76578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (eqSet.size > 1) { + return null + } -"use strict"; + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + if (lt && !satisfies(eq, String(lt), options)) { + return null + } -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 -}; + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + return true + } -function copy(o, to) { - to = to || {}; - for (var key in o) to[key] = o[key]; - return to; -} + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } -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 + '"'; + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false } -} + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } -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); + return true +} - return code; +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a } - -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 { + if (!a) { + return b } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a } - -function toHash(arr) { - var hash = {}; - for (var i=0; i { -function escapeQuotes(str) { - return str.replace(SINGLE_QUOTE, '\\$&') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\f/g, '\\f') - .replace(/\t/g, '\\t'); -} +const Range = __nccwpck_require__(27426) +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) -function varOccurences(str, dataVar) { - dataVar += '[^0-9]'; - var matches = str.match(new RegExp(dataVar, 'g')); - return matches ? matches.length : 0; -} +module.exports = toComparators -function varReplace(str, dataVar, expr) { - dataVar += '([^0-9])'; - expr = expr.replace(/\$/g, '$$$$'); - return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); -} +/***/ }), +/***/ 31524: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function schemaHasRules(schema, rules) { - if (typeof schema == 'boolean') return !schema; - for (var key in schema) if (rules[key]) return true; +const Range = __nccwpck_require__(27426) +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } } +module.exports = validRange -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; -} - +/***/ }), -function schemaUnknownRules(schema, rules) { - if (typeof schema == 'boolean') return; - for (var key in schema) if (!rules[key]) return key; -} +/***/ 48566: +/***/ ((module, exports) => { +module.exports = exports = abbrev.abbrev = abbrev -function toQuotedString(str) { - return '\'' + escapeQuotes(str) + '\''; -} +abbrev.monkeyPatch = monkeyPatch +function monkeyPatch () { + Object.defineProperty(Array.prototype, 'abbrev', { + value: function () { return abbrev(this) }, + enumerable: false, configurable: true, writable: true + }) -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); + Object.defineProperty(Object.prototype, 'abbrev', { + value: function () { return abbrev(Object.keys(this)) }, + enumerable: false, configurable: true, writable: true + }) } +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]) + } -function getPath(currentPath, prop, jsonPointers) { - var path = jsonPointers // false by default - ? toQuotedString('/' + escapeJsonPointer(prop)) - : toQuotedString(getProperty(prop)); - return joinPaths(currentPath, path); -} - + // sort them lexicographically, so that they're next to their nearest kin + args = args.sort(lexSort) -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]; + // 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 + } } - - 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 expr = data; - var segments = jsonPointer.split('/'); - for (var i=0; i b ? 1 : -1 } /***/ }), -/***/ 21412: -/***/ ((module) => { +/***/ 35894: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; - - -var KEYWORDS = [ - 'multipleOf', - 'maximum', - 'exclusiveMaximum', - 'minimum', - 'exclusiveMinimum', - 'maxLength', - 'minLength', - 'pattern', - 'additionalItems', - 'maxItems', - 'minItems', - 'uniqueItems', - 'maxProperties', - 'minProperties', - 'required', - 'additionalProperties', - 'enum', - 'format', - 'const' -]; - -module.exports = function (metaSchema, keywordsJsonPointers) { - for (var i=0; i { "use strict"; - - -var metaSchema = __nccwpck_require__(40038); - -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'} - ] - } - } -}; +/* + * @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; /***/ }), -/***/ 7404: -/***/ ((module) => { +/***/ 69775: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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 { - $exclusive = false; - $opStr += '='; - } - } - 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; -} - - -/***/ }), - -/***/ 64683: -/***/ ((module) => { - -"use strict"; - -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; -} +/* + * @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; /***/ }), -/***/ 52114: -/***/ ((module) => { +/***/ 74854: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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; -} - +/* + * @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; /***/ }), -/***/ 71142: -/***/ ((module) => { +/***/ 19270: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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; -} - - -/***/ }), - -/***/ 89443: -/***/ ((module) => { - -"use strict"; - -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; -} +/* + * @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; /***/ }), -/***/ 63093: -/***/ ((module) => { +/***/ 38289: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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; -} - +/* + * @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; /***/ }), -/***/ 30134: -/***/ ((module) => { +/***/ 66576: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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; -} - +/* + * @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; /***/ }), -/***/ 1661: +/***/ 10282: /***/ ((module) => { "use strict"; - -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; -} +/* + * @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; /***/ }), -/***/ 55964: -/***/ ((module) => { +/***/ 92288: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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; -} - +/* + * @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; /***/ }), -/***/ 5912: -/***/ ((module) => { +/***/ 92474: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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) + ' { +/***/ 27078: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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(", "))); - } - 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 (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++; } '; - } - } - } - 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; -} - - -/***/ }), - -/***/ 10163: -/***/ ((module) => { - -"use strict"; - -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; -} - - -/***/ }), - -/***/ 63847: -/***/ ((module) => { - -"use strict"; - -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; -} - - -/***/ }), - -/***/ 80862: -/***/ ((module) => { - -"use strict"; - -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; -} - +/* + * @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; /***/ }), -/***/ 85810: +/***/ 41602: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - - -//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) => { - -"use strict"; - -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; -} - - -/***/ }), - -/***/ 39772: -/***/ ((module) => { - -"use strict"; - -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; -} - - -/***/ }), - -/***/ 60750: -/***/ ((module) => { - -"use strict"; - -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; -} +/* + * @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; /***/ }), -/***/ 6106: -/***/ ((module) => { +/***/ 60772: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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; -} - +/* + * @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; /***/ }), -/***/ 13912: -/***/ ((module) => { +/***/ 21178: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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; -} +/* + * @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; /***/ }), -/***/ 52924: -/***/ ((module) => { +/***/ 58663: +/***/ ((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 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; -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)) + ' '; - } - } - } - } - 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 += '\' '; - } - 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++; '; - } - $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 { - 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 += ' ) { '; - } - } - out += ' ' + ($code) + ' } '; - } - } - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - 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; -} - - -/***/ }), - -/***/ 19195: -/***/ ((module) => { +/***/ 5336: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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) + '= 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; /***/ }), -/***/ 42393: -/***/ ((module) => { +/***/ 39035: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -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 { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - if ($breakOnError) { - out += ' if (false) { '; - } - } else if (it.opts.missingRefs == 'ignore') { - it.logger.warn($message); - if ($breakOnError) { - out += ' if (true) { '; - } - } 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; -} +/* + * @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; /***/ }), -/***/ 8420: -/***/ ((module) => { +/***/ 55927: +/***/ ((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 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; + +/***/ }), + +/***/ 27387: +/***/ ((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 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; + +/***/ }), + +/***/ 19744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var v1 = __nccwpck_require__(64425); +var v4 = __nccwpck_require__(85258); + +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; + +module.exports = uuid; -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; - } - } - } - } 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 { - 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 { '; - } 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 { - 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++; '; - } - 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 { - 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++; } } '; - if ($isData) { - out += ' } '; - } - } 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++; } '; - } - } - } - } - it.errorPath = $currentErrorPath; - } else if ($breakOnError) { - out += ' if (true) {'; - } - return out; -} - /***/ }), -/***/ 24995: +/***/ 54121: /***/ ((module) => { -"use strict"; +/** + * 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); +} -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); - } - 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; +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(''); } +module.exports = bytesToUuid; + /***/ }), -/***/ 49585: -/***/ ((module) => { +/***/ 57455: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +// Unique ID creation requires a high quality random # generator. In node.js +// this is pretty straight-forward - we use the crypto API. -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\' '; - } - 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++; '; - } - } else { - if (it.isTop) { - if ($async) { - out += ' return data; '; - } else { - out += ' validate.errors = null; return true; '; - } - } else { - out += ' var ' + ($valid) + ' = true; '; - } +var crypto = __nccwpck_require__(76417); + +module.exports = function nodeRNG() { + return crypto.randomBytes(16); +}; + + +/***/ }), + +/***/ 64425: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +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 + +var _nodeId; +var _clockseq; + +// Previous uuid creation time +var _lastMSecs = 0; +var _lastNSecs = 0; + +// See https://github.com/uuidjs/uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + + // 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 (it.isTop) { - out += ' }; return validate; '; + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } - 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;'; + + // 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(); + + // 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; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; } - 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; - } + + // 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; } - if ($typeIsArray && $typeSchema.length == 1) { - $typeSchema = $typeSchema[0]; - $typeIsArray = false; + + // 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'); } - 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 + '"'); - } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // 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; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; } - if (it.schema.$comment && it.opts.$comment) { - out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + + return buf ? buf : bytesToUuid(b); +} + +module.exports = v1; + + +/***/ }), + +/***/ 85258: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var rng = __nccwpck_require__(57455); +var bytesToUuid = __nccwpck_require__(54121); + +function v4(options, buf, offset) { + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options === 'binary' ? new Array(16) : null; + options = null; } - if ($typeSchema) { - if (it.opts.coerceTypes) { - var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + 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]; } - 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 { - 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 (' + ($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 { - 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 (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) + ';'; - } - - function $shouldUseGroup($rulesGroup) { - var rules = $rulesGroup.rules; - for (var i = 0; i < rules.length; i++) - if ($shouldUseRule(rules[i])) return true; - } - - function $shouldUseRule($rule) { - return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); } - 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; + return buf || bytesToUuid(rnds); } +module.exports = v4; + /***/ }), -/***/ 53297: +/***/ 64941: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; -var customRuleCode = __nccwpck_require__(5912); -var definitionSchema = __nccwpck_require__(10458); +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); -module.exports = { - add: addKeyword, - get: getKeyword, - remove: removeKeyword, - validate: validateKeyword -}; +module.exports = Ajv; +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; -/** - * 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'); +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; - if (!IDENTIFIER.test(keyword)) - throw new Error('Keyword ' + keyword + ' is not a valid identifier'); +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; - if (definition) { - this.validateKeyword(definition, true); +var errorClasses = __nccwpck_require__(25726); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; - var dataType = definition.type; - if (Array.isArray(dataType)) { - for (var i=0; i { -"use strict"; +/** + * 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); + } +} -module.exports = function () { - return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; -}; +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; + } +} -/***/ }), -/***/ 52068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function _getSchemaObj(self, keyRef) { + keyRef = resolve.normalizeId(keyRef); + return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; +} -"use strict"; -/* module decorator */ module = __nccwpck_require__.nmd(module); +/** + * 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; +} -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; +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]; + } + } +} -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; +/* @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; -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); + shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); + var id = resolve.normalizeId(this._getId(schema)); + if (id && shouldAddSchema) checkUnique(this, id); - return value; - }, - enumerable: true, - configurable: true - }); -}; + var willValidate = this._opts.validateSchema !== false && !skipValidation; + var recursiveMeta; + if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) + this.validateSchema(schema, true); -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = __nccwpck_require__(86931); - } + var localRefs = resolve.ids.call(this, schema); - const offset = isBackground ? 10 : 0; - const styles = {}; + var schemaObj = new SchemaObject({ + id: id, + schema: schema, + localRefs: localRefs, + cacheKey: cacheKey, + meta: meta + }); - 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); - } - } + if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; + this._cache.put(cacheKey, schemaObj); - return styles; -}; + if (willValidate && recursiveMeta) this.validateSchema(schema, 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], + return schemaObj; +} - // 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], - // 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] - } - }; +/* @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; - // 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; + var currentOpts; + if (schemaObj.meta) { + currentOpts = this._opts; + this._opts = this._metaOpts; + } - 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` - }; + 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; + } - group[styleName] = styles[styleName]; + schemaObj.validate = v; + schemaObj.refs = v.refs; + schemaObj.refVal = v.refVal; + schemaObj.root = v.root; + return v; - codes.set(style[0], style[1]); - } - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } + /* @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; + } +} - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; +function chooseGetId(opts) { + switch (opts.schemaId) { + case 'auto': return _get$IdOrId; + case 'id': return _getId; + default: return _get$Id; + } +} - 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)); +/* @this Ajv */ +function _getId(schema) { + if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); + return schema.id; +} - return styles; +/* @this Ajv */ +function _get$Id(schema) { + if (schema.id) this.logger.warn('schema id ignored', schema.id); + return schema.$id; } -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); +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; +} -/***/ }), -/***/ 64808: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * 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; -"use strict"; + var text = ''; + for (var i=0; i { +function addDefaultMetaSchema(self) { + var $dataSchema; + if (self._opts.$data) { + $dataSchema = __nccwpck_require__(66835); + self.addMetaSchema($dataSchema, $dataSchema.$id, true); + } + if (self._opts.meta === false) return; + var metaSchema = __nccwpck_require__(40038); + if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); + self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); + self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; +} -"use strict"; + +function addInitialSchemas(self) { + var optsSchemas = self._opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas); + else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key); +} -module.exports = function(dirname) { - var path = __nccwpck_require__(85622); - var resolve = __nccwpck_require__(15619); - var appRootPath = resolve(dirname); +function addInitialFormats(self) { + for (var name in self._opts.formats) { + var format = self._opts.formats[name]; + self.addFormat(name, format); + } +} - var publicInterface = { - resolve: function(pathToModule) { - return path.join(appRootPath, pathToModule); - }, - require: function(pathToModule) { - return require(publicInterface.resolve(pathToModule)); - }, +function addInitialKeywords(self) { + for (var name in self._opts.keywords) { + var keyword = self._opts.keywords[name]; + self.addKeyword(name, keyword); + } +} - toString: function() { - return appRootPath; - }, - setPath: function(explicitlySetPath) { - appRootPath = path.resolve(explicitlySetPath); - publicInterface.path = appRootPath; - }, +function checkUnique(self, id) { + if (self._schemas[id] || self._refs[id]) + throw new Error('schema with key or id "' + id + '" already exists'); +} - path: appRootPath - }; - return publicInterface; -}; +function getMetaSchemaOptions(self) { + var metaOpts = util.copy(self._opts); + for (var i=0; i { +/***/ 93679: +/***/ ((module) => { "use strict"; -// Dependencies -var path = __nccwpck_require__(85622); -// Load global paths -var globalPaths = __nccwpck_require__(32282).globalPaths; +var Cache = module.exports = function Cache() { + this._cache = {}; +}; -// 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'); -// Save OS-specific path separator -var sep = path.sep; +Cache.prototype.put = function Cache_put(key, value) { + this._cache[key] = value; +}; -// If we're in webpack, force it to use the original require() method -var requireFunction = ( true) - ? eval("require") - : 0; -const isInstalledWithPNPM = function(resolved) { - const pnpmDir = sep + '.pnpm'; +Cache.prototype.get = function Cache_get(key) { + return this._cache[key]; +}; - for (const globalPath of globalPaths) { - if (-1 !== globalPath.indexOf(pnpmDir) && -1 !== resolved.indexOf(pnpmDir)) { - return true; - } - } - return false; -} -const getFirstPartFromNodeModules = function(resolved) { - const nodeModulesDir = sep + 'node_modules'; +Cache.prototype.del = function Cache_del(key) { + delete this._cache[key]; +}; - if (-1 !== resolved.indexOf(nodeModulesDir)) { - const parts = resolved.split(nodeModulesDir); - if (parts.length) { - return parts[0]; - } - } - return null; -} +Cache.prototype.clear = function Cache_clear() { + this._cache = {}; +}; -// 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) {} - } +/***/ 80890: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Defer to AWS Lambda when executing there - if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) { - return process.env.LAMBDA_TASK_ROOT; - } +"use strict"; - var resolved = path.resolve(dirname); - var alternateMethod = false; - var appRootPath = null; - // 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); +var MissingRefError = __nccwpck_require__(25726).MissingRef; - if (appRootPath) { - return appRootPath; - } - } +module.exports = compileAsync; - // 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 the app-root-path library isn't loaded globally, - // and node_modules exists in the path, just split __dirname - if (!alternateMethod) { - appRootPath = getFirstPartFromNodeModules(resolved); - } +/** + * 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 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 (typeof meta == 'function') { + callback = meta; + meta = undefined; + } - // Handle global bin/ directory edge-case - if (alternateMethod && -1 !== appRootPath.indexOf(npmGlobalModuleDir) && (appRootPath.length - 4) === appRootPath.indexOf(sep + 'bin')) { - appRootPath = appRootPath.slice(0, -4); - } + var p = loadMetaSchemaOf(schema).then(function () { + var schemaObj = self._addSchema(schema, undefined, meta); + return schemaObj.validate || _compileAsync(schemaObj); + }); - // Return - return appRootPath; -}; + if (callback) { + p.then( + function(v) { callback(null, v); }, + callback + ); + } + return p; -/***/ }), -/***/ 83278: -/***/ ((module) => { + function loadMetaSchemaOf(sch) { + var $schema = sch.$schema; + return $schema && !self.getSchema($schema) + ? compileAsync.call(self, { $ref: $schema }, true) + : Promise.resolve(); + } -"use strict"; + function _compileAsync(schemaObj) { + try { return self._compile(schemaObj); } + catch(e) { + if (e instanceof MissingRefError) return loadMissingSchema(e); + throw e; + } -function isArguments (thingy) { - return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') -} -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 loadMissingSchema(e) { + var ref = e.missingSchema; + if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); -function addSchema (schema, arity) { - var group = arity[schema.length] = arity[schema.length] || [] - if (group.indexOf(schema) === -1) group.push(schema) -} + var schemaPromise = self._loadingSchemas[ref]; + if (!schemaPromise) { + schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); + schemaPromise.then(removePromise, removePromise); + } -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 = {} + 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); + }); - 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]) + function removePromise() { + delete self._loadingSchemas[ref]; + } + + function added(ref) { + return self._refs[ref] || self._schemas[ref]; + } } - matching = newMatching } } -function missingRequiredArg (num) { - return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) -} -function unknownType (num, type) { - return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) -} +/***/ }), -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) -} +/***/ 25726: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function englishList (list) { - return list.join(', ').replace(/, ([^,]+)$/, ' or $1') -} +"use strict"; -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 moreThanOneError (schema) { - return newException('ETOOMANYERRORTYPES', - 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') -} +var resolve = __nccwpck_require__(63896); -function newException (code, msg) { - var e = new Error(msg) - e.code = code - if (Error.captureStackTrace) Error.captureStackTrace(e, validate) - return e +module.exports = { + Validation: errorSubclass(ValidationError), + MissingRef: errorSubclass(MissingRefError) +}; + + +function ValidationError(errors) { + this.message = 'validation failed'; + this.errors = errors; + this.ajv = this.validation = true; } -/***/ }), +MissingRefError.message = function (baseId, ref) { + return 'can\'t resolve reference ' + ref + ' from id ' + baseId; +}; -/***/ 11083: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +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)); +} + -exports.TrackerGroup = __nccwpck_require__(60660) -exports.Tracker = __nccwpck_require__(8074) -exports.TrackerStream = __nccwpck_require__(31375) +function errorSubclass(Subclass) { + Subclass.prototype = Object.create(Error.prototype); + Subclass.prototype.constructor = Subclass; + return Subclass; +} /***/ }), -/***/ 92931: +/***/ 66627: /***/ ((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 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 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; -/**/ +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} -var pna = __nccwpck_require__(47810); -/**/ -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; +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 }; -/**/ - -module.exports = Duplex; -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ -var Readable = __nccwpck_require__(70661); -var Writable = __nccwpck_require__(7631); +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 +}; -util.inherits(Duplex, Readable); -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; - if (options && options.readable === false) this.readable = false; + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; - if (options && options.writable === false) this.writable = false; + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - this.once('end', onend); -} +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; -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 () { - return this._writableState.highWaterMark; - } -}); + 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); +} -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); +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); } -function onEndNT(self) { - self.end(); + +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); } -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (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 - this._readableState.destroyed = value; - this._writableState.destroyed = value; +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; } -}); - -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); +} - pna.nextTick(cb, err); -}; /***/ }), -/***/ 61894: +/***/ 875: /***/ ((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. +var resolve = __nccwpck_require__(63896) + , util = __nccwpck_require__(76578) + , errorClasses = __nccwpck_require__(25726) + , stableStringify = __nccwpck_require__(30969); -module.exports = PassThrough; +var validateGenerator = __nccwpck_require__(49585); -var Transform = __nccwpck_require__(53937); +/** + * Functions below are used inside compiled validations function + */ -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ +var ucs2length = util.ucs2length; +var equal = __nccwpck_require__(28206); -util.inherits(PassThrough, Transform); +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); +module.exports = compile; - Transform.call(this, options); -} -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; +/** + * 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 = []; -/***/ }), + root = root || { schema: schema, refVal: refVal, refs: refs }; -/***/ 70661: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); -"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. + var formats = this._formats; + var RULES = this.RULES; + 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); + } + /* @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; + } -/**/ + 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 pna = __nccwpck_require__(47810); -/**/ + var $async = _schema.$async === true; -module.exports = Readable; + 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 + }); -/**/ -var isArray = __nccwpck_require__(20893); -/**/ + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; -/**/ -var Duplex; -/**/ + 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 + ); -Readable.ReadableState = ReadableState; + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError + ); -/**/ -var EE = __nccwpck_require__(28614).EventEmitter; + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + 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 + }; + } -/**/ -var Stream = __nccwpck_require__(69777); -/**/ + return validate; + } -/**/ + 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); + } + } -var Buffer = __nccwpck_require__(95237).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} + 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); + } + } -/**/ + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } -/**/ -var debugUtil = __nccwpck_require__(31669); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ + function removeLocalRef(ref) { + delete refs[ref]; + } -var BufferList = __nccwpck_require__(52743); -var destroyImpl = __nccwpck_require__(69147); -var StringDecoder; + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } -util.inherits(Readable, Stream); + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } -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); + 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; + } + } - // 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 (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} + 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(',')); -function ReadableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(92931); + 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); + } + } + } - options = options || {}; + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; - // 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. - var isDuplex = stream instanceof Duplex; + 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; + } - // 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 (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + var index = customRules.length; + customRules[index] = validate; - // 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" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + return { + code: 'customRule' + index, + validate: validate + }; + } +} - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); +/** + * 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 }; +} - // 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; +/** + * 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); +} - // 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; - // has it been destroyed - this.destroyed = false; +/** + * 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 { -// 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. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; +"use strict"; - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; +var URI = __nccwpck_require__(70020) + , equal = __nccwpck_require__(28206) + , util = __nccwpck_require__(76578) + , SchemaObject = __nccwpck_require__(37605) + , traverse = __nccwpck_require__(52533); -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; +module.exports = resolve; -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } +resolve.normalizeId = normalizeId; +resolve.fullPath = getFullPath; +resolve.url = resolveUrl; +resolve.ids = resolveIds; +resolve.inlineRef = inlineRef; +resolve.schema = resolveSchema; - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - 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; - } +/** + * [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); } - return needMoreData(state); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + refVal = refVal || this._schemas[ref]; + if (refVal instanceof SchemaObject) { + return inlineRef(refVal.schema, this._opts.inlineRefs) + ? refVal.schema + : refVal.validate || this._compile(refVal); + } - if (state.needReadable) emitReadable(stream); + var res = resolveSchema.call(this, root, ref); + var schema, v, baseId; + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; } - maybeReadMore(stream, state); -} -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + 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); } - return er; -} -// if it's past the high water mark, we can push in some more. -// 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. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + return v; } -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __nccwpck_require__(63824)/* .StringDecoder */ .s; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - 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++; +/** + * 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 n; + return getJsonPointer.call(this, p, baseId, root.schema, root); } -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -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. - 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; + +/* @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); } - return state.length; } -// you can override either this method, or the async _read(n) below. -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. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - n = howMuchToRead(n, state); +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 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; + 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; + } + } + } + } } + if (schema !== undefined && schema !== root.schema) + return { schema: schema, root: root, baseId: baseId }; +} - // 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); - } +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; +} - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - if (ret === null) { - state.needReadable = true; - n = 0; +function checkNoRef(schema) { + var item; + if (Array.isArray(schema)) { + for (var i=0; i stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } -} -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); +var TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; } -// 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; - pna.nextTick(maybeReadMore_, stream, state); - } -} -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; +function resolveUrl(baseId, id) { + id = normalizeId(id); + return URI.resolve(baseId, id); } -// 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. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); +/* @this Ajv */ +function resolveIds(schema) { + var schemaId = normalizeId(this._getId(schema)); + var baseIds = {'': schemaId}; + var fullPaths = {'': getFullPath(schemaId, false)}; + var localRefs = {}; + var self = this; - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + 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)); - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + if (typeof id == 'string') { + id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); + 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; + }); - function onend() { - debug('onend'); - dest.end(); - } + return localRefs; +} - // 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; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - 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; +/***/ 68561: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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(); - } +"use strict"; - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // 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', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } +var ruleModules = __nccwpck_require__(85810) + , toHash = __nccwpck_require__(76578).toHash; - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); +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' ] } + ]; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + 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); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } + 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; + }); - // tell the dest that it's being piped to - dest.emit('pipe', src); + RULES.all.$comment = { + keyword: '$comment', + code: ruleModules.$comment + }; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } + if (group.type) RULES.types[group.type] = group; + }); - return dest; -}; + RULES.keywords = toHash(ALL.concat(KEYWORDS)); + RULES.custom = {}; -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} + return RULES; +}; -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; +/***/ 37605: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!dest) dest = state.pipes; +"use strict"; - // 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. +var util = __nccwpck_require__(76578); - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; +module.exports = SchemaObject; - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; - } +function SchemaObject(obj) { + util.copy(obj, 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); +/***/ 64580: +/***/ ((module) => { - return this; -}; +"use strict"; -// 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); - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } +// 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; +}; - return res; + +/***/ }), + +/***/ 76578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + + +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 }; -Readable.prototype.addListener = Readable.prototype.on; -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; } -// 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'); - state.flowing = true; - resume(this, state); + +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 + '"'; } - return this; -}; +} -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); + +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); + + return code; } } -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); + +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= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - return ret; +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); } -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; + +function getPath(currentPath, prop, jsonPointers) { + var path = jsonPointers // false by default + ? toQuotedString('/' + escapeJsonPointer(prop)) + : toQuotedString(getProperty(prop)); + return joinPaths(currentPath, path); } -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - 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; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; + +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]; } - ++c; + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; } - list.length -= c; - return ret; -} -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - 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; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i 0) throw new Error('"endReadable()" called on non-empty stream'); - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } +function joinPaths (a, b) { + if (a == '""') return b; + return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1'); } -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; +function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); } -/***/ }), -/***/ 53937: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); +} -"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. +function escapeJsonPointer(str) { + return str.replace(/~/g, '~0').replace(/\//g, '~1'); +} +function unescapeJsonPointer(str) { + return str.replace(/~1/g, '/').replace(/~0/g, '~'); +} -module.exports = Transform; -var Duplex = __nccwpck_require__(92931); +/***/ }), -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ +/***/ 21412: +/***/ ((module) => { -util.inherits(Transform, Duplex); +"use strict"; -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; +var KEYWORDS = [ + 'multipleOf', + 'maximum', + 'exclusiveMaximum', + 'minimum', + 'exclusiveMinimum', + 'maxLength', + 'minLength', + 'pattern', + 'additionalItems', + 'maxItems', + 'minItems', + 'uniqueItems', + 'maxProperties', + 'minProperties', + 'required', + 'additionalProperties', + 'enum', + 'format', + 'const' +]; - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); - } +module.exports = function (metaSchema, keywordsJsonPointers) { + for (var i=0; i { - Duplex.call(this, options); +"use strict"; - 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; +var metaSchema = __nccwpck_require__(40038); - // 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; +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'} + ] + } + } +}; - 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); -} +/***/ 7404: +/***/ ((module) => { -function prefinish() { - var _this = this; +"use strict"; - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); +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 { - done(this, null, null); + $schemaValue = $schema; } -} - -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) { - throw new Error('_transform() is not implemented'); -}; - -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); + 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'); } -}; - -// 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.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + 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 { - // 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; + 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 { + $exclusive = false; + $opStr += '='; + } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } } -}; - -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; - - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; + $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; +} -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); +/***/ }), - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); +/***/ 64683: +/***/ ((module) => { - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); +"use strict"; - return stream.push(null); +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; } + /***/ }), -/***/ 7631: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 52114: +/***/ ((module) => { "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. +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 pna = __nccwpck_require__(47810); -/**/ +/***/ 71142: +/***/ ((module) => { -module.exports = Writable; +"use strict"; -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = 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; } -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ +/***/ }), -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ +/***/ 89443: +/***/ ((module) => { -/**/ -var Duplex; -/**/ +"use strict"; -Writable.WritableState = WritableState; +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; +} -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ -/**/ -var internalUtil = { - deprecate: __nccwpck_require__(65278) -}; -/**/ +/***/ }), -/**/ -var Stream = __nccwpck_require__(69777); -/**/ +/***/ 63093: +/***/ ((module) => { -/**/ +"use strict"; -var Buffer = __nccwpck_require__(95237).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +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; } -/**/ -var destroyImpl = __nccwpck_require__(69147); +/***/ }), -util.inherits(Writable, Stream); +/***/ 30134: +/***/ ((module) => { -function nop() {} +"use strict"; -function WritableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(92931); +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; +} - 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. - var isDuplex = stream instanceof Duplex; +/***/ }), - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; +/***/ 1661: +/***/ ((module) => { - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; +"use strict"; - // 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() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // if _final has been called - 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 - 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. - 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. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - 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) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - 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 - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; +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; } - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - 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 realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - - return object && object._writableState instanceof WritableState; + 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\' '; } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(92931); - - // 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. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; } - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - 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; + 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++; '; } - - Stream.call(this); + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; } -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.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. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; +/***/ 55964: +/***/ ((module) => { - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); +"use strict"; + +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) {'; } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; + 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 += ' {} '; } - return valid; -} - -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); + 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 (typeof encoding === 'function') { - cb = encoding; - encoding = null; + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; - - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + if (it.opts.allErrors) { + out += ' } '; } + return out; +} - return ret; -}; - -Writable.prototype.cork = function () { - var state = this._writableState; - state.corked++; -}; +/***/ }), -Writable.prototype.uncork = function () { - var state = this._writableState; +/***/ 5912: +/***/ ((module) => { - if (state.corked) { - state.corked--; +"use strict"; - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); +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; } -}; - -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 TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); + 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; } - return chunk; -} - -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 () { - return this._writableState.highWaterMark; + 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;'; } -}); - -// 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. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; + 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) + ') { '; } } - 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. - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; } else { - state.bufferedRequest = state.lastBufferedRequest; + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - 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; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); + } 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 { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - 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); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; } - - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; } else { - afterWrite(stream, state, finished, cb); + 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) + '; '; + } } } -} - -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. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; } -} - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - 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; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; } - 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 - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } } else { - state.corkedRequestsFree = new CorkedRequest(state); + out += ' ' + (!$rDef.valid) + ' '; } - 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. - if (state.writing) { - break; + 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 (chunk !== null && chunk !== undefined) this.write(chunk, encoding); +"use strict"; - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); +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; } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); -}; - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); + 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(", "))); + } + 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 (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++; } '; + } + } + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } } } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); + 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 += '}'; + } } } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = corkReq; - } else { - state.corkedRequestsFree = corkReq; + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } + return out; } -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (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 - this._writableState.destroyed = value; - } -}); - -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; /***/ }), -/***/ 52743: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 10163: +/***/ ((module) => { "use strict"; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Buffer = __nccwpck_require__(95237).Buffer; -var util = __nccwpck_require__(31669); - -function copyBuffer(src, target, offset) { - src.copy(target, offset); +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; } -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - this.head = null; - this.tail = null; - this.length = 0; - } +/***/ }), - BufferList.prototype.push = 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; - }; +/***/ 63847: +/***/ ((module) => { - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; +"use strict"; - BufferList.prototype.shift = 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; - }; +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; +} - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; +/***/ }), - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; +/***/ 80862: +/***/ ((module) => { - return BufferList; -}(); +"use strict"; -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; - }; +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; } + /***/ }), -/***/ 69147: +/***/ 85810: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/**/ +//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) +}; -var pna = __nccwpck_require__(47810); -/**/ -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; +/***/ }), - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; +/***/ 54408: +/***/ ((module) => { - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - pna.nextTick(emitErrorNT, this, err); +"use strict"; + +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 { '; + } } - return this; + 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; +} - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - if (this._readableState) { - this._readableState.destroyed = true; - } +/***/ }), - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } +/***/ 39772: +/***/ ((module) => { - this._destroy(err || null, function (err) { - if (!cb && err) { - pna.nextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; +"use strict"; + +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) + '\''; } - } else if (cb) { - cb(err); } - }); - - return this; -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; + 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 += ' {} '; } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; + 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; } -function emitErrorNT(self, err) { - self.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy -}; /***/ }), -/***/ 69777: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(92413); - - -/***/ }), +/***/ 60750: +/***/ ((module) => { -/***/ 64043: -/***/ ((module, exports, __nccwpck_require__) => { +"use strict"; -var Stream = __nccwpck_require__(92413); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(70661); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(7631); - exports.Duplex = __nccwpck_require__(92931); - exports.Transform = __nccwpck_require__(53937); - exports.PassThrough = __nccwpck_require__(61894); +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; } /***/ }), -/***/ 95237: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 6106: +/***/ ((module) => { -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(64293) -var Buffer = buffer.Buffer +"use strict"; -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] +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) + '; }'; + } } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer + 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; } -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +/***/ }), -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} +/***/ 13912: +/***/ ((module) => { -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +"use strict"; + +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 buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) + 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 { - buf.fill(fill) + 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 { - buf.fill(0) + out += ' {} '; } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + 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++; '; } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + out += '} '; + if ($breakOnError) { + out += ' else { '; } - return buffer.SlowBuffer(size) + return out; } /***/ }), -/***/ 63824: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 52924: +/***/ ((module) => { "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. - - -/**/ - -var Buffer = __nccwpck_require__(95237).Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); +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); } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; + function notProto(p) { + return p !== '__proto__'; } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + 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) + ') { '; } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; + 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)) + ' '; + } + } + } + } + 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 (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; + 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 += '\' '; + } + 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++; '; + } + $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 += '}'; } } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); + 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 { + 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 += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } } } - return r; } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); + 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 += '}'; + } + } + } + } } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); + return out; } -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} /***/ }), -/***/ 10165: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 19195: +/***/ ((module) => { "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 +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) + ' { +/***/ 42393: +/***/ ((module) => { "use strict"; -var util = __nccwpck_require__(31669) -var TrackerBase = __nccwpck_require__(10165) -var Tracker = __nccwpck_require__(8074) -var TrackerStream = __nccwpck_require__(31375) - -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) - -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) - } -} - -TrackerGroup.prototype.nameInTree = function () { - var names = [] - var from = this - while (from) { - names.unshift(from.name) - from = from.parentGroup - } - return names.join('/') -} - -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)) +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 { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + if ($breakOnError) { + out += ' if (false) { '; + } + } else if (it.opts.missingRefs == 'ignore') { + it.logger.warn($message); + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + throw new it.MissingRefError(it.baseId, $schema, $message); } - toTest = toTest.parentGroup + } 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; } - 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 -} - -TrackerGroup.prototype.newGroup = function (name, weight) { - return this.addUnit(new TrackerGroup(name), weight) -} - -TrackerGroup.prototype.newItem = function (name, todo, weight) { - return this.addUnit(new Tracker(name, todo), weight) -} - -TrackerGroup.prototype.newStream = function (name, todo, weight) { - return this.addUnit(new TrackerStream(name, todo), weight) -} - -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) -} - -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) + if ($refCode) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + if (it.opts.passContext) { + out += ' ' + ($refCode) + '.call(this, '; } else { - output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n' + 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 output -} - - -/***/ }), - -/***/ 31375: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var util = __nccwpck_require__(31669) -var stream = __nccwpck_require__(64043) -var delegate = __nccwpck_require__(61318) -var Tracker = __nccwpck_require__(8074) - -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) - -function delegateChange (trackerStream) { - return function (name, completion, tracker) { - trackerStream.emit('change', name, completion, trackerStream) } -} - -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') - - -/***/ }), - -/***/ 8074: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var util = __nccwpck_require__(31669) -var TrackerBase = __nccwpck_require__(10165) - -var Tracker = module.exports = function (name, todo) { - TrackerBase.call(this, name) - this.workDone = 0 - this.workTodo = todo || 0 -} -util.inherits(Tracker, TrackerBase) - -Tracker.prototype.completed = function () { - return this.workTodo === 0 ? 0 : this.workDone / this.workTodo -} - -Tracker.prototype.addWork = function (work) { - this.workTodo += work - this.emit('change', this.name, this.completed(), this) -} - -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) -} - -Tracker.prototype.finish = function () { - this.workTodo = this.workDone = 1 - this.emit('change', this.name, 1, this) + return out; } /***/ }), -/***/ 99348: +/***/ 8420: /***/ ((module) => { -// Copyright 2011 Mark Cavage All rights reserved. - - -module.exports = { +"use strict"; - newInvalidAsn1Error: function (msg) { - var e = new Error(); - e.name = 'InvalidAsn1Error'; - e.message = msg || ''; - return e; +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; } - -}; - - -/***/ }), - -/***/ 194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Copyright 2011 Mark Cavage All rights reserved. - -var errors = __nccwpck_require__(99348); -var types = __nccwpck_require__(42473); - -var Reader = __nccwpck_require__(20290); -var Writer = __nccwpck_require__(43200); - - -// --- Exports - -module.exports = { - - Reader: Reader, - - Writer: Writer - -}; - -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]; -} - - -/***/ }), - -/***/ 20290: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Copyright 2011 Mark Cavage All rights reserved. - -var assert = __nccwpck_require__(42357); -var Buffer = __nccwpck_require__(15118).Buffer; - -var ASN1 = __nccwpck_require__(42473); -var errors = __nccwpck_require__(99348); + 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; + } + } + } + } 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 { + 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 { '; + } 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 { + 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++; '; + } + 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 { + 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++; } } '; + if ($isData) { + out += ' } '; + } + } 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++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} -// --- Globals +/***/ }), -var newInvalidAsn1Error = errors.newInvalidAsn1Error; +/***/ 24995: +/***/ ((module) => { +"use strict"; +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); + } + 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; +} -// --- API -function Reader(data) { - if (!data || !Buffer.isBuffer(data)) - throw new TypeError('data must be a node Buffer'); +/***/ }), - this._buf = data; - this._size = data.length; +/***/ 49585: +/***/ ((module) => { - // These hold the "current" state - this._len = 0; - this._offset = 0; -} +"use strict"; -Object.defineProperty(Reader.prototype, 'length', { - enumerable: true, - get: function () { return (this._len); } -}); +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\' '; + } + 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++; '; + } + } 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 { + 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 (' + ($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 { + 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 (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) + ';'; + } -Object.defineProperty(Reader.prototype, 'offset', { - enumerable: true, - get: function () { return (this._offset); } -}); + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } -Object.defineProperty(Reader.prototype, 'remain', { - get: function () { return (this._size - this._offset); } -}); + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } -Object.defineProperty(Reader.prototype, 'buffer', { - get: function () { return (this._buf.slice(this._offset)); } -}); + 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; +} -/** - * 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; +/***/ }), - var b = this._buf[this._offset] & 0xff; +/***/ 53297: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!peek) - this._offset += 1; +"use strict"; - return b; -}; +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = __nccwpck_require__(5912); +var definitionSchema = __nccwpck_require__(10458); -Reader.prototype.peek = function () { - return this.readByte(true); +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword }; /** - * 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 + * 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 */ -Reader.prototype.readLength = function (offset) { - if (offset === undefined) - offset = this._offset; +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'); - if (offset >= this._size) - return null; + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); - var lenB = this._buf[offset++] & 0xff; - if (lenB === null) - return null; + if (definition) { + this.validateKeyword(definition, true); - if ((lenB & 0x80) === 0x80) { - lenB &= 0x7f; + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i 4) - throw newInvalidAsn1Error('encoding too long'); + RULES.keywords[keyword] = RULES.all[keyword] = true; - if (this._size - offset < lenB) - return null; - this._len = 0; - for (var i = 0; i < lenB; i++) - this._len = (this._len << 8) + (this._buf[offset++] & 0xff); + function _addRule(keyword, dataType, definition) { + var ruleGroup; + for (var i=0; i this._size - o) - return null; +/***/ }), - this._offset = o; +/***/ 65063: +/***/ ((module) => { - if (this.length === 0) - return retbuf ? Buffer.alloc(0) : ''; +"use strict"; - var str = this._buf.slice(this._offset, this._offset + this.length); - this._offset += this.length; - return retbuf ? str : str.toString('utf8'); +module.exports = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; -Reader.prototype.readOID = function (tag) { - if (!tag) - tag = ASN1.OID; - var b = this.readString(tag, true); - if (b === null) - return null; +/***/ }), - var values = []; - var value = 0; +/***/ 52068: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (var i = 0; i < b.length; i++) { - var byte = b[i] & 0xff; +"use strict"; +/* module decorator */ module = __nccwpck_require__.nmd(module); - value <<= 7; - value += byte & 0x7f; - if ((byte & 0x80) === 0) { - values.push(value); - value = 0; - } - } - value = values.shift(); - values.unshift(value % 40); - values.unshift((value / 40) >> 0); +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; - return values.join('.'); +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; }; +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; -Reader.prototype._readTag = function (tag) { - assert.ok(tag !== undefined); +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; - var b = this.peek(); +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); - if (b === null) - return null; + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); + return value; + }, + enumerable: true, + configurable: true + }); +}; - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = __nccwpck_require__(86931); + } - if (this.length > 4) - throw newInvalidAsn1Error('Integer too long: ' + this.length); + const offset = isBackground ? 10 : 0; + const styles = {}; - if (this.length > this._size - o) - return null; - this._offset = o; + 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); + } + } - var fb = this._buf[this._offset]; - var value = 0; + return styles; +}; - for (var i = 0; i < this.length; i++) { - value <<= 8; - value |= (this._buf[this._offset++] & 0xff); - } +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 ((fb & 0x80) === 0x80 && i !== 4) - value -= (1 << (i * 8)); + // 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 value >> 0; -}; + // 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] + } + }; + + // 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; + 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` + }; + group[styleName] = styles[styleName]; -// --- Exported API + codes.set(style[0], style[1]); + } -module.exports = Reader; + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); -/***/ }), + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; -/***/ 42473: -/***/ ((module) => { + 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)); -// Copyright 2011 Mark Cavage All rights reserved. + return styles; +} +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); + + +/***/ }), + +/***/ 64808: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; -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 -}; +var lib = __nccwpck_require__(98035); +module.exports = lib(__dirname); /***/ }), -/***/ 43200: +/***/ 98035: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2011 Mark Cavage All rights reserved. +"use strict"; -var assert = __nccwpck_require__(42357); -var Buffer = __nccwpck_require__(15118).Buffer; -var ASN1 = __nccwpck_require__(42473); -var errors = __nccwpck_require__(99348); +module.exports = function(dirname) { + var path = __nccwpck_require__(85622); + var resolve = __nccwpck_require__(15619); + var appRootPath = resolve(dirname); -// --- Globals + var publicInterface = { + resolve: function(pathToModule) { + return path.join(appRootPath, pathToModule); + }, -var newInvalidAsn1Error = errors.newInvalidAsn1Error; + require: function(pathToModule) { + return require(publicInterface.resolve(pathToModule)); + }, -var DEFAULT_OPTS = { - size: 1024, - growthFactor: 8 + toString: function() { + return appRootPath; + }, + + setPath: function(explicitlySetPath) { + appRootPath = path.resolve(explicitlySetPath); + publicInterface.path = appRootPath; + }, + + path: appRootPath + }; + + return publicInterface; }; +/***/ }), -// --- Helpers +/***/ 15619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function merge(from, to) { - assert.ok(from); - assert.equal(typeof (from), 'object'); - assert.ok(to); - assert.equal(typeof (to), 'object'); +"use strict"; - var keys = Object.getOwnPropertyNames(from); - keys.forEach(function (key) { - if (to[key]) - return; - var value = Object.getOwnPropertyDescriptor(from, key); - Object.defineProperty(to, key, value); - }); +// Dependencies +var path = __nccwpck_require__(85622); - return to; +// Load global paths +var globalPaths = __nccwpck_require__(32282).globalPaths; + +// 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'); +// Save OS-specific path separator +var sep = path.sep; +// If we're in webpack, force it to use the original require() method +var requireFunction = ( true) + ? eval("require") + : 0; -// --- API +const isInstalledWithPNPM = function(resolved) { + const pnpmDir = sep + '.pnpm'; -function Writer(options) { - options = merge(DEFAULT_OPTS, options || {}); + for (const globalPath of globalPaths) { + if (-1 !== globalPath.indexOf(pnpmDir) && -1 !== resolved.indexOf(pnpmDir)) { + return true; + } + } + return false; +} - this._buf = Buffer.alloc(options.size || 1024); - this._size = this._buf.length; - this._offset = 0; - this._options = options; +const getFirstPartFromNodeModules = function(resolved) { + const nodeModulesDir = sep + 'node_modules'; - // A list of offsets in the buffer where we need to insert - // sequence tag/len pairs. - this._seq = []; + if (-1 !== resolved.indexOf(nodeModulesDir)) { + const parts = resolved.split(nodeModulesDir); + if (parts.length) { + return parts[0]; + } + } + + return null; } -Object.defineProperty(Writer.prototype, 'buffer', { - get: function () { - if (this._seq.length) - throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); +// Resolver +module.exports = function resolve(dirname) { + // Check for environmental variable + if (process.env.APP_ROOT_PATH) { + return path.resolve(process.env.APP_ROOT_PATH); + } - return (this._buf.slice(0, this._offset)); - } -}); + // 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) {} + } -Writer.prototype.writeByte = function (b) { - if (typeof (b) !== 'number') - throw new TypeError('argument must be a Number'); + // 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) {} + } - this._ensure(1); - this._buf[this._offset++] = b; -}; + // 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; -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; + // 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); - var sz = 4; + if (appRootPath) { + return appRootPath; + } + } - while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && - (sz > 1)) { - sz--; - i <<= 8; - } + // 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 (sz > 4) - throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); + // 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); + } - this._ensure(2 + sz); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = sz; + // 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); + } - while (sz-- > 0) { - this._buf[this._offset++] = ((i & 0xff000000) >>> 24); - i <<= 8; - } + // 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; }; -Writer.prototype.writeNull = function () { - this.writeByte(ASN1.Null); - this.writeByte(0x00); -}; - +/***/ }), -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; +/***/ 83278: +/***/ ((module) => { - return this.writeInt(i, tag); -}; +"use strict"; +module.exports = validate -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; +function isArguments (thingy) { + return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') +} - this._ensure(3); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = 0x01; - this._buf[this._offset++] = b ? 0xff : 0x00; -}; +const types = { + '*': {label: 'any', check: () => true}, + A: {label: 'array', check: _ => Array.isArray(_) || isArguments(_)}, + S: {label: 'string', check: _ => typeof _ === 'string'}, + N: {label: 'number', check: _ => typeof _ === 'number'}, + F: {label: 'function', check: _ => typeof _ === 'function'}, + O: {label: 'object', check: _ => typeof _ === 'object' && _ != null && !types.A.check(_) && !types.E.check(_)}, + B: {label: 'boolean', check: _ => typeof _ === 'boolean'}, + E: {label: 'error', check: _ => _ instanceof Error}, + Z: {label: 'null', check: _ => _ == null} +} +function addSchema (schema, arity) { + const group = arity[schema.length] = arity[schema.length] || [] + if (group.indexOf(schema) === -1) group.push(schema) +} -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; +function validate (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) + const schemas = rawSchemas.split('|') + const arity = {} - 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; + schemas.forEach(schema => { + for (let ii = 0; ii < schema.length; ++ii) { + const 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) + } + }) + let matching = arity[args.length] + if (!matching) { + throw wrongNumberOfArgs(Object.keys(arity), args.length) } -}; + for (let ii = 0; ii < args.length; ++ii) { + let newMatching = matching.filter(schema => { + const type = schema[ii] + const typeCheck = types[type].check + return typeCheck(args[ii]) + }) + if (!newMatching.length) { + const labels = matching.map(_ => types[_[ii]].label).filter(_ => _ != null) + throw invalidType(ii, labels, args[ii]) + } + matching = newMatching + } +} +function missingRequiredArg (num) { + return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) +} -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'); +function unknownType (num, type) { + return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 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; -}; +function invalidType (num, expectedTypes, value) { + let valueType + Object.keys(types).forEach(typeCode => { + if (types[typeCode].check(value)) valueType = types[typeCode].label + }) + return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + + englishList(expectedTypes) + ' but got ' + valueType) +} +function englishList (list) { + return list.join(', ').replace(/, ([^,]+)$/, ' or $1') +} -Writer.prototype.writeStringArray = function (strings) { - if ((!strings instanceof Array)) - throw new TypeError('argument must be an Array[String]'); +function wrongNumberOfArgs (expected, got) { + const english = englishList(expected) + const args = expected.every(ex => ex.length === 1) + ? 'argument' + : 'arguments' + return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) +} - var self = this; - strings.forEach(function (s) { - self.writeString(s); - }); -}; +function moreThanOneError (schema) { + return newException('ETOOMANYERRORTYPES', + 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') +} -// 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; +function newException (code, msg) { + const err = new Error(msg) + err.code = code + /* istanbul ignore else */ + if (Error.captureStackTrace) Error.captureStackTrace(err, validate) + return err +} - 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 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)); - }); +/***/ 82391: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var self = this; - this._ensure(2 + bytes.length); - this.writeByte(tag); - this.writeLength(bytes.length); - bytes.forEach(function (b) { - self.writeByte(b); - }); -}; +"use strict"; +exports.TrackerGroup = __nccwpck_require__(14788) +exports.Tracker = __nccwpck_require__(27869) +exports.TrackerStream = __nccwpck_require__(96138) -Writer.prototype.writeLength = function (len) { - if (typeof (len) !== 'number') - throw new TypeError('argument must be a Number'); - this._ensure(4); +/***/ }), - 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)'); - } -}; +/***/ 6524: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Writer.prototype.startSequence = function (tag) { - if (typeof (tag) !== 'number') - tag = ASN1.Sequence | ASN1.Constructor; +"use strict"; - this.writeByte(tag); - this._seq.push(this._offset); - this._ensure(3); - this._offset += 3; -}; +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) -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'); - } -}; +/***/ }), +/***/ 14788: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Writer.prototype._shift = function (start, len, shift) { - assert.ok(start !== undefined); - assert.ok(len !== undefined); - assert.ok(shift); +"use strict"; - this._buf.copy(this._buf, start + shift, start, start + len); - this._offset += shift; -}; +var util = __nccwpck_require__(31669) +var TrackerBase = __nccwpck_require__(6524) +var Tracker = __nccwpck_require__(27869) +var TrackerStream = __nccwpck_require__(96138) -Writer.prototype._ensure = function (len) { - assert.ok(len); +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 (this._size - this._offset < len) { - var sz = this._size * this._options.growthFactor; - if (sz - this._offset < len) - sz += len; +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) + } +} - var buf = Buffer.alloc(sz); +TrackerGroup.prototype.nameInTree = function () { + var names = [] + var from = this + while (from) { + names.unshift(from.name) + from = from.parentGroup + } + return names.join('/') +} - this._buf.copy(buf, 0, 0, this._offset); - this._buf = buf; - this._size = sz; +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 +} + +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 +} +TrackerGroup.prototype.newGroup = function (name, weight) { + return this.addUnit(new TrackerGroup(name), weight) +} +TrackerGroup.prototype.newItem = function (name, todo, weight) { + return this.addUnit(new Tracker(name, todo), weight) +} -// --- Exported API +TrackerGroup.prototype.newStream = function (name, todo, weight) { + return this.addUnit(new TrackerStream(name, todo), weight) +} -module.exports = Writer; +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) +} + +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 +} /***/ }), -/***/ 80970: +/***/ 96138: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2011 Mark Cavage All rights reserved. +"use strict"; -// If you have no idea what ASN.1 or BER is, see this: -// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc +var util = __nccwpck_require__(31669) +var stream = __nccwpck_require__(64043) +var delegate = __nccwpck_require__(61318) +var Tracker = __nccwpck_require__(27869) -var Ber = __nccwpck_require__(194); +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) +function delegateChange (trackerStream) { + return function (name, completion, tracker) { + trackerStream.emit('change', name, completion, trackerStream) + } +} +TrackerStream.prototype._transform = function (data, encoding, cb) { + this.tracker.completeWork(data.length ? data.length : 1) + this.push(data) + cb() +} -// --- Exported API +TrackerStream.prototype._flush = function (cb) { + this.tracker.finish() + cb() +} -module.exports = { +delegate(TrackerStream.prototype, 'tracker') + .method('completed') + .method('addWork') + .method('finish') - Ber: Ber, - BerReader: Ber.Reader, +/***/ }), - BerWriter: Ber.Writer +/***/ 27869: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -}; +"use strict"; + +var util = __nccwpck_require__(31669) +var TrackerBase = __nccwpck_require__(6524) + +var Tracker = module.exports = function (name, todo) { + TrackerBase.call(this, name) + this.workDone = 0 + this.workTodo = todo || 0 +} +util.inherits(Tracker, TrackerBase) + +Tracker.prototype.completed = function () { + return this.workTodo === 0 ? 0 : this.workDone / this.workTodo +} + +Tracker.prototype.addWork = function (work) { + this.workTodo += work + this.emit('change', this.name, this.completed(), this) +} + +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) +} + +Tracker.prototype.finish = function () { + this.workTodo = this.workDone = 1 + this.emit('change', this.name, 1, this) +} /***/ }), -/***/ 66631: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 99949: +/***/ ((module) => { -// Copyright (c) 2012, Mark Cavage. All rights reserved. -// Copyright 2015 Joyent, Inc. +"use strict"; -var assert = __nccwpck_require__(42357); -var Stream = __nccwpck_require__(92413).Stream; -var util = __nccwpck_require__(31669); +const codes = {}; -///--- Globals +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } -/* 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}$/; + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } -///--- Internal + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; -function _capitalize(str) { - return (str.charAt(0).toUpperCase() + str.slice(1)); + codes[code] = NodeError; } -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 - }); +// 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)}`; + } } -function _getClass(arg) { - return (Object.prototype.toString.call(arg).slice(8, -1)); +// 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; } -function noop() { - // Why even bother with asserts? +// 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; } +// 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; + } -///--- Exports + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} -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' - } -}; - -function _setExports(ndebug) { - var keys = Object.keys(types); - var out; - - /* re-export standard assert */ - if (process.env.NODE_NDEBUG) { - out = noop; - } else { - out = function (arg, msg) { - if (!arg) { - _toss(msg, 'true', arg); - } - }; - } - - /* 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); - } - }; - }); - - /* 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); - } - }; - }); - - /* 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); - } - } - }; - }); - - /* 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); - } - } - }; - }); - - /* 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]; - }); +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'; + } - /* export ourselves (for unit tests _only_) */ - out._setExports = _setExports; + 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')}`; + } - return out; -} + 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'); -module.exports = _setExports(process.env.NODE_NDEBUG); +module.exports.q = codes; /***/ }), -/***/ 57888: -/***/ (function(__unused_webpack_module, exports) { - -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; +/***/ 92931: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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); - } +"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. - function initialParams (fn) { - return function (...args/*, callback*/) { - var callback = args.pop(); - return fn.call(this, args, callback); - }; - } +// 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. - /* istanbul ignore file */ - var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; - var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - function fallback(fn) { - setTimeout(fn, 0); - } +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ - function wrap(defer) { - return (fn, ...args) => defer(() => fn(...args)); +module.exports = Duplex; +var Readable = __nccwpck_require__(70661); +var Writable = __nccwpck_require__(7631); +__nccwpck_require__(44124)(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); } + } +} +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; + } +}); - var _defer; +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; - if (hasSetImmediate) { - _defer = setImmediate; - } else if (hasNextTick) { - _defer = process.nextTick; - } else { - _defer = fallback; + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +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 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; } - var setImmediate$1 = wrap(_defer); - - /** - * 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) - } - } + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); - 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); - } - }); - } +/***/ }), - function handlePromise(promise, callback) { - return promise.then(value => { - invokeCallback(callback, null, value); - }, err => { - invokeCallback(callback, err && err.message ? err : new Error(err)); - }); - } +/***/ 61894: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (err) { - setImmediate$1(e => { throw e }, err); - } - } +"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. - function isAsync(fn) { - return fn[Symbol.toStringTag] === 'AsyncFunction'; - } +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - function isAsyncGenerator(fn) { - return fn[Symbol.toStringTag] === 'AsyncGenerator'; - } - function isAsyncIterable(obj) { - return typeof obj[Symbol.asyncIterator] === 'function'; - } - function wrapAsync(asyncFn) { - if (typeof asyncFn !== 'function') throw new Error('expected a function') - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; - } +module.exports = PassThrough; +var Transform = __nccwpck_require__(53937); +__nccwpck_require__(44124)(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; - // 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 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); - }) - } +/***/ 70661: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return awaitable - } +"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. - 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; - }; - } - function _asyncMap(eachfn, arr, iteratee, callback) { - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); - return eachfn(arr, (value, _, iterCb) => { - var index = counter++; - _iteratee(value, (err, v) => { - results[index] = v; - iterCb(err); - }); - }, err => { - callback(err, results); - }); - } +module.exports = Readable; - function isArrayLike(value) { - return value && - typeof value.length === 'number' && - value.length >= 0 && - value.length % 1 === 0; - } +/**/ +var Duplex; +/**/ - // A temporary value used to identify if the loop should be broken. - // See #1064, #1293 - const breakLoop = {}; +Readable.ReadableState = ReadableState; - 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 - } +/**/ +var EE = __nccwpck_require__(28614).EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ - function getIterator (coll) { - return coll[Symbol.iterator] && coll[Symbol.iterator](); - } +/**/ +var Stream = __nccwpck_require__(69777); +/**/ - function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; - } - } +var Buffer = __nccwpck_require__(64293).Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} - 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}; - } - } +/**/ +var debugUtil = __nccwpck_require__(31669); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ - 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; - }; - } +var BufferList = __nccwpck_require__(99900); +var destroyImpl = __nccwpck_require__(69147); +var _require = __nccwpck_require__(844), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = __nccwpck_require__(99949)/* .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); - function createIterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); - } + // 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__(92931); + options = options || {}; - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); - } + // 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; - 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); - }; - } + // 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; - // for async generators - function asyncEachOfLimit(generator, limit, iteratee, callback) { - let done = false; - let canceled = false; - let awaiting = false; - let running = 0; - let idx = 0; + // 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); - 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); - } + // 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; - function iterateeCallback(err, result) { - //console.log('iterateeCallback') - running -= 1; - if (canceled) return - if (err) return handleError(err) + // 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; - if (err === false) { - done = true; - canceled = true; - return - } + // 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; - if (result === breakLoop || (done && running <= 0)) { - done = true; - //console.log('done iterCb') - return callback(null); - } - replenish(); - } + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; - function handleError(err) { - if (canceled) return - awaiting = false; - done = true; - callback(err); - } + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; - replenish(); - } + // has it been destroyed + this.destroyed = false; - 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; + // 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'; - 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(); - } - } + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - 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 true, a maybeReadMore has been scheduled + 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__(92931); + if (!(this instanceof Readable)) return new Readable(options); - replenish(); - }; - }; + // 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); - /** - * 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); + // 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); +} +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; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; } - 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); - } + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; - 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); - } - } +// 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. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + 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); + } + 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; + 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); } + } - // 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); - } + // 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 !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); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; - /** - * 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); - } +// backwards compatibility. +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; - var eachOf$1 = awaitify(eachOf, 3); + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + 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; +}; - /** - * 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); +// Don't raise the hwm > 1GB +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; +} - /** - * 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); +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +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. + 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; +} - /** - * 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); +// you can override either this method, or the async _read(n) below. +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; - /** - * 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); + // 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. + 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; + } + n = howMuchToRead(n, state); - /** - * 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); + // 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; + } - const PROMISE_SYMBOL = Symbol('promiseCallback'); + // 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. - function promiseCallback () { - let resolve, reject; - function callback (err, ...args) { - if (err) return reject(err) - resolve(args.length > 1 ? args : args[0]); - } + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); - callback[PROMISE_SYMBOL] = new Promise((res, rej) => { - resolve = res, - reject = rej; - }); + // 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); + } - return callback - } + // 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); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + 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; - /** - * 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; - } + // 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; + } + } + 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); + } + } +} - var results = {}; - var runningTasks = 0; - var canceled = false; - var hasError = false; +// 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 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; + } - var listeners = Object.create(null); + // 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); +} - var readyTasks = []; +// 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; +} - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; +// 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. +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; + case 1: + state.pipes = [state.pipes, dest]; + break; + 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'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } - Object.keys(tasks).forEach(key => { - var task = tasks[key]; - if (!Array.isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } + // 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; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + 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; - 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; + // 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(); + } + src.on('data', ondata); + 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(); + } + } - 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); - } - }); - }); - }); + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } - checkForDeadlocks(); - processQueue(); + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - function enqueueTask(key, task) { - readyTasks.push(() => runTask(key, task)); - } + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } - 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(); - } + // tell the dest that it's being piped to + dest.emit('pipe', src); - } + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + 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 + }; - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - taskListeners.push(fn); - } + // 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; - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - taskListeners.forEach(fn => fn()); - processQueue(); - } + // 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. - function runTask(key, task) { - if (hasError) return; + 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; + } - 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); - } - }); + // 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; +}; - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } +// 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; - 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); - } - }); - } + // 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; - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } - } + // 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); +} - 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; - } +// 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); +} - return callback[PROMISE_SYMBOL] +// 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); - 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; - - 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()); + // 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(); } + }); - /** - * 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 = {}; + // 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); + } + } - 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); + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } - if (Array.isArray(taskFn)) { - params = [...taskFn]; - taskFn = params.pop(); + // 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__(96359); + } + 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; + } + } +}); - 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."); - } +// 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; + } +}); - // remove callback param - if (!fnIsAsync) params.pop(); +// 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); - newTasks[key] = params.concat(newTask); - } + // 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__(8744); + } + 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; +} - function newTask(results, taskCb) { - var newArgs = params.map(name => results[name]); - newArgs.push(taskCb); - wrapAsync(taskFn)(...newArgs); - } - }); +/***/ }), - return auto(newTasks, callback); - } +/***/ 53937: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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; - } +"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. - 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; +// 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. - node.prev = node.next = null; - this.length -= 1; - return node; - } - empty () { - while(this.head) this.shift(); - return this; - } - 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; - } +module.exports = Transform; +var _require$codes = __nccwpck_require__(99949)/* .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__(92931); +__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 + }; - 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; - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - unshift(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); - } + // 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; + } - push(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); - } + // 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); +}; - shift() { - return this.head && this.removeLink(this.head); - } +// 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); + } +}; - pop() { - return this.tail && this.removeLink(this.tail); - } +// 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); - toArray() { - return [...this] - } + // 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); +} - *[Symbol.iterator] () { - var cur = this.head; - while (cur) { - yield cur.data; - cur = cur.next; - } - } +/***/ }), - remove (testFn) { - var curr = this.head; - while(curr) { - var {next} = curr; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; - } - } +/***/ 7631: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; - } +"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. - function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new RangeError('Concurrency must not be zero'); - } +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; - const events = { - error: [], - drain: [], - saturated: [], - unsaturated: [], - empty: [] - }; - function on (event, handler) { - events[event].push(handler); - } - function once (event, handler) { - const handleAndRemove = (...args) => { - off(event, handleAndRemove); - handler(...args); - }; - events[event].push(handleAndRemove); - } +module.exports = Writable; - 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); - } +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} - function trigger (event, ...args) { - events[event].forEach(handler => handler(...args)); - } +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ - 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; +/**/ +var Duplex; +/**/ - 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); - } +Writable.WritableState = WritableState; - var item = { - data, - callback: rejectOnError ? - promiseCallback : - (callback || promiseCallback) - }; +/**/ +var internalUtil = { + deprecate: __nccwpck_require__(65278) +}; +/**/ - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } +/**/ +var Stream = __nccwpck_require__(69777); +/**/ - if (!processingScheduled) { - processingScheduled = true; - setImmediate$1(() => { - processingScheduled = false; - q.process(); - }); - } +var Buffer = __nccwpck_require__(64293).Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = __nccwpck_require__(69147); +var _require = __nccwpck_require__(844), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = __nccwpck_require__(99949)/* .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; +var errorOrDestroy = destroyImpl.errorOrDestroy; +__nccwpck_require__(44124)(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(92931); + options = options || {}; - if (rejectOnError || !callback) { - return new Promise((resolve, reject) => { - res = resolve; - rej = reject; - }) - } - } + // 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. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; - function _createCB(tasks) { - return function (err, ...args) { - numRunning -= 1; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; + // 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); - var index = workersList.indexOf(task); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } + // if _final has been called + this.finalCalled = false; - task.callback(err, ...args); + // 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 + this.finished = false; - if (err != null) { - trigger('error', err, task.data); - } - } + // has it been destroyed + this.destroyed = false; - if (numRunning <= (q.concurrency - q.buffer) ) { - trigger('unsaturated'); - } + // 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; - if (q.idle()) { - trigger('drain'); - } - q.process(); - }; - } + // 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'; - 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 - } + // 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. + this.length = 0; - 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); + // a flag to see when we're in the middle of a write. + this.writing = false; - }; + // when true all writes will be buffered until .uncork() call + this.corked = 0; - 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); - } + // 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; - numRunning += 1; + // 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; - if (q._tasks.length === 0) { - trigger('empty'); - } + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; - if (numRunning === q.concurrency) { - trigger('saturated'); - } + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - 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; - } + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; - /** - * 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; + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - var cb = args[args.length - 1]; - if (typeof cb == 'function') { - args.pop(); - } else { - cb = promiseCallback(); - } + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; - reduce$1(_functions, args, (newargs, fn, iterCb) => { - fn.apply(that, newargs.concat((err, ...nextargs) => { - iterCb(err, nextargs); - })); - }, - (err, results) => cb(err, ...results)); + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; - return cb[PROMISE_SYMBOL] - }; - } + // count buffered requests + this.bufferedRequestCount = 0; - /** - * 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()); - } + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(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 (_) {} +})(); - /** - * 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) +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +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; } - var mapLimit$1 = awaitify(mapLimit, 4); + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || __nccwpck_require__(92931); - /** - * 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]); - } - } + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. - return callback(err, result); - }); - } - var concatLimit$1 = awaitify(concatLimit, 4); + // 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. - /** - * 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); + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); - /** - * 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); + // legacy. + this.writable = true; + 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; + } + Stream.call(this); +} - /** - * 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); - }; - } +// Otherwise people can pipe Writable streams, which is just wrong. +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 + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} - 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); +// 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. +function validChunk(stream, state, chunk, cb) { + var er; + 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); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +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); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + 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; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +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; +}; +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 decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +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 (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)); - }); - }; +// 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. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; } - - /** - * 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. - - * 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 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. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; } - var detect$1 = awaitify(detect, 3); - - /** - * 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) + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +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; + 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 + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +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); } - 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) + 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); +} - var detectSeries$1 = awaitify(detectSeries, 3); +// 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. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} - 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)); - } - } - }) +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + 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; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); - /** - * 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'); - - /** - * 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; + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + 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. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +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; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - function next(err, ...args) { - if (err) return callback(err); - if (err === false) return; - results = args; - _test(...args, check); - } + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } - function check(err, truth) { - if (err) return callback(err); - if (err === false) return; - if (!truth) return callback(null, ...results); - _fn(next); + // ignore unnecessary end() calls. + 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; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +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 finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + 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(); } - - return check(null, true); + } } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } - var doWhilst$1 = awaitify(doWhilst, 3); - - /** - * 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); + // reuse the free corkReq. + 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; } - - function _withoutIndex(iteratee) { - return (value, index, callback) => iteratee(value, callback); + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; } - /** - * 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); - } + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; - 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); +/***/ 96359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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. +"use strict"; - * @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; - }; +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = __nccwpck_require__(12356); +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'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); } - - /** - * 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) + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); } - var every$1 = awaitify(every, 3); - - /** - * 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) + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + 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)); + } + }); + }); } - 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) + // 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(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); } - var everySeries$1 = awaitify(everySeries, 3); + this[kLastPromise] = promise; + return promise; + } +}, _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); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + 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(); + 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); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; - 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); - }); +/***/ }), + +/***/ 99900: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); 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"); } } +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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = __nccwpck_require__(64293), + Buffer = _require.Buffer; +var _require2 = __nccwpck_require__(31669), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _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; + while (p = p.next) ret += s + p.data; + 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; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; } - 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)); - }); + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + 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); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; } - function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - return filter(eachfn, coll, wrapAsync(iteratee), callback); + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + 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; + 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; + } + this.length -= c; + return ret; } - /** - * 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) + // Consumes a specified amount of bytes from the buffered data. + }, { + 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; + 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; + 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); + } + break; + } + ++c; + } + this.length -= c; + return ret; } - var filter$1 = awaitify(filter, 3); - /** - * 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) + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); } - var filterLimit$1 = awaitify(filterLimit, 4); + }]); + return BufferList; +}(); - /** - * 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) +/***/ }), + +/***/ 69147: +/***/ ((module) => { + +"use strict"; + + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + 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); + } } - var filterSeries$1 = awaitify(filterSeries, 3); + return this; + } - /** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - * 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)); + if (this._readableState) { + this._readableState.destroyed = true; + } - function next(err) { - if (err) return done(err); - if (err === false) return; - task(next); - } - return next(); + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + 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); } - var forever$1 = awaitify(forever, 2); + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + 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; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +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. - /** - * 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; + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; - 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]; - } - } - } +/***/ 12356: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return callback(err, result); - }); - } +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). - var groupByLimit$1 = awaitify(groupByLimit, 4); - /** - * 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) - } - /** - * 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) +var ERR_STREAM_PREMATURE_CLOSE = __nccwpck_require__(99949)/* .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); + }; +} +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; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + 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); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + 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); + } + 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); + }; +} +module.exports = eos; - /** - * 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'); +/***/ }), - /** - * 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)); - } +/***/ 8744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); +"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). - * @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) +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 _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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = __nccwpck_require__(99949)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + 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 readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + 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); + } + return readable; +} +module.exports = from; - /** - * 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; - } - /** - * 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 (hasNextTick) { - _defer$1 = process.nextTick; - } else if (hasSetImmediate) { - _defer$1 = setImmediate; - } else { - _defer$1 = fallback; - } +/***/ 50131: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var nextTick = wrap(_defer$1); +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). - var parallel = awaitify((eachfn, tasks, callback) => { - var results = isArrayLike(tasks) ? [] : {}; - 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); - /** - * 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); - } +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = __nccwpck_require__(99949)/* .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; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __nccwpck_require__(12356); + 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; - /** - * 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); - } + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + 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); +} +module.exports = pipeline; - /** - * 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() - */ +/***/ }), - /** - * 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); - } +/***/ 844: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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; - } +"use strict"; - get length() { - return this.heap.length; - } - empty () { - this.heap = []; - return this; - } +var ERR_INVALID_OPT_VALUE = __nccwpck_require__(99949)/* .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 getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + 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); + } + return Math.floor(hwm); + } - percUp(index) { - let p; + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; - 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; +/***/ }), - index = p; - } - } +/***/ 69777: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - percDown(index) { - let l; +module.exports = __nccwpck_require__(92413); - 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 (smaller(this.heap[index], this.heap[l])) { - break; - } +/***/ }), - let t = this.heap[index]; - this.heap[index] = this.heap[l]; - this.heap[l] = t; +/***/ 64043: +/***/ ((module, exports, __nccwpck_require__) => { - index = l; - } - } +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__(70661); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(7631); + exports.Duplex = __nccwpck_require__(92931); + exports.Transform = __nccwpck_require__(53937); + exports.PassThrough = __nccwpck_require__(61894); + exports.finished = __nccwpck_require__(12356); + exports.pipeline = __nccwpck_require__(50131); +} - push(node) { - node.pushCount = ++this.pushCount; - this.heap.push(node); - this.percUp(this.heap.length-1); - } - unshift(node) { - return this.heap.push(node); - } +/***/ }), - shift() { - let [top] = this.heap; +/***/ 99348: +/***/ ((module) => { - this.heap[0] = this.heap[this.heap.length-1]; - this.heap.pop(); - this.percDown(0); +// Copyright 2011 Mark Cavage All rights reserved. - return top; - } - toArray() { - return [...this]; - } +module.exports = { - *[Symbol.iterator] () { - for (let i = 0; i < this.heap.length; i++) { - yield this.heap[i].data; - } - } + newInvalidAsn1Error: function (msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } - 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++; - } - } +}; - this.heap.splice(j); - for (let i = parent(this.heap.length-1); i >= 0; i--) { - this.percDown(i); - } +/***/ }), - return this; - } - } +/***/ 194: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function leftChi(i) { - return (i<<1)+1; - } +// Copyright 2011 Mark Cavage All rights reserved. - function parent(i) { - return ((i+1)>>1)-1; - } +var errors = __nccwpck_require__(99348); +var types = __nccwpck_require__(42473); - function smaller(x, y) { - if (x.priority !== y.priority) { - return x.priority < y.priority; - } - else { - return x.pushCount < y.pushCount; - } - } +var Reader = __nccwpck_require__(20290); +var Writer = __nccwpck_require__(43200); - /** - * 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(); +// --- Exports - // 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()); - } +module.exports = { - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority, - callback - }; + Reader: Reader, - q._tasks.push(item); - } + Writer: Writer - setImmediate$1(q.process); - }; +}; - // Remove unshift function - delete q.unshift; +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]; +} - return q; - } - /** - * 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); +/***/ 20290: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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); - } +// Copyright 2011 Mark Cavage All rights reserved. - /** - * 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); - }); +var assert = __nccwpck_require__(42357); +var Buffer = __nccwpck_require__(15118).Buffer; - return _fn.apply(this, args); - }); - } +var ASN1 = __nccwpck_require__(42473); +var errors = __nccwpck_require__(99348); - /** - * 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; - } - function reject(eachfn, arr, _iteratee, callback) { - const iteratee = wrapAsync(_iteratee); - return _filter(eachfn, arr, (value, cb) => { - iteratee(value, (err, v) => { - cb(err, !v); - }); - }, callback); - } +// --- Globals - /** - * 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); +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - /** - * 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; - } - } +// --- API - /** - * 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; +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) + throw new TypeError('data must be a node Buffer'); - function retry(opts, task, callback) { - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) - }; + this._buf = data; + this._size = data.length; - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || promiseCallback(); - task = opts; - } else { - parseTimes(options, opts); - callback = callback || promiseCallback(); - } + // These hold the "current" state + this._len = 0; + this._offset = 0; +} - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function () { return (this._len); } +}); - var _task = wrapAsync(task); +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function () { return (this._offset); } +}); - 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); - } - }); - } +Object.defineProperty(Reader.prototype, 'remain', { + get: function () { return (this._size - this._offset); } +}); - retryAttempt(); - return callback[PROMISE_SYMBOL] - } +Object.defineProperty(Reader.prototype, 'buffer', { + get: function () { return (this._buf.slice(this._offset)); } +}); - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); +/** + * 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; - 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"); - } - } + var b = this._buf[this._offset] & 0xff; - /** - * 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); - } + if (!peek) + this._offset += 1; - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); + return b; +}; - return callback[PROMISE_SYMBOL] - }); - } - /** - * 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); - } +Reader.prototype.peek = function () { + return this.readByte(true); +}; - /** - * 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); - /** - * 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); +/** + * 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; - /** - * 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); + if (offset >= this._size) + return null; - /** - * 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)); - }); + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) + return null; - 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); + if ((lenB & 0x80) === 0x80) { + lenB &= 0x7f; - /** - * 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); + if (lenB === 0) + throw newInvalidAsn1Error('Indefinite length not supported'); - return initialParams((args, callback) => { - var timedOut = false; - var timer; + if (lenB > 4) + throw newInvalidAsn1Error('encoding too long'); - 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); - } + if (this._size - offset < lenB) + return null; - args.push((...cbArgs) => { - if (!timedOut) { - callback(...cbArgs); - clearTimeout(timer); - } - }); + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn(...args); - }); - } + } else { + // Wasn't a variable length + this._len = lenB; + } - function range(size) { - var result = Array(size); - while (size--) { - result[size] = size; - } - return result; - } + return offset; +}; - /** - * 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) - } +/** + * 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)); - /** - * 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) - } + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; - /** - * 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); + this._offset = o; + return seq; +}; - 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); +Reader.prototype.readInt = function () { + return this._readTag(ASN1.Integer); +}; - if (args.length < 2) { - [result] = args; - } else { - result = args; - } - error = err; - taskCb(err ? null : {}); - }); - }, () => callback(error, result)); - } - var tryEach$1 = awaitify(tryEach); +Reader.prototype.readBoolean = function () { + return (this._readTag(ASN1.Boolean) === 0 ? false : true); +}; - /** - * 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); - }; - } - /** - * 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 = []; +Reader.prototype.readEnumeration = function () { + return this._readTag(ASN1.Enumeration); +}; - function next(err, ...rest) { - if (err) return callback(err); - results = rest; - if (err === false) return; - _test(check); - } - function check(err, truth) { - if (err) return callback(err); - if (err === false) return; - if (!truth) return callback(null, ...results); - _fn(next); - } +Reader.prototype.readString = function (tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; - return _test(check); - } - var whilst$1 = awaitify(whilst, 3); + var b = this.peek(); + if (b === null) + return null; - /** - * 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); - } + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - /** - * 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; + var o = this.readLength(this._offset + 1); // stored in `length` - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - task(...args, onlyOnce(next)); - } + if (o === null) + return null; - function next(err, ...args) { - if (err === false) return - if (err || taskIndex === tasks.length) { - return callback(err, ...args); - } - nextTask(args); - } + if (this.length > this._size - o) + return null; - nextTask([]); - } + this._offset = o; - var waterfall$1 = awaitify(waterfall); + if (this.length === 0) + return retbuf ? Buffer.alloc(0) : ''; - /** - * 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 str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; - 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 - }; + return retbuf ? str : str.toString('utf8'); +}; - 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; +Reader.prototype.readOID = function (tag) { + if (!tag) + tag = ASN1.OID; - Object.defineProperty(exports, '__esModule', { value: true }); + var b = this.readString(tag, true); + if (b === null) + return null; -}))); + var values = []; + var value = 0; + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 0xff; -/***/ }), + value <<= 7; + value += byte & 0x7f; + if ((byte & 0x80) === 0) { + values.push(value); + value = 0; + } + } -/***/ 14812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + value = values.shift(); + values.unshift(value % 40); + values.unshift((value / 40) >> 0); -module.exports = -{ - parallel : __nccwpck_require__(8210), - serial : __nccwpck_require__(50445), - serialOrdered : __nccwpck_require__(3578) + return values.join('.'); }; -/***/ }), +Reader.prototype._readTag = function (tag) { + assert.ok(tag !== undefined); -/***/ 1700: -/***/ ((module) => { + var b = this.peek(); -// API -module.exports = abort; + if (b === null) + return null; -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - // reset leftover jobs - state.jobs = {}; -} + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; -/** - * 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](); - } -} + if (this.length > 4) + throw newInvalidAsn1Error('Integer too long: ' + this.length); + if (this.length > this._size - o) + return null; + this._offset = o; -/***/ }), + var fb = this._buf[this._offset]; + var value = 0; -/***/ 72794: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= (this._buf[this._offset++] & 0xff); + } -var defer = __nccwpck_require__(15295); + if ((fb & 0x80) === 0x80 && i !== 4) + value -= (1 << (i * 8)); -// API -module.exports = async; + return value >> 0; +}; -/** - * 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; - // check if async happened - defer(function() { isAsync = true; }); - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; -} +// --- Exported API + +module.exports = Reader; /***/ }), -/***/ 15295: +/***/ 42473: /***/ ((module) => { -module.exports = defer; +// Copyright 2011 Mark Cavage All rights reserved. -/** - * 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 (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } -} +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 +}; /***/ }), -/***/ 9023: +/***/ 43200: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var async = __nccwpck_require__(72794) - , abort = __nccwpck_require__(1700) - ; +// Copyright 2011 Mark Cavage All rights reserved. -// API -module.exports = iterate; +var assert = __nccwpck_require__(42357); +var Buffer = __nccwpck_require__(15118).Buffer; +var ASN1 = __nccwpck_require__(42473); +var errors = __nccwpck_require__(99348); -/** - * 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; - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; - } +// --- Globals - // clean up jobs - delete state.jobs[key]; +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - 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 DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 +}; - // return salvaged results - callback(error, state.results); + +// --- Helpers + +function merge(from, to) { + assert.ok(from); + assert.equal(typeof (from), 'object'); + assert.ok(to); + assert.equal(typeof (to), 'object'); + + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function (key) { + if (to[key]) + return; + + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); }); + + return to; } -/** - * 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; - // 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 aborter; +// --- API + +function Writer(options) { + options = merge(DEFAULT_OPTS, options || {}); + + this._buf = Buffer.alloc(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; + + // A list of offsets in the buffer where we need to insert + // sequence tag/len pairs. + this._seq = []; } +Object.defineProperty(Writer.prototype, 'buffer', { + get: function () { + if (this._seq.length) + throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); -/***/ }), + return (this._buf.slice(0, this._offset)); + } +}); -/***/ 42474: -/***/ ((module) => { +Writer.prototype.writeByte = function (b) { + if (typeof (b) !== 'number') + throw new TypeError('argument must be a Number'); -// API -module.exports = state; + this._ensure(1); + this._buf[this._offset++] = b; +}; -/** - * 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 - } - ; - 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]); - }); +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 sz = 4; + + while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && + (sz > 1)) { + sz--; + i <<= 8; } - return initState; -} + if (sz > 4) + throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; -/***/ }), + while (sz-- > 0) { + this._buf[this._offset++] = ((i & 0xff000000) >>> 24); + i <<= 8; + } -/***/ 37942: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +}; -var abort = __nccwpck_require__(1700) - , async = __nccwpck_require__(72794) - ; -// API -module.exports = terminator; +Writer.prototype.writeNull = function () { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; -/** - * 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; + +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; + + return this.writeInt(i, tag); +}; + + +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; + + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; + + +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; + + 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; } +}; - // fast forward iteration index - this.index = this.size; - // abort jobs - abort(this); +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'); - // send back results we have so far - async(callback)(null, this.results); -} + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; -/***/ }), +Writer.prototype.writeStringArray = function (strings) { + if ((!strings instanceof Array)) + throw new TypeError('argument must be an Array[String]'); -/***/ 8210: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var self = this; + strings.forEach(function (s) { + self.writeString(s); + }); +}; -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; +// 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; -// Public API -module.exports = parallel; + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error('argument is not a valid OID string'); -/** - * 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); + 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); + } + } - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } + 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)); + }); - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); + var self = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function (b) { + self.writeByte(b); + }); +}; - state.index++; + +Writer.prototype.writeLength = function (len) { + if (typeof (len) !== 'number') + throw new TypeError('argument must be a Number'); + + this._ensure(4); + + 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)'); } +}; - return terminator.bind(state, callback); -} +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; +}; -/***/ }), -/***/ 50445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Writer.prototype.endSequence = function () { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; -var serialOrdered = __nccwpck_require__(3578); + 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'); + } +}; -// Public API -module.exports = serial; -/** - * 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); -} +Writer.prototype._shift = function (start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); + + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; +}; + +Writer.prototype._ensure = function (len) { + assert.ok(len); + + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) + sz += len; + + var buf = Buffer.alloc(sz); + + this._buf.copy(buf, 0, 0, this._offset); + this._buf = buf; + this._size = sz; + } +}; + + + +// --- Exported API + +module.exports = Writer; /***/ }), -/***/ 3578: +/***/ 80970: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; +// Copyright 2011 Mark Cavage All rights reserved. -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; +// If you have no idea what ASN.1 or BER is, see this: +// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc -/** - * 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); +var Ber = __nccwpck_require__(194); - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; - } - state.index++; - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; - } +// --- Exported API - // done here - callback(null, state.results); - }); +module.exports = { - return terminator.bind(state, callback); -} + Ber: Ber, -/* - * -- Sort methods - */ + BerReader: Ber.Reader, -/** - * 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; -} + BerWriter: Ber.Writer -/** - * 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); -} +}; /***/ }), -/***/ 96342: +/***/ 66631: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. -/*! - * 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. - */ +var assert = __nccwpck_require__(42357); +var Stream = __nccwpck_require__(92413).Stream; +var util = __nccwpck_require__(31669); -/** - * Module dependencies. - */ -var crypto = __nccwpck_require__(76417) - , parse = __nccwpck_require__(78835).parse - ; +///--- Globals -/** - * Valid keys. - */ +/* 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}$/; -var keys = - [ 'acl' - , 'location' - , 'logging' - , 'notification' - , 'partNumber' - , 'policy' - , 'requestPayment' - , 'torrent' - , 'uploadId' - , 'uploads' - , 'versionId' - , 'versioning' - , 'versions' - , 'website' - ] -/** - * Return an "Authorization" header value with the given `options` - * in the form of "AWS :" - * - * @param {Object} options - * @return {String} - * @api private - */ +///--- Internal -function authorization (options) { - return 'AWS ' + options.key + ':' + sign(options) +function _capitalize(str) { + return (str.charAt(0).toUpperCase() + str.slice(1)); } -module.exports = authorization -module.exports.authorization = authorization +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 + }); +} -/** - * Simple HMAC-SHA1 Wrapper - * - * @param {Object} options - * @return {String} - * @api private - */ +function _getClass(arg) { + return (Object.prototype.toString.call(arg).slice(8, -1)); +} -function hmacSha1 (options) { - return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +function noop() { + // Why even bother with asserts? } -module.exports.hmacSha1 = hmacSha1 -/** - * Create a base64 sha1 HMAC for `options`. - * - * @param {Object} options - * @return {String} - * @api private - */ +///--- Exports -function sign (options) { - options.message = stringToSign(options) - return hmacSha1(options) -} -module.exports.sign = sign - -/** - * Create a base64 sha1 HMAC for `options`. - * - * Specifically to be used with S3 presigned URLs - * - * @param {Object} options - * @return {String} - * @api private - */ - -function signQuery (options) { - options.message = queryStringToSign(options) - return hmacSha1(options) -} -module.exports.signQuery= signQuery - -/** - * Return a string for sign() with the given `options`. - * - * Spec: - * - * \n - * \n - * \n - * \n - * [headers\n] - * - * - * @param {Object} options - * @return {String} - * @api private - */ +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' + } +}; -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 +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; -/** - * 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 - */ + /* re-export standard assert */ + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function (arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; + } -function queryStringToSign (options){ - return 'GET\n\n\n' + options.date + '\n' + options.resource -} -module.exports.queryStringToSign = queryStringToSign + /* 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); + } + }; + }); -/** - * Perform the following: - * - * - ignore non-amazon headers - * - lowercase fields - * - sort lexicographically - * - trim whitespace between ":" - * - join with newline - * - * @param {Object} headers - * @return {String} - * @api private - */ + /* 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); + } + }; + }); -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 + /* 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); + } + } + }; + }); -/** - * Perform the following: - * - * - ignore non sub-resources - * - sort lexicographically - * - * @param {String} resource - * @return {String} - * @api private - */ + /* 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); + } + } + }; + }); -function canonicalizeResource (resource) { - var url = parse(resource, true) - , path = url.pathname - , buf = [] - ; + /* 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]; + }); - 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) - }) + /* export ourselves (for unit tests _only_) */ + out._setExports = _setExports; - return path + (buf.length ? '?' + buf.sort().join('&') : '') + return out; } -module.exports.canonicalizeResource = canonicalizeResource - -/***/ }), +module.exports = _setExports(process.env.NODE_NDEBUG); -/***/ 16071: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var aws4 = exports, - url = __nccwpck_require__(78835), - querystring = __nccwpck_require__(71191), - crypto = __nccwpck_require__(76417), - lru = __nccwpck_require__(74225), - credentialsCache = lru(1000) +/***/ }), -// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html +/***/ 57888: +/***/ (function(__unused_webpack_module, exports) { -function hmac(key, string, encoding) { - return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) -} +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; -function hash(string, encoding) { - return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) -} + /** + * 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); + } -// 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() - }) -} + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } -function encodeRfc3986Full(str) { - return encodeRfc3986(encodeURIComponent(str)) -} + /* istanbul ignore file */ -// 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, -} + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; -// request: { path | body, [host], [method], [headers], [service], [region] } -// credentials: { accessKeyId, secretAccessKey, [sessionToken] } -function RequestSigner(request, credentials) { + function fallback(fn) { + setTimeout(fn, 0); + } - if (typeof request === 'string') request = url.parse(request) + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } - var headers = request.headers = (request.headers || {}), - hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) + var _defer; - this.request = request - this.credentials = credentials || this.defaultCredentials() + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } else { + _defer = fallback; + } - this.service = request.service || hostParts[0] || '' - this.region = request.region || hostParts[1] || 'us-east-1' + var setImmediate$1 = wrap(_defer); - // SES uses a different domain from the service name - if (this.service === 'email') this.service = 'ses' + /** + * 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) + } + } - if (!request.method && request.body) - request.method = 'POST' + 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); + } + }); + } - if (!headers.Host && !headers.host) { - headers.Host = request.hostname || request.host || this.createHost() + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); + } - // 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 + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } - this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' -} + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } -RequestSigner.prototype.matchHost = function(host) { - var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) - var hostParts = (match || []).slice(1, 3) + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } - // 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() + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } - 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 - } + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; } - } - return hostParts -} + // 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) + } -// 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 + 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 ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] - .indexOf(this.service) >= 0 -} + return awaitable + } -RequestSigner.prototype.createHost = function() { - var region = this.isSingleRegion() ? '' : '.' + this.region, - subdomain = this.service === 'ses' ? 'email' : this.service - return subdomain + region + '.amazonaws.com' -} + 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; + }; + } -RequestSigner.prototype.prepareRequest = function() { - this.parsePath() + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); - var request = this.request, headers = request.headers, query + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } - if (request.signQuery) { + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } - this.parsedPath.query = query = this.parsedPath.query || {} + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; - if (this.credentials.sessionToken) - query['X-Amz-Security-Token'] = this.credentials.sessionToken + 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 + } - if (this.service === 's3' && !query['X-Amz-Expires']) - query['X-Amz-Expires'] = 86400 + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } - if (query['X-Amz-Date']) - this.datetime = query['X-Amz-Date'] - else - query['X-Amz-Date'] = this.getDateTime() + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } - query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' - query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() - query['X-Amz-SignedHeaders'] = this.signedHeaders() + 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}; + } + } - } else { + 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; + }; + } - 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' + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } - if (request.body && !headers['Content-Length'] && !headers['content-length']) - headers['Content-Length'] = Buffer.byteLength(request.body) + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } - if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) - headers['X-Amz-Security-Token'] = this.credentials.sessionToken + 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); + }; + } - if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) - headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; - 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() - } + 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); + } - delete headers.Authorization - delete headers.authorization - } -} + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) -RequestSigner.prototype.sign = function() { - if (!this.parsedPath) this.prepareRequest() + if (err === false) { + done = true; + canceled = true; + return + } - if (this.request.signQuery) { - this.parsedPath.query['X-Amz-Signature'] = this.signature() - } else { - this.request.headers.Authorization = this.authHeader() - } + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } - this.request.path = this.formatPath() + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } - return this.request -} + replenish(); + } -RequestSigner.prototype.getDateTime = function() { - if (!this.datetime) { - var headers = this.request.headers, - date = new Date(headers.Date || headers.date || new Date) + 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; - this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') + 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(); + } + } - // 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 -} + 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; + } -RequestSigner.prototype.getDate = function() { - return this.getDateTime().substr(0, 8) -} + replenish(); + }; + }; -RequestSigner.prototype.authHeader = function() { - return [ - 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), - 'SignedHeaders=' + this.signedHeaders(), - 'Signature=' + this.signature(), - ].join(', ') -} + /** + * 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); + } -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') -} + var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); -RequestSigner.prototype.stringToSign = function() { - return [ - 'AWS4-HMAC-SHA256', - this.getDateTime(), - this.credentialString(), - hash(this.canonicalString(), 'hex'), - ].join('\n') -} + // 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); + } -RequestSigner.prototype.canonicalString = function() { - if (!this.parsedPath) this.prepareRequest() + 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); + } + } - 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 + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } - 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') - } + // 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); + } - 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, '/') - } + /** + * 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); + } - return [ - this.request.method || 'GET', - pathStr, - queryStr, - this.canonicalHeaders() + '\n', - this.signedHeaders(), - bodyHash, - ].join('\n') -} + var eachOf$1 = awaitify(eachOf, 3); -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('/') -} + /** + * 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); -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, - } -} + /** + * 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); -RequestSigner.prototype.parsePath = function() { - var path = this.request.path || '/' + /** + * 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); - // 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)) - } + /** + * 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); - var queryIx = path.indexOf('?'), - query = null + /** + * 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); - if (queryIx >= 0) { - query = querystring.parse(path.slice(queryIx + 1)) - path = path.slice(0, queryIx) - } + const PROMISE_SYMBOL = Symbol('promiseCallback'); - this.parsedPath = { - path: path, - query: query, - } -} + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } -RequestSigner.prototype.formatPath = function() { - var path = this.parsedPath.path, - query = this.parsedPath.query + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); - if (!query) return path + return callback + } - // Services don't support empty query string keys - if (query[''] != null) delete query[''] + /** + * 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; + } - return path + '?' + encodeRfc3986(querystring.stringify(query)) -} + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; -aws4.RequestSigner = RequestSigner + var listeners = Object.create(null); -aws4.sign = function(request, credentials) { - return new RequestSigner(request, credentials).sign() -} + var readyTasks = []; + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; -/***/ }), + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } -/***/ 74225: -/***/ ((module) => { + 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; -module.exports = function(size) { - return new LruCache(size) -} + 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); + } + }); + }); + }); -function LruCache(size) { - this.capacity = size | 0 - this.map = Object.create(null) - this.list = new DoublyLinkedList() -} + checkForDeadlocks(); + processQueue(); -LruCache.prototype.get = function(key) { - var node = this.map[key] - if (node == null) return undefined - this.used(node) - return node.val -} + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } -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 -} + 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(); + } -LruCache.prototype.used = function(node) { - this.list.moveToFront(node) -} + } -LruCache.prototype.prune = function() { - var node = this.list.pop() - if (node != null) { - delete this.map[node.key] - this.capacity++ - } -} + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + taskListeners.push(fn); + } -function DoublyLinkedList() { - this.firstNode = null - this.lastNode = null -} + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } -DoublyLinkedList.prototype.moveToFront = function(node) { - if (this.firstNode == node) return - this.remove(node) + function runTask(key, task) { + if (hasError) return; - 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 - } -} + 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); + } + }); -DoublyLinkedList.prototype.pop = function() { - var lastNode = this.lastNode - if (lastNode != null) { - this.remove(lastNode) - } - return lastNode -} + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } -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 - } -} + 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); + } + }); + } + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } -function DoublyLinkedNode(key, val) { - this.key = key - this.val = val - this.prev = null - this.next = null -} + 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 callback[PROMISE_SYMBOL] + } -/***/ }), + 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; -/***/ 96545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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()); + } -module.exports = __nccwpck_require__(52618); + /** + * 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); -/***/ 68104: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); -"use strict"; + 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."); + } + // remove callback param + if (!fnIsAsync) params.pop(); -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); + newTasks[key] = params.concat(newTask); + } -var isHttps = /https:?/; + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); -/** - * - * @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; + return auto(newTasks, callback); + } - // 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; - } + // 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; + } - // 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); - }; -} + 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; -/*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; + node.prev = node.next = null; + this.length -= 1; + return node; + } - // 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; - } + empty () { + while(this.head) this.shift(); + return this; + } - 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 - )); - } + 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; + } - // Add Content-Length header if data exists - headers['Content-Length'] = data.length; - } + 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; + } - // HTTP basic authentication - var auth = undefined; - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - auth = username + ':' + password; - } + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } - // Parse url - var fullPath = buildFullPath(config.baseURL, config.url); - var parsed = url.parse(fullPath); - var protocol = parsed.protocol || 'http:'; + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } - if (!auth && parsed.auth) { - var urlAuth = parsed.auth.split(':'); - var urlUsername = urlAuth[0] || ''; - var urlPassword = urlAuth[1] || ''; - auth = urlUsername + ':' + urlPassword; - } + shift() { + return this.head && this.removeLink(this.head); + } - if (auth) { - delete headers.Authorization; - } + pop() { + return this.tail && this.removeLink(this.tail); + } - var isHttpsRequest = isHttps.test(protocol); - var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + toArray() { + return [...this] + } - 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 - }; + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname; - options.port = parsed.port; + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } } - 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; + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } - if (noProxyEnv) { - var noProxy = noProxyEnv.split(',').map(function trim(s) { - return s.trim(); - }); + function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } - 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; - } + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; - return parsed.hostname === proxyElement; - }); + function on (event, handler) { + events[event].push(handler); } - if (shouldProxy) { - proxy = { - host: parsedProxyUrl.hostname, - port: parsedProxyUrl.port, - protocol: parsedProxyUrl.protocol - }; - - if (parsedProxyUrl.auth) { - var proxyUrlAuth = parsedProxyUrl.auth.split(':'); - proxy.auth = { - username: proxyUrlAuth[0], - password: proxyUrlAuth[1] + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); }; - } + events[event].push(handleAndRemove); } - } - } - - if (proxy) { - options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); - setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); - } - 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; - } + 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); + } - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; - } + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } - // Create the request - var req = transport.request(options, function handleResponse(res) { - if (req.aborted) return; + 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; - // uncompress the response body transparently if required - var stream = res; + 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 the last request in case of redirects - var lastRequest = res.req || req; + var item = { + data, + callback: rejectOnError ? + promiseCallback : + (callback || promiseCallback) + }; + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } - // 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 (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } } - } - var response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: res.headers, - config: config, - request: lastRequest - }; + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; - if (config.responseType === 'stream') { - response.data = stream; - settle(resolve, reject, response); - } else { - var responseBuffer = []; - stream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; - // 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)); - } - }); - - stream.on('error', function handleStreamError(err) { - if (req.aborted) return; - reject(enhanceError(err, config, null, lastRequest)); - }); - - 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); - } - } - - response.data = responseData; - settle(resolve, reject, response); - }); - } - }); - - // 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)); - }); + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } - // 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)); - }); - } + task.callback(err, ...args); - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (req.aborted) return; + if (err != null) { + trigger('error', err, task.data); + } + } - req.abort(); - reject(cancel); - }); - } + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } - // 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); - } - }); -}; + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + 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 + } -/***/ }), + 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); -/***/ 3454: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + }; -"use strict"; + 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); + } + numRunning += 1; -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); + if (q._tasks.length === 0) { + trigger('empty'); + } -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; + if (numRunning === q.concurrency) { + trigger('saturated'); + } - if (utils.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it + 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; } - var request = new XMLHttpRequest(); - - // 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); + /** + * 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